Android service stops working when phone locked

后端 未结 3 780
轻奢々
轻奢々 2021-01-12 08:06

I have an application which starts a service. The service has a timer and pops a notification every 30 seconds. I notice the following behavior:

  • if the screen
相关标签:
3条回答
  • 2021-01-12 08:12

    If you really want your service to run every 30s when the device is locked, you have to schedule your alarm with type ELAPSED_REALTIME_WAKEUP . But beware, this will certainly drain devices batteries to death rapidly!

    0 讨论(0)
  • 2021-01-12 08:19

    You don't. That would be the perfect way to quickly drain the phone's battery. If the phone is sleeping, let it sleep, unless you have a GOOD reason not to (in which case you use the AlarmManager for a one-time wake-up call in the future).

    I don't know what you're trying to achieve, but you need to use a completely different approach. A network tickle would be a good idea, for example, assuming you can live with your app being 2.2+ only.

    0 讨论(0)
  • 2021-01-12 08:27

    I had the some problem.

    You may use the WakeLock to do the work! Something like this:

    PowerManager pm = (PowerManager)getApplicationContext().getSystemService(
              getApplicationContext().POWER_SERVICE);
    WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wl.acquire();
    

    Then use this:

    wl.release();
    

    to release the wakelock.

    Don't forger to add:

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

    to the manifest!

    0 讨论(0)
提交回复
热议问题