Activity handle when screen unlocked
Asked Answered
H

1

6

So I have my onResume command restarting a stopped thread which runs my game loop. This works perfectly for resuming the app when closed by home button or by focusing on another app. However, when you turn the screen off then on again, the activities onResume command fires right away before screen is unlocked. I need my activity to know when the screen is unlocked so it can restart the thread at the appropriate time.

Has anyone had this happen before?

Hekker answered 17/3, 2012 at 5:33 Comment(0)
P
15

for detect screen on and screen off register a broadcast reciver like:

AndroidManifest.xml:

    <receiver android:name="receiverScreen">
        <intent-filter> 
            <action android:name="android.intent.action.SCREEN_ON" />
            <action android:name="android.intent.action.SCREEN_OFF" />
<action android:name="android.Intent.ACTION_USER_PRESENT" />
        </intent-filter> 
    </receiver>

In Activity or Service:

    try {
              IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);

              filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);

              BroadcastReceiver mReceiver = new receiverScreen();

              registerReceiver(mReceiver, filter);
         } catch (Exception e) {

         }

receiver code where System inform you if Screen on/off happen:

 public class receiverScreen extends BroadcastReceiver {

     @Override
     public void onReceive(Context context, Intent intent) {

         if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)){

         }
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){

         }
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)){

         }
     }

    }
Posticous answered 17/3, 2012 at 5:43 Comment(5)
It looks like the code for AndroidManifest.xml did not get included.Vitus
very helpful, however ACTION_SCREEN_OFF only executes when the screen is turned on and the unlock screen appears, i need this to execute when the unlock screen unlocks and disappearsHekker
@Hekker then register on more BroadcastReceiver receiver Intent.ACTION_USER_PRESENTMablemabry
@Hekker only these three Intent.ACTION_USER_PRESENT,ACTION_SCREEN_OFF and ACTION_SCREEN_ON receivers are available to inform system when screen on/offMablemabry
EXCELLENT! exactly what I needed Intent.ACTION_USER_PRESENT thankyou.Hekker

© 2022 - 2024 — McMap. All rights reserved.