gpt4 book ai didi

android - 如何在 Android 的不同应用程序中使用 Broadcast Receiver?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:27:01 24 4
gpt4 key购买 nike

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

我按以下方式启动它:

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

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

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 中收到 Intent。

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

最佳答案

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

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

关于android - 如何在 Android 的不同应用程序中使用 Broadcast Receiver?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2749893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com