问题
How to start an Activity on device even if screen is locked. I tried as below but it's not working.
Broadcast receiver:
Intent alarmIntent = new Intent("android.intent.action.MAIN");
alarmIntent.setClass(context, Alarm.class);
alarmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
alarmIntent.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED +
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD +
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON +
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
context.startActivity(alarmIntent);
回答1:
You need the following permission in AndroidManifest.xml
file:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
Check the manifest details here. You can check this link on you query.
回答2:
You can achieve this in two ways:
using wake lock as explained by @Yup in this post.
using window flags.
Using window flags:
Open the Activity A which you want to start in onReceive(...)
. Paste this in onCreate()
of that Activity A
final Window win= getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
Make sure you're not pasting it before setContentView(...)
:-)
回答3:
Paste this in your onCreate method of the activity you want to open when the screen is locked, after setContentView()
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
回答4:
You can check here regarding whether screen is locked or unlocked.
Then you can use wake lock and power management options to maintain screen without getting locked. you can find help here
回答5:
- manifest file give permission uses-permission android:name="android.permission.WAKE_LOCK" then write code inside in your requirement activity onCreate()
- final Window win= getWindow(); win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
来源:https://stackoverflow.com/questions/20113161/start-activity-screen-even-if-screen-is-locked-in-android