List of usage examples for android.location LocationListener LocationListener
LocationListener
From source file:de.madvertise.android.sdk.MadvertiseUtil.java
/** * Try to update current location. Non blocking call. * //w ww . ja va2s . c o m * @param context * application context */ public static void refreshCoordinates(final Context context) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Trying to refresh location"); if (context == null) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Context not set - quit location refresh"); return; } // check if we need a regular update if ((sLocationUpdateTimestamp + MadvertiseUtil.SECONDS_TO_REFRESH_LOCATION * 1000) > System .currentTimeMillis()) { MadvertiseUtil.logMessage(null, Log.DEBUG, "It's not time yet for refreshing the location"); return; } synchronized (context) { // recheck, if location was updated by another thread while we // paused if ((sLocationUpdateTimestamp + MadvertiseUtil.SECONDS_TO_REFRESH_LOCATION * 1000) > System .currentTimeMillis()) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Another thread updated the loation already"); return; } boolean permissionCoarseLocation = MadvertiseUtil .checkPermissionGranted(android.Manifest.permission.ACCESS_COARSE_LOCATION, context); boolean permissionFineLocation = MadvertiseUtil .checkPermissionGranted(android.Manifest.permission.ACCESS_FINE_LOCATION, context); // return (null) if we do not have any permissions if (!permissionCoarseLocation && !permissionFineLocation) { MadvertiseUtil.logMessage(null, Log.DEBUG, "No permissions for requesting the location"); return; } // return (null) if we can't get a location manager LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); if (locationManager == null) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Unable to fetch a location manger"); return; } String provider = null; Criteria criteria = new Criteria(); criteria.setCostAllowed(false); // try to get coarse location first if (permissionCoarseLocation) { criteria.setAccuracy(Criteria.ACCURACY_COARSE); provider = locationManager.getBestProvider(criteria, true); } // try to get gps location if coarse locatio did not work if (provider == null && permissionFineLocation) { criteria.setAccuracy(Criteria.ACCURACY_FINE); provider = locationManager.getBestProvider(criteria, true); } // still no provider, return (null) if (provider == null) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Unable to fetch a location provider"); return; } // create a finalized reference to the location manager, in order to // access it in the inner class final LocationManager finalizedLocationManager = locationManager; sLocationUpdateTimestamp = System.currentTimeMillis(); locationManager.requestLocationUpdates(provider, 0, 0, new LocationListener() { @Override public void onLocationChanged(Location location) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Refreshing location"); sCurrentLocation = location; sLocationUpdateTimestamp = System.currentTimeMillis(); // stop draining battery life finalizedLocationManager.removeUpdates(this); } // not used yet @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } }, context.getMainLooper()); } }
From source file:com.example.devesh.Coride.DriverRegistration.java
@TargetApi(Build.VERSION_CODES.M) public void sendData(View view) throws MalformedURLException { Log.e("TEST LOG", "Entered the loop"); Toast.makeText(this, "coride", Toast.LENGTH_SHORT).show(); Master master = new Master(); String url_string = master.url + "driverdata"; EditText n_edittext;// w w w . java 2 s .co m EditText mob_edittext; EditText confrm_edittext; EditText age_edittext; EditText lnumber; EditText pnumber; EditText vnumber; EditText mnumber; EditText capacity; String name; String mobile; String conpassword; String password; String address; String email; String slnumber; String spnumber; String svnumber; String smnumber; String scapacity; int count = 0; n_edittext = (EditText) findViewById(R.id.name); mob_edittext = (EditText) findViewById(R.id.mobileno); confrm_edittext = (EditText) findViewById(R.id.confirmpassword); mPasswordView = (EditText) findViewById(R.id.password); mEmailView = (AutoCompleteTextView) findViewById(R.id.email); age_edittext = (EditText) findViewById(R.id.address); lnumber = (EditText) findViewById(R.id.lnumber); pnumber = (EditText) findViewById(R.id.pnumber); vnumber = (EditText) findViewById(R.id.vnumber); mnumber = (EditText) findViewById(R.id.mnumber); capacity = (EditText) findViewById(R.id.capacity); name = n_edittext.getText().toString(); mobile = mob_edittext.getText().toString(); master.mobile1 = mobile; password = mPasswordView.getText().toString(); conpassword = confrm_edittext.getText().toString(); address = age_edittext.getText().toString(); email = mEmailView.getText().toString(); slnumber = lnumber.getText().toString(); spnumber = pnumber.getText().toString(); svnumber = vnumber.getText().toString(); smnumber = mnumber.getText().toString(); ; scapacity = capacity.getText().toString(); regId = registerGCM(); System.out.println(regId); // String reg=regId.toString(); count = validate(name, email, mobile, password, conpassword, address); if (count == 0) { count = email_validation(mEmailView, getBaseContext()); } if (count == 0) { count = password_matcher(password, conpassword); } if (count == 0) { String json = "[{name:\"" + name + "\"},{mobile:\"" + mobile + "\"},{password:\"" + password + "\"},{email:\"" + email + "\"},{address:\"" + address + "\"},{license:\"" + slnumber + "\"},{pan:\"" + spnumber + "\"},{vehicle:\"" + svnumber + "\"},{model:\"" + smnumber + "\"},{capacity:\"" + scapacity + "\"},{regid:\"" + regId + "\"}]"; // snd.addNameValuePair("name", name); //snd.addNameValuePair("mobile", mobile); //snd.addNameValuePair("password", password); // snd.addNameValuePair("email",email); //snd.addNameValuePair("age", age); SendDataTask snd = new SendDataTask(json); //Go to sendData class fromhere URL url = new URL(url_string); snd.execute(url); } System.out.println("i am hear"); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER) || locationManager.isProviderEnabled(locationManager.GPS_PROVIDER)) { Log.e("Coride", "Provider enable"); callLocationService(); } else { Log.e("Coride", "provider disabled"); showSettingsAlert("NETWORK_PROVIDER"); } LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { callLocationService(); } @Override public void onProviderDisabled(String s) { showSettingsAlert("NETWORK_PROVIDER"); } }; // dialog.cancel(); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, 123); return; } locationManager.requestLocationUpdates(locationManager.NETWORK_PROVIDER, 0, 0, locationListener); }
From source file:tv.piratemedia.flightcontroller.BluetoothComputerFragment.java
public void setupGPS() { LocationManager locationManager = (LocationManager) getActivity() .getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { currentLat = location.getLatitude(); currentLong = location.getLongitude(); JSONObject msg = new JSONObject(); try { msg.put("action", "location_update"); msg.put("long", currentLong); msg.put("lat", currentLat); } catch (JSONException e) { e.printStackTrace();//from w w w. j a va 2 s. c om } sendTextMessage(msg.toString()); Log.d("location", currentLat + " x " + currentLong); } 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); }
From source file:com.fpil.android.remotesensor.MainDisplay.java
public void processData(final Intent data) { Toast.makeText(getContext(), "Received Info", Toast.LENGTH_SHORT).show(); myTalker.flushData(mChatService.inRedArray, mChatService.inGreenArray, mChatService.inBlueArray, mChatService.inCArray, mChatService.inLeafNumber, mChatService.incomingIndex, mChatService.leafIndex);/*from w w w.j a va 2 s .c om*/ data.putExtra(SuggestAndSave.red, mChatService.inRedArray); data.putExtra(SuggestAndSave.green, mChatService.inGreenArray); data.putExtra(SuggestAndSave.blue, mChatService.inBlueArray); data.putExtra(SuggestAndSave.C, mChatService.inCArray); TelephonyManager tmanager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE); data.putExtra(SuggestAndSave.IMEI, tmanager.getDeviceId()); if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. // no location data, save without it saver.saveInfo(data); refreshCards(); } else { final long key_update = saver.saveInfo(data); refreshCards(); Toast.makeText(getActivity(), "Saved data, waiting for location", Toast.LENGTH_SHORT).show(); Log.d(TAG, "Waiting for location"); final long time = new Date().getTime(); LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { if ((Math.abs(current.getAccuracy() - locAccuracy) < 20) || (new Date().getTime() - time > 3000)) { try { locationManager.removeUpdates(this); } catch (SecurityException e) { } Log.d(TAG, String.format("Lat: %f, Long: %f, Accuracy: %f", location.getLatitude(), location.getLongitude(), location.getAccuracy())); Toast.makeText(getActivity(), "Updated location", Toast.LENGTH_SHORT).show(); saver.updateLocation(key_update, location.getLatitude(), location.getLongitude()); refreshCards(); } } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; locationManager.requestLocationUpdates(locationProviderName, 2000, 0, locationListener); } }
From source file:org.y20k.trackbook.MainActivityMapFragment.java
private LocationListener createLocationListener() { return new LocationListener() { public void onLocationChanged(Location location) { // check if the new location is better if (mCurrentBestLocation == null || LocationHelper.isBetterLocation(location, mCurrentBestLocation)) { // save location mCurrentBestLocation = location; // mark user's new location on map and remove last marker updateMyLocationMarker(); }/*from w w w.j a va 2 s . com*/ } public void onStatusChanged(String provider, int status, Bundle extras) { LogHelper.v(LOG_TAG, "Location provider status change: " + provider + " | " + status); } public void onProviderEnabled(String provider) { LogHelper.v(LOG_TAG, "Location provider enabled: " + provider); } public void onProviderDisabled(String provider) { LogHelper.v(LOG_TAG, "Location provider disabled: " + provider); } }; }
From source file:gov.sfmta.sfpark.MainScreenActivity.java
void startLocation() { SharedPreferences preferences = getPreferences(MODE_PRIVATE); warningSeen = preferences.getBoolean(WARNING_KEY, false); if (warningSeen) { //once only, ever! return;/*from w w w . j a v a 2s . c o m*/ } locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); speed = 0; lastSpeed = 0; thisProvider = LocationManager.GPS_PROVIDER; // Define a listener that responds to location updates locationListener = new LocationListener() { public void onStatusChanged(String provider, int status, Bundle extras) { MYLOG(String.format("onStatusChanged %d", status)); } public void onProviderEnabled(String provider) { MYLOG("onProviderEnabled" + provider); thisProvider = provider; } public void onProviderDisabled(String provider) { MYLOG("onProviderDisabled" + provider); thisProvider = null; } @Override public void onLocationChanged(Location loc) { MYLOG("onLocationChanged"); lastSpeed = speed; if (loc == null) { speed = 0; } else { // speed is returned in meters per second speed = loc.getSpeed(); userLocation = loc; mapView.invalidate(); } // need last speed > threshold as well. if (speed > SPEED_THRESHOLD) { if (lastSpeed > SPEED_THRESHOLD) { SharedPreferences preferences = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); warningSeen = preferences.getBoolean(WARNING_KEY, false); if (warningSeen == false) { warningSeen = true; editor.putBoolean(WARNING_KEY, warningSeen); editor.commit(); SpeedingViewActivity.present(mapView.getContext()); } } } if (SFparkActivity.DEBUG) { String locStr = String.format("speed:%f last speed:%f, when %d", speed, lastSpeed, System.currentTimeMillis()); debugText.setText(locStr); } } }; locationUpdates(true); }
From source file:com.google.android.gms.samples.vision.ocrreader.MainActivity.java
private void _getLocation() { // Get the location manager Coordinates = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET }, PackageManager.PERMISSION_GRANTED); }/* w w w. j a va 2 s .co m*/ GPSEnabled = true; NetworkEnabled = true; try { GPSEnabled = Coordinates.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception ex) { } try { NetworkEnabled = Coordinates.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception ex) { } if (!GPSEnabled) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage("GPS is Required but Disabled : Enable GPS , Restart App."); alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); finish(); } }); alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } if (!NetworkEnabled) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage("Network is Required but Disabled : Enable Network , Restart App."); alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); finish(); } }); alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } if (GPSEnabled && NetworkEnabled) { Coordinates.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() { @Override public void onLocationChanged(Location location) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }); try { location = Coordinates.getLastKnownLocation(LocationManager.GPS_PROVIDER); lat = location.getLatitude(); lon = location.getLongitude(); } catch (Exception e) { } } }
From source file:com.anton.gavel.GavelMain.java
@TargetApi(Build.VERSION_CODES.GINGERBREAD) @Override/*from w w w .j a v a 2 s . c o m*/ public void onClick(View arg0) { //click listener for location button LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setPowerRequirement(Criteria.POWER_HIGH); //String provider = locationManager.getBestProvider(criteria, true); locationManager.requestSingleUpdate(criteria, new LocationListener() { @Override public void onLocationChanged(Location location) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) createDialog(DIALOG_NO_GEOCODING); else if (Geocoder.isPresent()) (new ReverseGeocodingTask(getBaseContext())).execute(new Location[] { location }); // Invoking reverse geocoding in an AsyncTask. } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } }, null); }
From source file:com.wikitude.phonegap.WikitudePlugin.java
/** * add architectView to current screen//from ww w. j a v a2 s.c o m * @param apiKey developers's api key to use (hides watermarking/intro-animation if it matches your package-name) * @param filePath the url (starting with http:// for online use; starting with LOCAL_ASSETS_PATH_ROOT if oyu want to load assets within your app-assets folder) * @throws IOException might be thrown from ARchitect-SDK */ private void addArchitectView(final String apiKey, String filePath) throws IOException { if (this.architectView == null) { this.architectView = new ArchitectViewPhoneGap(this.cordova.getActivity(), new OnKeyDownListener() { @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (WikitudePlugin.this.architectView != null && keyCode == KeyEvent.KEYCODE_BACK) { WikitudePlugin.this.locationProvider.onPause(); removeArchitectView(); return true; } return false; } }); this.architectView.setFocusableInTouchMode(true); this.architectView.requestFocus(); 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) { if (location != null) { WikitudePlugin.this.lastKnownLocaton = location; if (WikitudePlugin.this.architectView != null) { if (location.hasAltitude()) { WikitudePlugin.this.architectView.setLocation(location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getAccuracy()); } else { WikitudePlugin.this.architectView.setLocation(location.getLatitude(), location.getLongitude(), location.getAccuracy()); } } } } }; /* add content view and fake initial life-cycle */ (this.cordova.getActivity()).addContentView(this.architectView, new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); /* fake life-cycle calls, because activity is already up and running */ this.architectView.onCreate(getArchitectConfig(apiKey)); this.architectView.onPostCreate(); /* register self as url listener to fwd these native calls to PhoneGap */ this.architectView.registerUrlListener(WikitudePlugin.this); /* load asset from local directory if prefix is used */ if (filePath.startsWith(WikitudePlugin.LOCAL_ASSETS_PATH_ROOT)) { filePath = filePath.substring(WikitudePlugin.LOCAL_ASSETS_PATH_ROOT.length()); } this.architectView.load(filePath); /* also a fake-life-cycle call (the last one before it is really shown in UI */ this.architectView.onResume(); this.locationProvider = new LocationProvider(this.cordova.getActivity(), this.locationListener); this.locationProvider.onResume(); } // hide keyboard when adding AR view on top of views InputMethodManager inputManager = (InputMethodManager) (this.cordova.getActivity()) .getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow((this.cordova.getActivity()).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); }
From source file:com.davidmascharka.lips.TrackerActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //allow users to go back to Main Activity //TODO: test if this works on Marshmallow if (Build.VERSION.SDK_INT >= 23) { getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayShowHomeEnabled(true); } else {/*from w w w . java 2 s .c o m*/ getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestMyPermissions(); } setContentView(R.layout.activity_tracker); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction().add(R.id.container, new TrackerFragment()).commit(); } rotation = new float[9]; inclination = new float[9]; orientation = new float[3]; sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { updateLocation(location); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; loadXClassifierModels(); loadYClassifierModels(); loadPartitionClassifierModels(); setUpXInstances(); setUpYInstances(); setUpPartitionInstances(); wifiReadings = new LinkedHashMap<String, Integer>(); t = new Thread(); t.start(); //load5PartitionClassifiers = new Thread(); //load5PartitionClassifiers.start(); }