在收到GCM推送通知清爽活动 [英] Refreshing activity on receiving gcm push notification
问题描述
如何为刷新上的活动的接收GCM推送通知如果我的应用程序是打开。我有一个包含列表视图充满了来自服务器的数据的活动。我想刷新我的活动( 这里再增加一个项目的ListView 的),如果我收到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推进一步要求更新服务器数据触发并更新我的活动的用户界面?
尊敬的评论者,请仔细阅读问题,我只需要为刷新列表(如果应用程序是开放的,特定的活动是开放的)的否则没有必要相同
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
}
};
以上code进去要'听'事件的活动。
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.
注意:您的活动必须运行/打开接收广播意向
Note: Your activity must be running/open to receive the broadcast intent
注2 :我切换到一个叫奥托库。它实际上做同样的事情,但更容易,'广播事件'thoughout应用程序。这里有一个链接 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屋!