my application objective is to save location updates every ,let say, 20 minuets .
I used service and it worked fine , but when i lock the screen or it is locked automatically the service stop running . when i unlock it , service runs again.
highlight on my code:
Service()
onCreat(){
call timer();
}
timer(){
co开发者_运维技巧de
}
How to make my code run all the time in all conditions?
Yes, use AlarmManager to start the service every 10 minutes for example with setRepeating like below. Get rid of timer in service and just let service run task in oncreate or onCommand start to completion.
int SECS = 1000;
int MINS = 60 * SECS;
Calendar cal = Calendar.getInstance();
Intent in = new Intent(context, YourService.class);
PendingIntent pi = PendingIntent.getService(context, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarms = (AlarmManager)context.getSystemService(
Context.ALARM_SERVICE);
alarms.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
10 * MINS, pi);
You can create an activity to contain this code in an onclick handler from a button to start the service. If you want to run at boot time you need to put this in a broadcast receiver that gets notified when device is up, but that is another topic on its own.
The reason service and timer does not work when device is asleep is because cpu is off and your code has no wake lock. AlarmManager will wake up the cpu ever so slightly to run your service.
The right way to arrange for your service to do work on a scheduled basis (e.g., "call timer()"), including waking up the device, is to use the AlarmManager
, probably along with my WakefulIntentService
or something similar.
精彩评论