Android: Getting an already started Timer
I have an Activity that starts a fixed rate timer. How do I check if the timer is currently running once I reopen the activity?
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run()
{
startService(new Intent(getBaseContext(), GetClassInfoService.class));
}
}, 0, Integer.parseInt(updateTime)*60*1000);
editor.putStri开发者_运维技巧ng("timerState", "on");
I have tried setting a shared preference, and that works in every instance except when the app is fully closed, turning off the timer completely (If the user force closes or restarts the device). The shared preference would be left "on". Simply changing it in onDestroy won't work because I want the timer to continue going off even if the app is closed (but timer left on).
Is there a better way to check the timer? Or possibly a way to know when the timer gets turned off by a force close or restart?
The Service invoked by startService method is dependent on the Activity which it contains.
Why don't you use bindService method?
Honestly, I'd need more code to give you an informed opinion, but based on what you've given I'd say you want to move your timer logic into the service. By calling startService
the service will continue running until you call stopService
. Then your timer could continue running indefinitely inside the service and not have to worry about being stopped (unless the user force closes your service).
Depending on what you need to communicate to GetClassInfoService.class
, you can either use a mailbox like system based on the IntentService or you can use the more robust service binding method. Both are described here.
精彩评论