首页 > 解决方案 > 无法使用 FLAG_INCLUDE_STOPPED_PACKAGES 标志触发处于停止状态的 BroadcastReceiver

问题描述

用例:

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

应用2 BroadcastReceiver

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

应用2 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);
}

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

即使是上面的命令也无法触发BroadcastReceiver。但是如果我启动应用程序一次然后关闭它,那么上面的命令就能够触发广播接收器。

ps:正如您从代码中看到的那样,我正在从 a 广播意图Fragment,尽管我认为这不会有任何区别。

编辑:也尝试使用明确的意图,但仍然没有工作

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

标签: android-intentintentfilterandroid-broadcastreceiver

解决方案


推荐阅读