锁定屏幕处于活动状态时如何重点运行“活动”?

时间:2018-06-21 13:49:53

标签: android lockscreen

目标是:当手机锁定屏幕时,将“活动”从服务运行到前台,并在启动的“活动”中设置窗口焦点。

准备:
通过电源按钮将手机设置为锁定状态,
从服务运行活动:

Intent i = new Intent(mCtx, RecActivity.class);
i.putExtra(RecActivity.INTENT_REQUEST, intentExtra);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(i); //ctx is context

在活动onCreate()中运行此方法:

private void checkIntentExtraData(){
    try {
        //Check Intent
        Intent i = getIntent();
        Bundle extras = i.getExtras();
        if(extras != null) {
            /*PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
                    | PowerManager.ACQUIRE_CAUSES_WAKEUP
                    | PowerManager.ON_AFTER_RELEASE, "INFO");
            wl.acquire();*/

            window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); //This constant was deprecated in API level 26.
                window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); //This constant was deprecated in API level 27. => setShowWhenLocked(  
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //API 26+ Android 8.0+
                KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
                if(km != null)
                    km.requestDismissKeyguard(this, null);
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) { //API 27+ Android 8.1+
                setShowWhenLocked(true);
                setTurnScreenOn(true);
            }

            Log.i(TAG, "hasWindowFocus: "+hasWindowFocus()); //TODO
        }
    } catch (Exception e){
        e.printStackTrace();
    }
}

运行活动,回调为:onCreate() => onResume() => onPause()
我不想运行onPause()方法。可能是因为Activity没有重点(hasWindowFocus()返回false)。

有什么建议吗?谢谢。

我也尝试过,但是没有用:

android:showOnLockScreen="true"

在清单中。

1 个答案:

答案 0 :(得分:0)

我认为km.requestDismissKeyguard(this, null);应该在setShowWhenLocked()方法之后调用