Broadcast receiver registered in manifest not gett

2019-01-19 22:33发布

问题:

I have registered following receiver which is not getting called in Android Oreo but works on lower version devices.

<receiver
     android:name=".common.receiver.ConsultReceiver"
     android:exported="false">
       <intent-filter>
            <action android:name="APP_STARTED" />
            <action android:name="APP_STARTED_FROM_ORGANIC" />
       </intent-filter>
</receiver>  

Any help would be appreciated?

回答1:

In general, you cannot use an implicit Intent (e.g., one with just an action string) for a broadcast on Android 8.0+.

Your <receiver> is not exported. This suggests one of three things:

  1. You are using this with a PendingIntent, such as for a Notification. If so, get rid of the <intent-filter> and use an explicit Intent (new Intent(this, ConsultReceiver.class)) as part of creating your PendingIntent that points to this receiver.

  2. You are using this as part of some IPC between multiple app processes in your app. In that case, also use an explicit Intent.

  3. You are using this receiver purely within one process within your app. In that case, get rid of the <receiver> and use something else (LocalBroadcastManager, an event bus, RxJava, LiveData, etc.).



回答2:

In Android 8.0 and above, use the following code to check when some app is installed or uninstalled.

class MainActivity : AppCompatActivity() {

    private val receiver = YourBroadcastReceiverClass()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val filter = IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_ADDED)
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED)
        filter.addDataScheme("package")

        registerReceiver(receiver, filter)
    }

    override fun onDestory() {
        unregisterReceiver(receiver)
        super.onDestroy()
    }
}


回答3:

If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver for implicit broadcasts (broadcasts that do not target your app specifically), except for a few implicit broadcasts that are exempted from that restriction. In most cases, you can use scheduled jobs instead.



回答4:

Restrict the Intent to your package with setPackage.