How do I detect when the screen of an Android device is close to timeout or "Lock"?

I have an Android app that needs to determine when the screen will be locked.
Can I find out how long the screen will remain “Unlocked” for?

+4
source share
2 answers

You will need to register the broadcast receiver. Your system will send the ford when the device is sleeping. Put the following code wherever you want:

private BroadcastReceiver receiver = new BroadcastReceiver() { public void onReceive(final Context context, final Intent intent) { //check if the broadcast is our desired one if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) //here define your method to be executed when screen is going to sleep }}; 

you need to register the recipient:

  IntentFilter regFilter = new IntentFilter(); // get device sleep evernt regFilter .addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(receiver, regFilter ); 

ACTION_SCREEN_OFF is sent after turning off the screen and ACTION_SCREEN_ON is sent after turning on the screen.

UPDATE:

1.Method 1: As far as I know, you cannot configure the listener before the device goes into sleep mode. There is no such listener in PowerManager. The solution that comes to my mind is to get the device time from the settings , and then set the countdown timer in your application. The countdown should be reset every time the user touches the screen. Thus, you can guess the time when the device goes into sleep mode, and then configure wakelock before the device goes into sleep mode and launches your desired code, then turn off wakelock and put the device into sleep mode.

2. Method 2: the inPause () method of your activity is called when your device goes into sleep mode. Perhaps you can make some code there. Just think it over.

+6
source

You should use "Wakelock" .. try this code

 PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE); wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "whatever");wl.acquire(); 

And don't forget to accept the permission for your manifest "Android.permission.WAKE_LOCK" and write wl.release () in your pouse () method.

+1
source

Source: https://habr.com/ru/post/1494276/


All Articles