我花了几个小时才弄清楚。在此发布以防其他人遇到同样的问题。
这个想法是你必须将你的活动注册为广播接收器。最简单的方法是这样的:
//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
}
};
上面的代码放入您想要“监听”事件的活动中。
现在,我们如何向这个“监听器”发送数据?转到您的推送通知处理程序(或从您想要更新活动的位置),当您收到通知时调用此函数:
// 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);
}
当您调用上述函数时,您的活动应该会收到它。
Note:您的活动必须正在运行/打开才能接收广播意图
Note2:我切换到一个名为“otto”的库。它实际上做同样的事情,但更简单,在整个应用程序中“广播事件”。这是一个链接http://square.github.io/otto/ http://square.github.io/otto/