android AlarmManager not waking phone up

后端 未结 3 485
借酒劲吻你
借酒劲吻你 2020-11-27 14:29

I want an activity to be displayed at a certain time. For this, I am using AlarmManager. It works fine when the device is awake, but it doesn\'t wake it up if it\'s asleep.<

相关标签:
3条回答
  • 2020-11-27 14:53

    Most likely, the alarm is waking up the device. However, AlarmManager broadcasts won't turn the screen on, and the device may well fall back asleep before your activity starts up.

    You will need to acquire a WakeLock in onReceive() before calling startActivity(), and release that WakeLock after the user responds to your activity.

    0 讨论(0)
  • 2020-11-27 14:55

    For Services (maybe works for activity as well), extend your AlarmReceiver from WakefulBroadcastReceiver, it acquires WAKE_LOCK for you while intent is being processed.

    WakefulBroadcastReceiver docs - https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html

    Keeping device awake guide - https://developer.android.com/training/scheduling/wakelock.html

    0 讨论(0)
  • 2020-11-27 15:07

    I had a similar problem and the solution was to use WakeLocker. That should be done (preferably as the 1st thing in the receiver), or the device will wake up when the alarm is received, but will fall asleep again before context.startActivity(newIntent); is called. (I have also observed behavior when that does not happen, so it seems to be a bit arbitrary) So the easy and quick answer: Make a new class called WakeLocker with this source code:

    package mypackage.test;
    
    import android.content.Context;
    import android.os.PowerManager;
    
    public abstract class WakeLocker {
        private static PowerManager.WakeLock wakeLock;
    
        public static void acquire(Context ctx) {
            if (wakeLock != null) wakeLock.release();
    
            PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
                    PowerManager.ACQUIRE_CAUSES_WAKEUP |
                    PowerManager.ON_AFTER_RELEASE, MainActivity.APP_TAG);
            wakeLock.acquire();
        }
    
        public static void release() {
            if (wakeLock != null) wakeLock.release(); wakeLock = null;
        }
    }
    

    and in your receiver call WakeLocker.acquire(context); as the 1st thing. Extra: it would also be neat to call WakeLocker.release(); once your alarm has done its thing.

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