Broadcast receiver not receiving intent

2020-05-16 09:25发布

问题:

I have two apps that I have complete control over. Both are signed with the same cert and both use the exact same intent filter. One sends the broadcast from a fragment, the other is suppose to receive it and do something. This however is not working:

Strings.FILTER_INIT_REGISTER = "com.app.FILTER_INIT_REGISTER"

Intent intent = new Intent(Strings.FILTER_INIT_REGISTER);
getActivity().sendBroadcast(intent);

I have registered the receiver in the Manifest app tag for the app containing the ReportingReceiver class:

<receiver             
    android:name=".receivers.ReportingReceiver"
    android:exported="true"
    >
        <intent-filter>
            <action android:name="com.app.FILTER_INIT_REGISTER" />
            <category android:name="android.intent.category.DEFAULT" />                
        </intent-filter>
</receiver>

Curious why the ReportingReceiver class is not getting the intent call?

回答1:

If your application only has a service and receivers then this won't work in Android 3.1 and later. The reason is that the system will not send broadcast Intents to application that are in the STOPPED STATE. An application is in the STOPPED STATE when it is first installed. It is removed from the STOPPED STATE when the user manually starts the application for the first time. It is returned to the STOPPED STATE if the user forces the application to stop using the application manager tool.

Since your application has no Activities, there is no way for the user to "start" it. Therefore it will never come out of the stopped state.

See http://developer.android.com/about/versions/android-3.1.html#launchcontrols



回答2:

As Android Addict says in his comment to David Wasser's answer ... there is a way around this behaviour.

Just add the following flag to the calling Intent. This will ensure that you also reach broadcast receivers from "stopped" applications.

http://developer.android.com/reference/android/content/Intent.html#FLAG_INCLUDE_STOPPED_PACKAGES

You can read more about this Android 3.1 change here

http://developer.android.com/about/versions/android-3.1.html#launchcontrols

and here

http://code.google.com/p/android/issues/detail?id=18225