List of usage examples for android.location LocationListener LocationListener
LocationListener
From source file:com.temboo.example.FoursquareConnectedActivity.java
/** * onCreate is called by Android when the activity is first created. *//*from w w w .j a v a 2s.c o m*/ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Initialize the UI with the "connected mode" layout (defined in /res/layout/foursquare_connected.xml) setContentView(R.layout.foursquare_connected); // Obtain a reference to the "current venue" textview currentVenueTextView = (TextView) findViewById(R.id.foursquareVenueField); // Initiate the Temboo session try { session = new MyTemboo(TEMBOO_APPKEY_NAME, TEMBOO_APPKEY); } catch (Exception e) { currentVenueTextView.setText("Uh-oh! Something has gone horribly wrong."); Log.e("TEMBOO", "Error starting Temboo session.", e); } // Debug: display the Fourquare Oauth token retrieved by FoursquareOauthActivity Toast.makeText(FoursquareConnectedActivity.this, "Successfully connected to Foursquare. Oauth token: " + FOURSQUARE_OAUTH_TOKEN, Toast.LENGTH_SHORT) .show(); // Obtain a reference to the Android LocationManager, which is (surprisingly) responsible for managing GPS/location data LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // Get and store the last known location currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); // Register a listener with the Location Manager to receive location updates. Currently, this is configured // to request GPS updates every 3 minutes, with a minimum location-differential of 3 meters per update. // See http://developer.android.com/reference/android/location/LocationManager.html locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 180000, 3, new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } // When the location changes, store the current location in the parent activity @Override public void onLocationChanged(Location location) { currentLocation = location; } }); // Attach the "lookup location" button click handler Button lookupButton = (Button) findViewById(R.id.getVenue); lookupButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { getFoursquareVenueForCurrentLocation(); } catch (Exception e) { Log.e("TEMBOO", "Error performing Foursquare venue lookup", e); Toast.makeText(FoursquareConnectedActivity.this, "Error performing foursquare venue lookup! " + e.getMessage(), Toast.LENGTH_SHORT) .show(); } } }); // Attach the "Foursquare checkin" button click handler Button checkinButton = (Button) findViewById(R.id.doFoursquareCheckin); checkinButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { doFoursquareCheckin(); } catch (Exception e) { Log.e("TEMBOO", "Error performing Foursquare checkin", e); Toast.makeText(FoursquareConnectedActivity.this, "Error performing foursquare checkin! " + e.getMessage(), Toast.LENGTH_SHORT).show(); } } }); }
From source file:heartware.com.heartware_master.FB_PickerActivity.java
@Override protected void onStart() { super.onStart(); if (FRIEND_PICKER.equals(getIntent().getData())) { try {/*from w w w. j a v a2s .c o m*/ friendPickerFragment.loadData(false); } catch (Exception ex) { onError(ex); } } else if (PLACE_PICKER.equals(getIntent().getData())) { try { Location location = null; Criteria criteria = new Criteria(); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); String bestProvider = locationManager.getBestProvider(criteria, false); if (bestProvider != null) { location = locationManager.getLastKnownLocation(bestProvider); if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) { locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { boolean updateLocation = true; Location prevLocation = placePickerFragment.getLocation(); if (prevLocation != null) { updateLocation = location.distanceTo(prevLocation) >= LOCATION_CHANGE_THRESHOLD; } if (updateLocation) { placePickerFragment.setLocation(location); placePickerFragment.loadData(true); } } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD, locationListener, Looper.getMainLooper()); } } if (location == null) { String model = Build.MODEL; if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) { // this may be the emulator, pretend we're in an exotic place location = TEMPE_AZ_LOCATION; } location = TEMPE_AZ_LOCATION; // @TODO HARDCODED location } if (location != null) { location = TEMPE_AZ_LOCATION; placePickerFragment.setLocation(location); placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS); placePickerFragment.setSearchText(SEARCH_TEXT); placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT); placePickerFragment.loadData(false); } else { onError(getResources().getString(R.string.no_location_error), true); } } catch (Exception ex) { onError(ex); } } }
From source file:com.upmoon.alexanderbean.barcrawlr.fragments.PlanSelectorFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_plan_selector, container, false); /**/*from w w w. jav a 2 s . c o m*/ * Widgets here */ mLeftFAB = (FloatingActionButton) v.findViewById(R.id.connect_fab); mLeftFAB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder buildo = new AlertDialog.Builder(getActivity()); final EditText inp1 = new EditText(getActivity()); inp1.setInputType(InputType.TYPE_CLASS_TEXT); buildo.setTitle("Join Active Plan"); buildo.setView(inp1); buildo.setPositiveButton("Join", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface diag, int which) { AlertDialog.Builder buildo = new AlertDialog.Builder(getActivity()); final EditText inp2 = new EditText(getActivity()); inp2.setInputType(InputType.TYPE_CLASS_TEXT); buildo.setTitle("Choose a username"); buildo.setView(inp2); buildo.setPositiveButton("Join", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface diag, int which) { if (!inp2.getText().toString().equals("")) { GetPlan gp = new GetPlan(); gp.execute(inp1.getText().toString(), inp2.getText().toString()); } } }); buildo.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface diag, int which) { diag.cancel(); } }); buildo.show(); } }); buildo.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface diag, int which) { diag.cancel(); } }); buildo.show(); } }); mRightFAB = (FloatingActionButton) v.findViewById(R.id.new_plan_fab); mRightFAB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder buildo = new AlertDialog.Builder(getActivity()); final EditText inp = new EditText(getActivity()); inp.setInputType(InputType.TYPE_CLASS_TEXT); buildo.setTitle("Create New Plan"); buildo.setView(inp); buildo.setPositiveButton("Create", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface diag, int which) { PlanLoader pl = new PlanLoader(getActivity()); String planName = inp.getText().toString(); if (!planName.equals("") && pl.planNameExists(planName)) { Toast.makeText(getActivity(), "Invalid Name or name exists", Toast.LENGTH_SHORT).show(); } else { Plan plan = new Plan(); plan.setName(inp.getText().toString()); CurrentPlan.getInstance().setPlan(plan); Intent intent = new Intent(getActivity(), PlanCreator.class); startActivity(intent); } } }); buildo.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface diag, int which) { } }); buildo.show(); } }); //RecyclerView mAdapter = new PlanAdapter(); mRecyclerView = (RecyclerView) v.findViewById(R.id.gol_recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); mRecyclerView.setAdapter(mAdapter); /** * Load in plan data */ PlanListChanged(); /** * location */ locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location provider. updateLocation(location.getLongitude(), location.getLatitude()); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; return v; }
From source file:com.wipro.sa349342.wmar.AbstractArchitectCamActivity.java
/** Called when the activity is first created. */ @SuppressLint("NewApi") @Override/*from ww w . j ava 2 s. c om*/ public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* pressing volume up/down should cause music volume changes */ this.setVolumeControlStream(AudioManager.STREAM_MUSIC); /* set samples content view */ this.setContentView(this.getContentViewId()); this.setTitle(this.getActivityTitle()); View mapFrag = findViewById(R.id.map); if (this.isMapPanelRequired()) { mapFrag.setVisibility(View.VISIBLE); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(map); mapFragment.getMapAsync(AbstractArchitectCamActivity.this); } else { mapFrag.setVisibility(View.GONE); } /* * this enables remote debugging of a WebView on Android 4.4+ when debugging = true in AndroidManifest.xml * If you get a compile time error here, ensure to have SDK 19+ used in your ADT/Eclipse. * You may even delete this block in case you don't need remote debugging or don't have an Android 4.4+ device in place. * Details: https://developers.google.com/chrome-developer-tools/docs/remote-debugging */ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (0 != (getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) { WebView.setWebContentsDebuggingEnabled(true); } } /* set AR-view for life-cycle notifications etc. */ this.architectView = (ArchitectView) this.findViewById(this.getArchitectViewId()); /* pass SDK key if you have one, this one is only valid for this package identifier and must not be used somewhere else */ final StartupConfiguration config = new StartupConfiguration(this.getWikitudeSDKLicenseKey(), this.getFeatures(), this.getCameraPosition()); try { /* first mandatory life-cycle notification */ this.architectView.onCreate(config); } catch (RuntimeException rex) { this.architectView = null; Toast.makeText(getApplicationContext(), "can't create Architect View", Toast.LENGTH_SHORT).show(); Log.e(this.getClass().getName(), "Exception in ArchitectView.onCreate()", rex); } // set accuracy listener if implemented, you may e.g. show calibration prompt for compass using this listener this.sensorAccuracyListener = this.getSensorAccuracyListener(); // set urlListener, any calls made in JS like "document.location = 'architectsdk://foo?bar=123'" is forwarded to this listener, use this to interact between JS and native Android activity/fragment this.urlListener = this.getUrlListener(); // register valid urlListener in architectView, ensure this is set before content is loaded to not miss any event if (this.urlListener != null && this.architectView != null) { this.architectView.registerUrlListener(this.getUrlListener()); } if (hasGeo()) { // listener passed over to locationProvider, any location update is handled here this.locationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(final Location location) { // forward location updates fired by LocationProvider to architectView, you can set lat/lon from any location-strategy if (location != null) { // sore last location as member, in case it is needed somewhere (in e.g. your adjusted project) AbstractArchitectCamActivity.this.lastKnownLocaton = location; if (AbstractArchitectCamActivity.this.architectView != null) { // check if location has altitude at certain accuracy level & call right architect method (the one with altitude information) if (location.hasAltitude() && location.hasAccuracy() && location.getAccuracy() < 7) { AbstractArchitectCamActivity.this.architectView.setLocation(location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getAccuracy()); } else { AbstractArchitectCamActivity.this.architectView.setLocation(location.getLatitude(), location.getLongitude(), location.hasAccuracy() ? location.getAccuracy() : 1000); } } // currentLocationMarker(location); } } }; // locationProvider used to fetch user position this.locationProvider = getLocationProvider(this.locationListener); } else { this.locationProvider = null; this.locationListener = null; } }
From source file:com.microsoft.band.sdksample.SensorsFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_sensors, container, false); senSensorManager1 = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); senSensorManager2 = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); senGyroscope = senSensorManager1.getDefaultSensor(Sensor.TYPE_GYROSCOPE); senSensorManager1.registerListener(this, senGyroscope, SensorManager.SENSOR_DELAY_NORMAL); senAccelerometer = senSensorManager2.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); senSensorManager2.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); mTableAcc = (TableLayout) rootView.findViewById(R.id.tableAcc); mTableAcc.setVisibility(View.GONE); mTextAccX = (TextView) rootView.findViewById(R.id.textAccX); mTextAccY = (TextView) rootView.findViewById(R.id.textAccY); mTextAccZ = (TextView) rootView.findViewById(R.id.textAccZ); mTextAngX = (TextView) rootView.findViewById(R.id.textPAngX); mTextAngY = (TextView) rootView.findViewById(R.id.textPAngY); mTextAngZ = (TextView) rootView.findViewById(R.id.textPAngZ); mTextLong = (TextView) rootView.findViewById(R.id.textLong); mTextLat = (TextView) rootView.findViewById(R.id.textLat); mTextTime = (TextView) rootView.findViewById(R.id.textTime); temp_list = new double[14]; c = 0;// ww w . j a v a2 s . com // Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager) getActivity() .getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location provider. temp_list[12] = location.getLongitude(); temp_list[13] = location.getLatitude(); mTextLong.setText(Double.toString(temp_list[12])); mTextLat.setText(Double.toString(temp_list[13])); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; // Register the listener with the Location Manager to receive location updates locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); runnable.run(); // // Gyro setup // mTableGyro = (TableLayout) rootView.findViewById(R.id.tableGyro); mTableGyro.setVisibility(View.GONE); mTextGyroAccX = (TextView) rootView.findViewById(R.id.textGyroAccX); mTextGyroAccY = (TextView) rootView.findViewById(R.id.textGyroAccY); mTextGyroAccZ = (TextView) rootView.findViewById(R.id.textGyroAccZ); mTextGyroAngX = (TextView) rootView.findViewById(R.id.textAngX); mTextGyroAngY = (TextView) rootView.findViewById(R.id.textAngY); mTextGyroAngZ = (TextView) rootView.findViewById(R.id.textAngZ); // // Contact setup // mTableContact = (TableLayout) rootView.findViewById(R.id.tableContact); mTableContact.setVisibility(View.GONE); mTextContact = (TextView) rootView.findViewById(R.id.textContact); turnOnSensors(); return rootView; }
From source file:hackathon.openrice.CardsActivity.java
@Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); Bundle extras = getIntent().getExtras(); String keyword = null;// ww w . j a va 2s .c o m if (extras != null) { ArrayList<String> text = extras.getStringArrayList(RecognizerIntent.EXTRA_RESULTS); if (text != null) { for (String t : text) { String temp = t.toLowerCase().trim(); if (temp.startsWith("search")) { keyword = temp.substring(6).trim(); } } } } Card info = new Card(this); info.setText("Loading data..."); cards.add(info); RetrieveImage task = new RetrieveImage(); // listener passed over to locationProvider, any location update is handled here this.locationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(final Location location) { // forward location updates fired by LocationProvider to architectView, you can set lat/lon from any location-strategy if (location != null) { // sore last location as member, in case it is needed somewhere (in e.g. your adjusted project) lastKnownLocation = location; if (lastKnownLocation != null) { // check if location has altitude at certain accuracy level & call right architect method (the one with altitude information) if (location.hasAltitude() && location.hasAccuracy() && location.getAccuracy() < 7) { lastKnownLocation = location; } else { lastKnownLocation = location; } } } } }; locationProvider = new LocationProvider(this, locationListener); double x, y; if (lastKnownLocation != null) { x = lastKnownLocation.getLatitude(); y = lastKnownLocation.getLongitude(); } else { x = 22.3049989; y = 114.17925600000001; } if (keyword != null) { //Log.d("FFFF", keyword); task.execute( "http://openricescraper.herokuapp.com/?x=" + x + "&y=" + y + "&keyword=" + Uri.encode(keyword)); } else { task.execute("http://openricescraper.herokuapp.com/?x=" + x + "&y=" + y); } mCardScroller = new CardScrollView(this); mCardScroller.setAdapter(new CardAdapter(cards)); mCardScroller.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { final String className = "com.wikitude.samples.SampleCamActivity"; try { final Intent intent = new Intent(ctx, Class.forName(className)); intent.putExtra(EXTRAS_KEY_ACTIVITY_TITLE_STRING, "5.2 Adding Radar"); intent.putExtra(EXTRAS_KEY_ACTIVITY_ARCHITECT_WORLD_URL, "samples/5_Browsing$Pois_2_Adding$Radar/index.html"); if (poiData != null) { JSONArray pass = new JSONArray(); final String ATTR_ID = "id"; final String ATTR_NAME = "name"; final String ATTR_DESCRIPTION = "description"; final String ATTR_LATITUDE = "latitude"; final String ATTR_LONGITUDE = "longitude"; final String ATTR_ALTITUDE = "altitude"; int i = position - 1; //for (int i = 0; i < poiData.length(); i++) { JSONObject jsonObj = (JSONObject) poiData.get(i); final HashMap<String, String> poiInformation = new HashMap<String, String>(); poiInformation.put(ATTR_ID, String.valueOf(i)); poiInformation.put(ATTR_NAME, new String(jsonObj.getString("name").getBytes("ISO-8859-1"), "UTF-8")); if (jsonObj.getString("score").equalsIgnoreCase("null")) { poiInformation.put(ATTR_DESCRIPTION, new String(jsonObj.getString("address").getBytes("ISO-8859-1"), "UTF-8")); } else { poiInformation.put(ATTR_DESCRIPTION, "" + jsonObj.getDouble("score") + ", " + new String(jsonObj.getString("address").getBytes("ISO-8859-1"), "UTF-8")); } poiInformation.put(ATTR_LATITUDE, String.valueOf(jsonObj.get("x"))); poiInformation.put(ATTR_LONGITUDE, String.valueOf(jsonObj.get("y"))); final float UNKNOWN_ALTITUDE = -32768f; // equals "AR.CONST.UNKNOWN_ALTITUDE" in JavaScript (compare AR.GeoLocation specification) // Use "AR.CONST.UNKNOWN_ALTITUDE" to tell ARchitect that altitude of places should be on user level. Be aware to handle altitude properly in locationManager in case you use valid POI altitude value (e.g. pass altitude only if GPS accuracy is <7m). poiInformation.put(ATTR_ALTITUDE, String.valueOf(UNKNOWN_ALTITUDE)); pass.put(new JSONObject(poiInformation)); //} intent.putExtra("poiData", pass.toString()); } /* launch activity */ ctx.startActivity(intent); } catch (Exception e) { /* * may never occur, as long as all SampleActivities exist and are * listed in manifest */ Toast.makeText(ctx, className + "\nnot defined/accessible", Toast.LENGTH_SHORT).show(); } } }); setContentView(mCardScroller); IntentFilter filter = new IntentFilter(); filter.addAction("com.ours.asyncisover"); filter.addCategory("android.intent.category.DEFAULT"); registerReceiver(myBroadcastReceiver, filter); isReceiverRegistered = true; }
From source file:com.esri.arcgis.android.samples.nearby.Nearby.java
private void setupLocationListener() { if ((mMapView != null) && (mMapView.isLoaded())) { mLDM = mMapView.getLocationDisplayManager(); mLDM.setLocationListener(new LocationListener() { boolean locationChanged = false; // Zooms to the current location when first GPS fix arrives. @Override/* w w w. j av a 2s. co m*/ public void onLocationChanged(Location loc) { if (!locationChanged) { locationChanged = true; zoomToLocation(loc); // After zooming, turn on the Location pan mode to show the location // symbol. This will disable as soon as you interact with the map. mLDM.setAutoPanMode(LocationDisplayManager.AutoPanMode.LOCATION); } } @Override public void onProviderDisabled(String arg0) { } @Override public void onProviderEnabled(String arg0) { } @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { } }); mLDM.start(); } }
From source file:com.wiret.arbrowser.AbstractArchitectCamActivity.java
private void initArView() { /* set AR-view for life-cycle notifications etc. */ this.architectView = (ArchitectView) this.findViewById(this.getArchitectViewId()); /* pass SDK key if you have one, this one is only valid for this package identifier and must not be used somewhere else */ final StartupConfiguration config = new StartupConfiguration(this.getWikitudeSDKLicenseKey(), this.getFeatures(), this.getCameraPosition()); /* first mandatory life-cycle notification */ this.architectView.onCreate(config); // set accuracy listener if implemented, you may e.g. show calibration prompt for compass using this listener this.sensorAccuracyListener = this.getSensorAccuracyListener(); // set urlListener, any calls made in JS like "document.location = 'architectsdk://foo?bar=123'" is forwarded to this listener, use this to interact between JS and native Android activity/fragment this.urlListener = this.getUrlListener(); // register valid urlListener in architectView, ensure this is set before content is loaded to not miss any event if (this.urlListener != null && this.architectView != null) { this.architectView.registerUrlListener(this.getUrlListener()); }//from ww w .ja v a 2 s .c o m if (hasGeo()) { // listener passed over to locationProvider, any location update is handled here this.locationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(final Location location) { // forward location updates fired by LocationProvider to architectView, you can set lat/lon from any location-strategy if (location != null) { // sore last location as member, in case it is needed somewhere (in e.g. your adjusted project) AbstractArchitectCamActivity.this.lastKnownLocaton = location; if (AbstractArchitectCamActivity.this.architectView != null) { // check if location has altitude at certain accuracy level & call right architect method (the one with altitude information) if (location.hasAltitude() && location.hasAccuracy() && location.getAccuracy() < 7) { AbstractArchitectCamActivity.this.architectView.setLocation(location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getAccuracy()); } else { AbstractArchitectCamActivity.this.architectView.setLocation(location.getLatitude(), location.getLongitude(), location.hasAccuracy() ? location.getAccuracy() : 1000); } } } } }; // locationProvider used to fetch user position this.locationProvider = getLocationProvider(this.locationListener); } else { this.locationProvider = null; this.locationListener = null; } }
From source file:com.example.mohamed.a3qaqer.RegisterActvity.java
private void getloc() { if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { loc_string = "none";// indicate that no gps data return;// w w w . jav a2 s. c om } Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setBearingRequired(true); criteria.setCostAllowed(true); criteria.setPowerRequirement(Criteria.POWER_LOW); criteria.setAltitudeRequired(false); String bestProvider = locationManager.getBestProvider(criteria, true); if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } locationManager.requestLocationUpdates(bestProvider, 2000, 10, new LocationListener() { @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } @Override public void onLocationChanged(final Location location) { } }); Location myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); double longitude = myLocation.getLongitude(); double latitude = myLocation.getLatitude(); loc_string = latitude + "-" + longitude; }
From source file:au.gov.ga.worldwind.androidremote.client.Remote.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Normally one shouldn't instantiate all these objects in the onCreate method, //as onCreate is called every time a configuration change occurs (orientation, //keyboard hidden, screen size, etc). But we are handling configuration changes //ourselves.//from ww w .jav a2 s .c om //hide the status bar this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //get local Bluetooth adapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { Toast.makeText(this, R.string.bluetooth_unavailable, Toast.LENGTH_LONG).show(); finish(); return; } communicator = new AndroidCommunicator(this, bluetoothAdapter); communicator.addListener(this); remoteViewCommunicator = new SocketAndroidCommunicator(this); DatasetModelState datasetsState = new DatasetModelState(communicator, this); LayerModelState layersState = new LayerModelState(communicator, this); PlaceModelState placesState = new PlaceModelState(communicator, this); ItemModelState[] states = new ItemModelState[] { datasetsState, layersState, placesState }; for (ItemModelState state : states) { itemModelStates.put(state.getModel().getId(), state); ItemModelFragmentMenuProvider menuProvider = new EmptyMenuProvider(); if (state == placesState) { menuProvider = new PlacesMenuProvider(communicator); } menuProviders.put(state.getModel().getId(), menuProvider); } controlFragment = ControlFragment.newInstance(remoteViewCommunicator); datasetsFragment = ItemModelFragment.newInstance(datasetsState.getModel().getId(), false); layersFragment = ItemModelFragment.newInstance(layersState.getModel().getId(), false); flatLayersFragment = ItemModelFragment.newInstance(layersState.getModel().getId(), true); placesFragment = ItemModelFragment.newInstance(placesState.getModel().getId(), false); tabFragments = new Fragment[] { controlFragment, datasetsFragment, layersFragment, flatLayersFragment, placesFragment }; //create the tabs getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); int[] tabIds = new int[] { R.string.controls_tab, R.string.datasets_tab, R.string.layers_tab, R.string.flat_layers_tab, R.string.places_tab }; for (int i = 0; i < tabIds.length; i++) { ActionBar.Tab tab = getSupportActionBar().newTab(); tab.setTag(tabIds[i]); tab.setText(tabIds[i]); tab.setTabListener(this); getSupportActionBar().addTab(tab); } getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setHomeButtonEnabled(true); //setup the shake sensor sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); sensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() { @Override public void onShake() { communicator.sendMessage(new ShakeMessage()); } }); // Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { if (isSendLocation()) { communicator.sendMessage(new LocationMessage(location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getAccuracy(), location.getBearing())); } } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); }