简体   繁体   中英

Lock screen programatically when exiting app

Some apps in Android seem to be able to keep the screen on beyond the normal timeout (presumably done with FLAG_KEEP_SCREEN_ON), but on exiting the app lock the screen. I've seen this eg in navigation apps, that keep route guidance open, but the screen locks as soon as you leave the app.

How is this done?

(Note that the lock should happen when the application is goes into the background, not just when an activity is replaced by another activity within the same application.)

I managed to partially figure this out, based on " Launch activity when user taps on a notification from the lockscreen ". Here is an example. Use this project https://github.com/googlesamples/android-CustomNotifications/ (eg Android Studio: File > New > Import Sample; look for ("Custom Notifications") and replace onCreate like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Window window = this.getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.sample_main);
}

and in the manifest add

    <activity ...
         android:showOnLockScreen="true"
    ...

You now observe that the activity persists if

  • You press power button to turn off the screen. Press power button to activate screen, and your activity resumes without need to unlock screen.
  • You let the screen time out: Again, press power button to activate screen, and your activity resumed without need to unlock screen.

But: Once the screen has been locked at least once (through timeout or power buttons), then, when you navigate away from the app, the screen locks (which provides a partial answer to Lock screen programatically when exiting app ).

However, it doesn't work when you navigate away before the screen has been locked at least once. Does anybody have suggestions?

Related question here: Launch activity when user taps on a notification from the lockscreen (secure unlock)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM