java如何在OnBackpress、onPause或OnResume中停止线程
在这里,我使用location来更新经度和纬度,每当我尝试按下back按钮或app is background或任何实例时,我都希望location\u线程停止运行它。当我切换到当前活动时恢复它
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;
安卓.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());
}
}
# 1 楼答案
不要使用
Thread.stop()
方法停止线程的最好方法是完成它的工作
创建volatile变量,比如
替换你的
到
然后把它变成现实
因为你的背压开始了另一项活动并完成了当前的任务,所以最好是这样做:
所以
s no need to stop thread in
根本就没有人反对请注意,在设置
threadIsStopped
之后,线程可能会停止关于恢复线程-在您的情况下,您只需创建新线程并启动它
还请注意,如果更改设备的方向,将再次调用
onPause
和onResume
。这就是为什么强烈建议使用IntentService
来做这些事情的原因