1

Is it possible to have an Android app continue to run while the device is asleep, activating or polling every N seconds?

ina
  • 19,167
  • 39
  • 122
  • 201
  • 1
    You can use a service with an alarm manager instead together with a Power Manager, that will be less resource consuming. – Skynet Feb 22 '14 at 13:44
  • Does this require rooting? – ina Feb 22 '14 at 13:46
  • Not at all, its there to help developers. However please pay attention to what the docs say when applying all this in API Level 19. This might come handy: http://stackoverflow.com/questions/21461191/alarmmanager-fires-alarms-at-wrong-time/21461246#21461246 – Skynet Feb 22 '14 at 13:47

2 Answers2

2

you can use wake up while the app is in sleep or when the app is unlocked

use this in your manifest file

< uses-permission android:name="android.permission.WAKE_LOCK" />
 < uses-permission android:name="android.permission.DISABLE_KEYGUARD" />

to continue to run while the device is asleep

use the below code

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
 wl.acquire();
   ..screen will stay on during this section..
 wl.release();

Hope this helps

1

Yes, there is the way to do it. You have to simply set your scheduled runner via alarm manager to run your application at specified time or after elapsed time.

   public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {

     final public static String ONE_TIME = 'onetime';

     @Override
     public void onReceive(Context context, Intent intent) {
 PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 'YOUR TAG');
         //Acquire the lock
         wl.acquire();
          SetAlarm(context);
   //Release the lock
         wl.release();
     }

     public void SetAlarm(Context context)
        {
            AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
            intent.putExtra(ONE_TIME, Boolean.FALSE);
            PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
            //After after 5 seconds
            am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi); 
        }

    }

Remember to add your receiver in manifest

<receiver android:name='com.rakesh.alarmmanagerexample.AlarmManagerBroadcastReceiver'>
            </receiver>
RMachnik
  • 3,598
  • 1
  • 34
  • 51
  • are there other things that should be set in manifest? does this require rooting – ina Apr 04 '14 at 22:34