[英]Android Handler keeps running for a while even after the activity has been destroyed
I read that the handler.postDelayed
method helps pause a task for any amount of time.我读到
handler.postDelayed
方法有助于暂停任务任意时间。 So I wrote it into the light sensor so that the sensor only detects light every 2 seconds, in order to save battery life:所以我把它写到光传感器中,让传感器每 2 秒才检测一次光,以节省电池寿命:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor light = sm.getDefaultSensor(Sensor.TYPE_LIGHT);
SensorEventListener listener;
if (light != null) {
final Handler handler = new Handler();
final Runnable task = new Runnable() {
@Override
public void run() {
sm.registerListener(listener, light, SensorManager.SENSOR_DELAY_NORMAL);
}
};
listener = new SensorEventListener() {
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Toast.makeText(MainActivity.this, "accuracy changed!", Toast.LENGTH_SHORT).show();
}
@Override
public void onSensorChanged(SensorEvent event) {
sm.unregisterListener(listener, light);
// Do the stuff here with the received sensor light value, which is event.values[0]
handler.postDelayed(task, 2000);
}
};
}
@Override
protected void onPause() {
super.onPause();
sm.unregisterListener(listener, light);
}
@Override
protected void onResume() {
super.onResume();
sm.registerListener(listener, light, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onStop() {
super.onStop();
sm.unregisterListener(listener, light);
}
@Override
protected void onDestroy() {
super.onDestroy();
sm.unregisterListener(listener, light);
}
}
At first it seemed to work fine.起初它似乎工作正常。 But I found that every time I exit the app it kept detecting the light for like 20 to 30 seconds as if the activity was still open.
但我发现每次我退出应用程序时,它都会持续检测 20 到 30 秒的光线,就好像活动仍然打开一样。 What am I doing wrong?
我究竟做错了什么? I even added both the onStop and onDestroy methods just to be sure it was closing correctly.
我什至添加了 onStop 和 onDestroy 方法,以确保它正确关闭。
Inside the onDestroy() of your activity clear your handler like在您的活动的onDestroy()内部清除您的处理程序,例如
handler.removeCallbacksAndMessages(null);
And it will stop right away!它会立即停止!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.