如何在Android中的不同应用程序中使用广播接收器?

6 android broadcastreceiver

我在这里有两个不同项目的应用程序在eclipse中.一个应用程序(A)定义首先启动的活动(A1).然后我从这个活动开始第二个项目(B)中的第二个活动(B1).这很好用.

我从以下方式开始:

Intent intent = new Intent("pacman.intent.action.Launch");
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

现在我想通过使用广播接收器发送两个活动之间的意图.在活动A1中,我按以下方式发送意图:

Intent intent = new Intent("pacman.intent.action.BROADCAST");
intent.putExtra("message","Wake up.");
sendBroadcast(intent);
Run Code Online (Sandbox Code Playgroud)

活动A1中负责此广播的清单文件部分如下:

<activity android:name="ch.ifi.csg.games4blue.games.pacman.controller.PacmanGame" android:label="@string/app_name">
    <intent-filter>
       <action android:name="android.intent.action.MAIN" />
       <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter>
       <action android:name="android.intent.action.BROADCAST" />
    </intent-filter>
</activity>
Run Code Online (Sandbox Code Playgroud)

在接收活动中,我在清单文件中按以下方式定义接收器:

<application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".PacmanGame"
                  android:label="@string/app_name"
                  android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="pacman.intent.action.Launch" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <receiver android:name="ch.ifi.csg.games4blue.games.pacman.controller.MsgListener" />
        </activity>

    </application>
Run Code Online (Sandbox Code Playgroud)

类消息监听器以这种方式实现:

public class MsgListener extends BroadcastReceiver {

    /* (non-Javadoc)
     * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("Message at Pacman received!");
    }

}
Run Code Online (Sandbox Code Playgroud)

不幸的是,从未收到过该消息.虽然调用了活动A1中的方法,但我从未在B1中收到意图.

任何提示如何解决这个问题?非常感谢!

Com*_*are 14

  1. 你的<receiver>元素需要成为元素的同伴<activity>,而不是孩子.
  2. 您的操作字符串应该在android.intent.action命名空间中,除非您为Google工作 - 使用ch.ifi.csg.games4blue.games.pacman.controller.BROADCAST或类似的东西
  3. <intent-filter>的自定义操作需要放在<receiver>,而不是发送或接收<activity>

有关实现清单注册的广播接收器(用于系统广播的Intent)的示例,请参见此处.