J'utilise ici lieu de mettre à jour longitude et la latitude à chaque fois que je tente d'appuyer sur le bouton de retour ou de l'application de fond ou de toute instance, je veux le location_thread être arrêté en exécuter. Reprendre quand je passe à l'activité en cours.comment arrêter fil dans onBackPressed ou OnPause ou onResume
location_thread = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(2000);
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i("TAG",currentThread().getName()+" Running");
updateLatLongInfo();
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
location_thread.setDaemon(false);
location_thread.start();
}
@Override
//whenever user press a backbutton thread must stoppped
public void onBackPressed() {
super.onBackPressed();
location_thread.stop();
Intent intent = new Intent(Logistic_ReportProblem.this, FPAgentHome.class);
startActivity(intent);
finish();
}
private void updateLatLongInfo() {
try {
int locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
latlongInfo.setBackgroundResource(R.drawable.latlng_info);
GradientDrawable drawable = (GradientDrawable) latlongInfo.getBackground();
if (locationMode == 0 || locationMode == 1 || locationMode == 2) {
latlongInfo.setText("Please enable high accuracy in your location settings");
drawable.setColor(Color.RED);
} else {
try {
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) this.getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
android.location.Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
param_latitude = df.format(lat).toString();
param_longitude = df.format(lng).toString();
// latlongInfo.setText("Latitude :" + Math.round(lat * 1000000.0)/1000000.0 + " ," + " Longitude :" + Math.round(lng * 1000000.0)/1000000.0);
latlongInfo.setText("Latitude : " + param_latitude + " ," + " Longitude : " + param_longitude);
latlongInfo.setGravity(Gravity.CENTER);
drawable.setColor(Color.GREEN);
} catch (SecurityException e) {
Log.e("Error", e.toString());
}
}
le principal problème est que vous utilisez 'getLastKnownLocation' pour obtenir l'emplacement mis à jour ... il est très mauvaise idée ... au lieu de cela, vous devez le faire avec' locationListener' ... vous pouvez trouver un exemple de code sur officiall Android site web du guide – Selvin