仅向特定活动发送广播

CSc*_*ulz 10 android intentfilter broadcastreceiver intentservice

我有一个Activity在方法中创建一个带有IntentFilterBroadcastReceiver: onCreate(...)

IntentFilter iFilter = new IntentFilter("action");

receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

    }
};

registerReceiver(receiver, iFilter);
Run Code Online (Sandbox Code Playgroud)

另一方面是IntentService,它将发送一些数据:

Intent intent = new Intent(getApplicationContext(), receiver.class);
intent.setAction("action");

[...]

sendBroadcast(intent);
Run Code Online (Sandbox Code Playgroud)

但它似乎不起作用.没有收到广播.
我的服务类是在一个android lib中,也许这会给你带来麻烦.

感谢您的任何建议.

aro*_*ero 10

只需使用您的操作创建意图.

Intent intent = new Intent("action");
[...]
sendBroadcast(intent);
Run Code Online (Sandbox Code Playgroud)

并考虑将"action"重命名为更有意义的内容,例如"com.my.package.actions.SOME_ACTION".

如果您只希望应用程序组件接收广播,请使用:

  1. 使用signature保护级别在Manifest中注册权限(并为该权限定义使用权限).更多这里.
  2. 使用sendBroadcast(intent, permission),并在1中指定权限.


and*_*per 6

如果意图仅在您的应用程序内,请考虑使用LocalBroadcastManager