如果我的应用打开,如何刷新接收 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/