android - 在不启动 Activity 的情况下将 Intent 从 GcmIntentService 发送到当前 Activity

标签 android android-intent google-cloud-messaging

如何从 GcmItentService 向当前打开的 Activity 发送 Intent。在更新 Activity 中的列表之前,我需要来自推送通知的数据。我不想要的是调用 startActivity(Intent) (因为显然 Activity 已经打开)。此外,当 Activity 仍处于打开状态时,不会调用 onResume 方法。假设我有一个要发送到当前 Activity 的字符串,我该怎么做才能实现这一点?

我已经完成了此线程中所述的操作: Intent Extras of GCMIntentService is not passed ,但我无法让它工作。非常感谢简单的分步说明。

最佳答案

您可以简单地使用 LocalBroadcastManager。

Helper to register for and send broadcasts of Intents to local objects within your process. This is has a number of advantages over sending global broadcasts with sendBroadcast(Intent):

  • You know that the data you are broadcasting won't leave your app, so don't need to worry about leaking private data.
  • It is not possible for other applications to send these broadcasts to your app, so you don't need to worry about having security holes they can exploit.
  • It is more efficient than sending a global broadcast through the system.
Intent intent = new Intent(YOUR_ACTION_NAME);
intent.putExtra("PushType", "test");            
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

在您的 Activity 中编写一个接收器来处理操作“YOUR_ACTION_NAME”

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LocalBroadcastManager.getInstance(this).registerReceiver(
            messageReceiver, new IntentFilter("YOUR_ACTION_NAME"));
}


private BroadcastReceiver messageReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {

    }
};

更多详情:LocalBroadcastManager

关于android - 在不启动 Activity 的情况下将 Intent 从 GcmIntentService 发送到当前 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25267090/

相关文章:

java - Android TCP - 应用程序关闭时套接字不会断开连接

java - 滚动时 OnNestedScroll 值不改变

Android:如何从 TextView 链接本地 HTML 文件

android - Intent extras 未删除/替换

android - 创建 Intent 并将其命名为当前日期和时间

android - 我们如何在 Google Cloud Messaging 的 Android 模拟器中找到设备 token

java - 在 WebView 中使用 GOOGLE TRANSLATE。 "Desktop"工作, "Mobile"不工作

javascript - 如何将 Google 标签管理器与 React Native 应用程序集成?

android - 一旦应用程序在 Android 中的小米和联想设备上被杀死,就不会收到 GCM 通知

安卓 : Google Cloud Messaging Error