【问题标题】:How to launch an activity when device is unlock with Kotlin?使用 Kotlin 解锁设备时如何启动活动?
【发布时间】:2020-06-30 13:55:12
【问题描述】:

我想在设备解锁时开始一项活动,但此代码不起作用:

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

【问题讨论】:

标签: android kotlin android-intent android-activity broadcastreceiver


【解决方案1】:

如上面 cmets 中提到的@Tenfour04,在 Android 8+ 中,隐式广播不再适用于清单声明的接收器,您需要在您的班级中这样做:

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

注意:如果您需要每次用户调用此接收器 解锁他的屏幕然后你需要使用前台服务并使用 这段代码在那里

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多