我在Eclipse的两个不同项目中有两个应用程序。一个应用程序(A)定义了一个 Activity (A1),该 Activity 首先开始。然后,我从该 Activity 开始第二个项目(B)中的第二个 Activity (B1)。这很好。

我通过以下方式启动它:

Intent intent = new Intent("pacman.intent.action.Launch");
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);

现在,我想使用广播接收器在两个 Activity 之间发送意图。在 Activity A1中,我通过以下方式发送意图:
Intent intent = new Intent("pacman.intent.action.BROADCAST");
intent.putExtra("message","Wake up.");
sendBroadcast(intent);

Activity A1中 list 文件中负责此广播的部分如下:
<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>

在接收 Activity 中,我在 list 文件中以以下方式定义接收者:
<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>

类消息侦听器是通过以下方式实现的:
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!");
    }

}

不幸的是,该消息从未收到。尽管调用了 Activity A1中的方法,但我从未在B1中收到任何意图。

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

最佳答案

  • 您的<receiver>元素必须是<activity>元素的同级元素,而不是子元素。
  • 除非您为Google工作,否则您的操作字符串应而不是android.intent.action命名空间中-使用ch.ifi.csg.games4blue.games.pacman.controller.BROADCAST或类似的方法代替
  • 您需要将带有自定义操作的<intent-filter>放置在<receiver>上,而不是发送或接收<activity>

  • 实现 list 注册的广播接收器的See here for an example(用于系统广播的Intent)。

    07-24 09:47
    查看更多