boomboxarcade
boomboxarcade

Reputation: 1

How to launch an activity when device is unlock with Kotlin?

I want to start an activity when device is unlocked, but this code isn't working:

AndroidManidest.xml:

<receiver android:name=".ScreenReceiver" android:enabled="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.SCREEN_ON" />
        <action android:name="android.intent.action.USER_PRESENT" />
        <action android:name="android.intent.action.USER_PRESENT"/>
    </intent-filter>
</receiver>

ScreenRececiver.kt:

override fun onReceive(context: Context?, intent: Intent?) {
    if (intent?.action.equals(Intent.ACTION_USER_PRESENT) ||
        intent?.action.equals(Intent.ACTION_SCREEN_ON) ||
        intent?.action.equals(Intent.ACTION_BOOT_COMPLETED)) {
        var myIntent = Intent(context, MainActivity::class.java)
        myIntent?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context?.startActivity(myIntent)
    }
}

Upvotes: 0

Views: 441

Answers (1)

Farouq Afghani
Farouq Afghani

Reputation: 296

Implicit broadcasts no longer work with manifest-declared receivers in Android 8+ as @Tenfour04 mentioned in the comments above, you need to do it in your class as:

private val myScreenReceiver: MyScreenReceiver = MyScreenReceiver()

/**
 * Register for broadcast that will be triggered when the phone is unlocked
 * (when the keyguard is gone)
 */
private fun registerForScreenUnlockReceiver() {
    val screenStateFilter = IntentFilter()
    screenStateFilter.addAction(Intent.ACTION_USER_PRESENT)
    registerReceiver(myScreenReceiver, screenStateFilter)
}

override fun onDestroy() {
    super.onDestroy()
    // Unregister the screenr reicever
    unregisterReceiver(myScreenReciever)
}

Note: If you need this receiver to be called every time the user unlocks his screen then you need to use Foreground service and use this code there

Upvotes: 1

Related Questions