tags:

views:

116

answers:

1

So I have a very simple android activity that starts a timer when you hit a button.

Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
doStuff();
}
}, 15 * 60 * 1000);

So this worked reasonably well for me when I was testing but as it turns out when the screen becomes inactive so does the timer. I was a bit surprised by this. I understand you need to create a service to have anything running in the background but I hadn't realized this is required for an activity in the foreground when the phone has inactivated the screen due to lack of activity. What confuses me is I think this worked as I expected originally and just in the last few weeks or so has the timer been affected by the phone saving power. I could be wrong though..

So basically my questions are: am I seeing expected behavior? Do I need to create all timers as services or somehow disallow powersaving?

thanks for any advice, Patrick

+2  A: 

I was a bit surprised by this.

When the screen goes off, the CPU shuts down shortly thereafter. Your user of Timer has nothing to do with it, as that's a Java thing, not an Android thing.

What confuses me is I think this worked as I expected originally and just in the last few weeks or so has the timer been affected by the phone saving power.

I highly doubt that.

am I seeing expected behavior?

Yes.

Do I need to create all timers as services or somehow disallow powersaving?

If you have an activity that must keep the screen and device on, use:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

However, this should be for something like a video player.

If you are trying to do something more like a Windows scheduled task or Linux cron job, you will want to use AlarmManager and an IntentService, perhaps a WakefulIntentService.

There are other possibilities as well, but I don't know what you're trying to build.

CommonsWare
It's basically just an alarm. It plays a noise when when the 15 minutes are up.Thanks for the good answer.
elchuppa
If the alarm absolutely has to sound after the 15 minutes, you will need to invest in `AlarmManager`. The keep-the-screen-on trick will only work if your activity is running, and the user could press BACK to exit it, or start another application, or something. If you only care about the timer if the activity is up and running, though, the `FLAG_KEEP_SCREEN_ON` approach may suffice.
CommonsWare