接收 gcm 推送通知的刷新活动 [英] Refreshing activity on receiving gcm push notification
问题描述
更新: GCM 已弃用,请使用
如果我的应用打开,如何刷新接收 gcm 推送通知的活动.我有一个活动,其中包含填充了来自服务器的数据的列表视图.如果我收到 gcm 推送通知(其中还包含一些数据),我想刷新我的活动(在这里再向列表视图添加一项).
How to refresh activity on receiving gcm push notification if my app is open. I have an activity which contains listview filled with data from the server. I want to refresh my activity (here adding one more item to listview) , if I receive gcm push notification(which also contains some data).
- 一种替代方法是添加计时器,它会定期执行服务器请求并更新列表适配器数据,但我不想要这些,因为这会占用大量资源.
- 我是否需要添加广播接收器,它会在接收到 gcm 推送时触发,进一步请求更新的服务器数据并更新我的活动 UI?
亲爱的评论者,请仔细阅读问题,我只需要刷新列表(如果应用程序已打开且特定活动已打开)其他不需要.
Dear commentors, please read the question carefully, I only need to refresh the list (if app is open and that particular activity is open) else no need for same.
推荐答案
我花了几个小时才弄明白.在这里发帖以防其他人遇到同样的问题.
Took me a few hours to figure it out. Posting here in case anyone anyone else has the same problem.
这个想法是您必须将您的活动注册为广播接收器.最简单的方法是这样的:
The idea is that you have to register your activity as a broadcast receiver. The easiest way to do this is like so:
//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
}
};
上面的代码进入你想要监听"事件的活动.
The above code goes in the activity that you want to 'listen' for events.
现在,我们如何向这个侦听器"发送数据?转到您的推送通知处理程序(或从您想要更新您的活动的位置),当您收到通知时调用此函数:
Now, how do we send data to this 'listener'? Go to your push notification handler(or from where you want to update your activity) and when you receive a notification call this function:
// 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);
}
当您调用上述函数时,您的活动应该会收到它.
When you call the above function, your activity should receive it.
注意:您的 Activity 必须正在运行/打开才能接收广播 Intent
Note: Your activity must be running/open to receive the broadcast intent
注意2:我切换到了一个名为otto"的图书馆.它实际上做同样的事情,但更容易,在整个应用程序中广播事件".这是一个链接 http://square.github.io/otto/
Note2: I switched to a library called 'otto'. It does actually the same thing but easier, 'broadcasts events' thoughout the app. Here's a link http://square.github.io/otto/
这篇关于接收 gcm 推送通知的刷新活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!