I need that android application do something ant specific time of the day, for example at 8:00 pm application should log out. I don’t want to use AlarmManager because it fired even if application is not running. also if phone was restarted of turned off schedule dispersers. Handler with Runnable will be very nice but if phone go asleep it don’t work.
So what i need is:
-
Application do something at specified time (which is saved in preferences)
-
This should happen only if application is running and logged in (even phone in asleep)
What can you propose?
EDITED:
Also this task should wait until application ends its other work(sending, receiving data), even better if only executes in specific activity(like home or main where other work aren’t performing)
The only way to wake the phone up when it is sleeping is by using the AlarmManager. There is no other way (well, you could hold a wake-lock and prevent the phone from going to sleep but that would drain the battery unnecessarily and your users would be angry).
So you want to schedule an alarm using the AlarmManager. Then, when the alarm goes off, you can check yourself if the application is already running and logged in (save this information is some static (ckass) variables). If the application wasn’t already running and logged in, then just do nothing.
EDIT: Add code example
Create a public static (class) variable that can be accessed by all of the classes in your application:
In your application, whenever it is doing something useful and doesn’t want to get interrupted or logged-out by your timer-based alarm, it should set this variable to “true” and when it has completed its work and is no longer doing anything useful it should reset the variable to “false”:
In your BroadcastReceiver, when the alarm goes off you can check if the application is doing anything useful. If it is, you just ignore the alarm and wait for the next one. If it isn’t doing anything useful, you log the user out.