Start activity when screen is off

♀尐吖头ヾ 提交于 2019-12-07 10:14:08

问题


I have set up an AlarmManager to start up an activity. This activity also plays a sound, similar to an alarm app or an incoming call.

It works ok if the screen is on, even if the screen is locked.

If the screen is off, it doesn't work at all. I tried using the following as the first thing in onCreate

getWindow().setFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,  WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

If the screenlock is not enabled, this turns on the screen and I can see my activity closing. I can't hear the sound playing. If the screenlock is enabled, the screen won't turn on at all.

Sometimes I get the following, but not always:

07-18 23:52:13.685: E/OpenGLRenderer(14148):   GL_INVALID_OPERATION

How can I make it start properly when the screen is off?


回答1:


I got my answer partially from here.

        lock = ((KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE)).newKeyguardLock(KEYGUARD_SERVICE);
        powerManager = ((PowerManager) getSystemService(Context.POWER_SERVICE));
        wake = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");

        lock.disableKeyguard();
        wake.acquire();

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);



回答2:


A while back I read that your app must be in full screen for the FLAG_TURN_SCREEN_ON to work.

"** One important note. Your activity must be full screen in order for the above flag combination to work. In my app I tried to use these flags with an activity which is not full screen (Dialog Theme) and it didn't work. After looking at the documentation I found that these flags require the window to be a full screen window." -Wake Android Device up

Quote from someone who posted their about a similar issue with FLAG_X.




回答3:


Look into running a service, activity is going to be stopped when not in foreground.

Also look into the Activity lifecycle. http://developer.android.com/reference/android/app/Activity.html



来源:https://stackoverflow.com/questions/24834529/start-activity-when-screen-is-off

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!