I have the following code, I tried to do some work when the phone is turned on or unlocked, this code is working. However, when I tried to run when the phone is off or locked. it is not work
class ScreenReceiver : BroadcastReceiver() {
internal var screen: ScreenReceiver? = null
internal var context: Context? = null
override fun onReceive(context: Context, intent: Intent) {
this.context = context
if (intent.action == Intent.ACTION_SCREEN_ON) {
// do some work here
}
if (intent.action == Intent.ACTION_SCREEN_OFF) {
// do some work here. But it does not seem to work
}
}
}
Andridmanifest.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_OFF" />
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.USER_PRESENT" />
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</receiver>
Can anyone help me why it does not work and how to fix it?
Thanks
You must register the broadcast with registerReceiver(BroadcastReceiver, IntentFilter)
. Declaring a receiver in the manifest does not work. You can register your broadcast like this in your code:
val filter = IntentFilter(Intent.ACTION_SCREEN_ON)
filter.addAction(Intent.ACTION_SCREEN_OFF)
filter.addAction(Intent.ACTION_USER_PRESENT)
filter.addAction(Intent.ACTION_BOOT_COMPLETED)
registerReceiver(ScreenReceiver(), filter)
Beginning with Android 8.0 (API level 26), the system imposes additional restrictions on manifest-declared receivers. If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver for most implicit broadcasts (broadcasts that do not target your app specifically).
Refer https://developer.android.com/guide/components/broadcasts for additional detail.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.