Hier verwende ich Ort, um Länge und Breite zu aktualisieren, immer wenn ich versuche, Taste oder App Hintergrund oder eine Instanz zu drücken, ich möchte, dass die location_thread ausgeführt wird. Setze es fort, wenn ich zur aktuellen Aktivität wechsele.Wie man Thread in onBackPressed oder OnPause oder OnResume stoppt
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());
}
}
Das Hauptproblem ist, dass Sie "getLastKnownLocation" für die Aktualisierung des Standorts verwenden ... es ist eine schreckliche Idee ... statt dies sollten Sie dies mit 'locationListener' tun ... Sie können Beispielcode auf offiziellen Android finden Leitfaden Website – Selvin