Deema
Deema

Reputation: 3

How to make Android Service run even when the device is not awake?

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(){
   code
 }

How to make my code run all the time in all conditions?

Upvotes: 0

Views: 1794

Answers (2)

stiqs
stiqs

Reputation: 16

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.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1007276

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.

Upvotes: 0

Related Questions