6

我在 Eclipse 的两个不同项目中有两个应用程序。一个应用程序 (A) 定义了一个首先启动的活动 (A1)。然后我从这个活动开始第二个项目(B)中的第二个活动(B1)。这工作正常。

我通过以下方式启动它:

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

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

Intent intent = new Intent("pacman.intent.action.BROADCAST");
intent.putExtra("message","Wake up.");
sendBroadcast(intent);

活动 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>

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

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

}

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

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

4

4 回答 4

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

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

于 2010-05-01T12:38:02.083 回答
2

Intent intent = new Intent("pacman.intent.action.BROADCAST");

对比

<android:name="android.intent.action.BROADCAST"/>

您确定在实际代码中使用相同的字符串吗?

于 2011-06-29T20:51:13.123 回答
1

无论我们在 android 内部传递什么动作,我们都必须在创建 Intent 对象或 Intent 的 setAction() 方法时使用相同的动作。当我们将在 Context 的 sendBroadcasteReceiver() 方法的帮助下发送这个 Intent 对象时,它会将此动作发送给所有接收者(未经许可),我们在 Manifest.xml 中设置的任何接收者都将(谁在意图中具有相同的动作-filter 标记)获取此操作。

于 2011-07-29T11:39:45.233 回答
0

还是不适合你?

尽管答案很有帮助,但我仍然遇到了问题。我在这里得到了解决方案。

发送广播时添加 ff 标志:

FLAG_INCLUDE_STOPPED_PACKAGES 标志在发送之前添加到意图,以指示允许该意图启动已停止应用程序的组件。

intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
于 2015-11-06T14:27:01.520 回答