Search code examples
javaandroidscreenandroid-broadcastreceiverunlock

Detect screen unlock


I used solution from there: Android - detect phone unlock event, not screen on

So, my activity onCreate:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    registerReceiver(
       new PhoneUnlockedReceiver(), new IntentFilter("android.intent.action.USER_PRESENT")
    );
}

And my receiver class:

public class PhoneUnlockedReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        KeyguardManager keyguardManager = 
            (KeyguardManager)context.getSystemService(Context.KEYGUARD_SERVICE);
        if (keyguardManager.isKeyguardSecure())
        {
            Toast.makeText(context, "Screen unlocked", Toast.LENGTH_LONG).show();
        }
    }
}

But it's not working, my onReceive method is never called. Any ideas what's wrong?

My Android Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.example.michal.popupmenu"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

As far as I know, there is no need to add anything to manifest if I choose to use registerReceiver, right?


Solution

  • As far as I know, there is no need to add anything to manifest if I choose to use registerReceiver, right?

    Wrong. The advantage of an registered receiver in the manifest is the fact that it does not require your app to be running when the Intent is fired.

    So your app probably is not active when the user unlocks the screen so there is no registerReceiver() called and therefore your receiver does not react.

    Add the receiver in your manifest and it will work.