Как запустить действие, когда устройство разблокировано с Kotlin? - PullRequest
0 голосов
/ 19 марта 2020

Я хочу начать действие, когда устройство разблокировано, но этот код не работает:

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)
    }
}

1 Ответ

1 голос
/ 19 марта 2020

Неявные трансляции больше не работают с объявленными манифестами получателями в Android 8+, как @ Tenfour04, упомянутый в комментариях выше, вам нужно сделать это в своем классе как:

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)
}

Примечание: если вам нужно, чтобы этот приемник вызывался каждый раз, когда пользователь разблокирует свой экран, вам нужно использовать Foreground service и использовать этот код там

...