无法使用FLAG_INCLUDE_STOPPED_PACKAGES标志在停止状态下触发BroadcastReceiver

时间:2019-02-07 06:18:10

标签: android-intent intentfilter android-broadcastreceiver

用例:

  

单击按钮时启动操作背景。 >操作位于BroadcastReceiver中的Application1中,并且> Intent正在从Application2中广播。

Application2 BroadcastReceiver

public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Receiver triggered", Toast.LENGTH_SHORT).show();
    }
}

Application2 AndroidManifest.xml

<receiver
android:name="com.my.package.MyBroadcastReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
       <action android:name="my.custom.action" />
       <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

Application1 sendMyBroadcast()(单击按钮时被调用):

public void sendMyBroadcast(){
Toast.makeText(getActivity(), "Sending broadcast", Toast.LENGTH_SHORT).show();
        Intent intent =  new Intent("my.custom.action");
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        this.getActivity().sendBroadcast(intent);
}

我还尝试使用以下命令从adb测试我的BroadcastReceiver
adb shell am broadcast -a my.custom.action --include-stopped-packages

即使以上命令也无法触发BroadcastReceiver。但是,如果我启动应用程序一次然后将其关闭,则上面的命令将能够触发BroadcastReceiver。

ps:从代码中可以看到,我正在广播Fragment中的意图,尽管我认为这没有什么区别。
< br /> 编辑:还尝试使用显式意图,但仍然无法正常运行

public void sendMyBroadcast(){
Toast.makeText(getActivity(), "Sending broadcast", Toast.LENGTH_SHORT).show();
        Intent intent =  new Intent("my.custom.action");
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        ComponentName component = new ComponentName("com.my.package", "com.my.package.MyBroadcastReceiver");
        intent.setComponent(component);
        this.getActivity().sendBroadcast(intent);
}

0 个答案:

没有答案