android - 接收 gcm 推送通知时刷新 Activity

标签 android listview android-activity google-cloud-messaging

Update: GCM is deprecated, use FCM

如果我的应用打开,如何刷新接收 gcm 推送通知的 Activity 。我有一个包含 ListView 的 Activity ,其中填充了来自服务器的数据。如果我收到 gcm 推送通知(其中还包含一些数据),我想刷新我的 Activity (这里向 ListView 添加一个项目)。

  • 另一种方法是添加 timer,它会定期执行服务器请求并更新列表适配器数据,但我不想要这些,因为它会占用大量资源。
  • 我是否需要添加 广播接收器,它会在接收 gcm push 时触发,进一步请求更新的服务器数据并更新我的 Activity UI?

尊敬的评论者,请仔细阅读问题,我只需要刷新列表(如果应用程序已打开并且该特定 Activity 已打开)否则无需相同 .

最佳答案

我花了几个小时才弄明白。在这里发帖以防其他人有同样的问题。

这个想法是您必须将您的 Activity 注册为广播接收器。最简单的方法是这样的:

//register your activity onResume()
@Override
public void onResume() {
    super.onResume();
    context.registerReceiver(mMessageReceiver, new IntentFilter("unique_name"));
}

//Must unregister onPause()
@Override
protected void onPause() {
    super.onPause();
    context.unregisterReceiver(mMessageReceiver);
}


//This is the handler that will manager to process the broadcast intent
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        // Extract data included in the Intent
        String message = intent.getStringExtra("message");

        //do other stuff here
    }
};

上面的代码进入你想要“监听”事件的 Activity 中。

现在,我们如何向这个“监听器”发送数据?转到您的推送通知处理程序(或从您要更新 Activity 的位置),当您收到通知时调用此函数:

// This function will create an intent. This intent must take as parameter the "unique_name" that you registered your activity with
static void updateMyActivity(Context context, String message) {

    Intent intent = new Intent("unique_name");

    //put whatever data you want to send, if any
    intent.putExtra("message", message);

    //send broadcast
    context.sendBroadcast(intent);
}

当您调用上述函数时,您的 Activity 应该会收到它。

注意:您的 Activity 必须正在运行/打开才能接收广播 Intent

Note2:我切换到了一个名为 'otto' 的库。它实际上做同样的事情,但更简单,在应用程序中“广播事件”。这是一个链接http://square.github.io/otto/

关于android - 接收 gcm 推送通知时刷新 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22252065/

相关文章:

android - React native-fbsdk 未知问题?

java - 从模糊的堆栈跟踪中查找异常原因

android - MediaPlayer 如何停止播放多个声音

android - 如何在 Android 2.2 中禁用 ListView 过度滚动?

android - Viewpager 不在协调器布局中滚动

android - 如何在 onCreate 中将 View 添加到 fragment

java - 如何解决尝试在空对象引用上调用虚拟方法 'void android.widget.TextView.setText(java.lang.CharSequence)'

android - 我想在 ListView 中检测哪个 onFling 事件的 ListItem

android:处理应用程序崩溃并启动特定的 Activity

android - 为什么原生 WLClient 生命周期绑定(bind)到 Activity 生命周期