在onCreate,我运行一个每分钟都重复的任务。我在这里是怎么做到的:
myTimer = new Timer();
int delay = 30000; // delay for 30 sec.
int period = 600000; // repeat every 60 sec.
doThis = new TimerTask() {
public void run() {
Log.v("TImer","repeated");
wv.reload();
}
};
myTimer.scheduleAtFixedRate(doThis, delay, period);
所有代码都在onCreate中。因此,当应用程序从屏幕上退出时,我可以在logcat中看到计时器钢块运行,除非应用程序被销毁,否则不会停止。所以,在onPause
的活动中我称之为myTimer.cancel();
,但它没有帮助。即使应用程序不在屏幕上,我仍然可以在logcat中看到更新。那么,如何阻止timerTask
?
这是你的代码放入我的文件,值延迟和周期调整,所以我不必等待这么久。我运行应用程序。我在LogCat中看到了这些消息。我按下Galaxy S3上的主页按钮。然后消息在LogCat中停止。
public class MainActivity extends Activity {
Timer myTimer;
TimerTask doThis;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTimer = new Timer();
int delay = 0; // delay for 30 sec.
int period = 1000; // repeat every 60 sec.
doThis = new TimerTask() {
public void run() {
Log.v("TImer","repeated");
}
};
myTimer.scheduleAtFixedRate(doThis, delay, period);
}
@Override
protected void onPause() {
myTimer.cancel();
super.onPause();
}
}
可能是因为线程已经被发送出去,所以它最后一次运行。在onLoad中将变量设置为true,然后在onPause中将其设置为false。然后在您的计时器任务中,如果变量为true,则仅运行您的代码。
尽管写入新if语句之外的日志。如果它确实只是最后一次运行它,那么这可能是你的解决方案。但如果在onPause之后仍然多次运行它,那么就不要采取我的解决方案。