我希望我的应用能够打开屏幕并显示我的应用。假设我要设置一个闹钟,并且我希望每小时显示我的应用2分钟,然后设备自然进入休眠状态。
我看到不赞成使用WakeLock(FULL_LOCK)和KeyguardManager。
我已经创建了WakefulBroadcastReceiver和服务,并且它们正在工作。
@Override
protected void onHandleIntent(Intent intent) {
// I need to show the screen here!
for (int i=0; i<5; i++) {
Log.i("SimpleWakefulReceiver", "Running service " + (i + 1)
+ "/5 @ " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i("SimpleWakefulReceiver", "Completed service @ " +
SystemClock.elapsedRealtime());
SimpleWakefulReceiver.completeWakefulIntent(intent);
}
如何以编程方式打开屏幕,越过锁定并从IntentService显示我的 Activity ?
谢谢
最佳答案
您可以使用此代码打开屏幕。
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);
您需要在AndroidManifest.xml文件中具有以下权限:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
编辑(不使用,仅此一项):
为此,还有另一种选择,因为您需要启动一个 Activity ,在 Activity
onCreate()
中,您需要将标志添加到窗口中。例如:
@Override
protected void onCreate(Bundle savedInstanceState) {
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);`
}