为另一个应用调用自定义广播接收器

时间:2012-12-10 14:38:49

标签: android android-broadcast

我有2个应用,App1和App2

在App1中,清单文件的BroadcastReceiverIncoming定义如下。

<receiver android:name="packagename.BroadcastReceiverIncoming"
          android:enabled="true"
          android:exported="true">
    <intent-filter>
        <action android:name="packagename.BroadcastReceiverIncoming" />
    </intent-filter>
 </receiver>

BroadcastReceiverIncoming在App1中定义。

现在在App2中,我正在调用它来调用广播接收器,但它现在正在以某种方式工作?

Intent intent = new Intent();
intent.setClassName("packageName", "packagename.BroadcastReceiverIncoming");
intent.setAction("packagename.BroadcastReceiverIncoming");
appContext.sendBroadcast(intent);

即使第2行已注释/未注释,它也不会调用BroadcastReceiverIncoming。

如果我致电adb shell am broadcast -n packageName/packagename.BroadcastReceiverIncoming,请通过adb 正在App1中正确调用BroadcastReceiverIncoming。

1 个答案:

答案 0 :(得分:2)

我的工作如下:

    myServiceReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context ctx, Intent data) {
            if (data.getAction().equals(POLayer.SVC_INTENT)) {
                final String alias = data.getStringExtra("alias");
                final String command = data.getStringExtra("action");
                if (command.equals("dosomething")) {
                    new DoSomethingTask().execute( alias );
                }
                             }
                     }
             };

  ....

  onCreate:
    final IntentFilter filter = new IntentFilter(POLayer.SVC_INTENT);
    filter.addAction(POLayer.ANOTHER_INTENT);
    this.registerReceiver(this.myServiceReceiver, filter);

发件人:

                Intent i = new Intent();
                i.setAction( SVC_INTENT );
                i.putExtra( "alias", theAlias );
                i.putExtra( "action", "dosomething" );
                this.sendBroadcast( i );

我看到的唯一区别是我不依赖于包/组件名称,而是定义我自己的ACTION。此外,所有名称都区分大小写,因此您可能需要检查packageName与packagename。