接收gcm推送通知时刷新活动

Amr*_*ngh 50 android listview android-activity google-cloud-messaging

更新: 不推荐使用GCM,请使用FCM

如果我的应用程序处于打开状态,如何刷新接收gcm推送通知的活动.我有一个活动,其中包含从服务器填充数据的列表视图.我想刷新我的活动(这里再向listview添加一个项目),如果我收到gcm推送通知(其中还包含一些数据).

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

亲爱的评论员,请仔细阅读问题,我只需刷新列表(如果应用程序已打开且特定活动已打开),否则不需要相同.

Art*_*hur 140

花了我几个小时来搞清楚.发布在这里以防任何人有同样的问题.

这个想法是你必须将你的活动注册为广播接收者.最简单的方法是:

//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
    }
};
Run Code Online (Sandbox Code Playgroud)

以上代码包含您要"监听"事件的活动.

现在,我们如何向这个"倾听者"发送数据?转到您的推送通知处理程序(或您想要更新活动的位置),当您收到通知时调用此函数:

// 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);
}
Run Code Online (Sandbox Code Playgroud)

当您调用上述功能时,您的活动应该接收它.

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

注2:我切换到名为'otto'的库.它实际上是相同的事情,但更容易,'广播事件'在整个应用程序.这是一个链接http://square.github.io/otto/

  • 感谢您的解决方案,对于像我这样的Android新用户,在IntentFilter("unique_name")中,您必须将"unique_name"替换为您用来接收PUSH的广播接收器的相同滤镜操作(我有按照Google DEV https://developer.android.com/google/gcm/client.html的示例,如果您使用此示例,则必须将其更改为IntentFilter("com.google.android.c2dm.intent.接收") (5认同)