Tey*_*Lan 3 notifications android firebase greenrobot-eventbus firebase-notifications
我想使用 Firebase 通知服务获取通知消息。我正在从 Firebase 发送消息,没关系。
如果用户运行,我想收到此通知,MainActivity我也想使用对话框显示弹出窗口。
如果用户运行其他活动,例如SettingActivity或ProfileActivity,通知处理无论如何,用户运行MainActivity弹出窗口突然出现。
为此,我使用 Greenbot Eventbus。当我在里面MainActivity并且通知来时它出现所以它可以。但是当我在里面时,另一个Activity通知没有来。
如何处理这个消息直到来MainActivity?
public class NotificationService extends FirebaseMessagingService {
private static final String TAG = "evenBus" ;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "onMessageReceived");
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
// do nothing if Notification message is received
Log.d(TAG, "Message data payload: " + remoteMessage.getNotification().getBody());
String body = remoteMessage.getNotification().getBody();
EventBus.getDefault().post(new NotificationEvent(body));
}
}
}
Run Code Online (Sandbox Code Playgroud)
主要活动
@Override
protected void onResume(){
EventBus.getDefault().register(this);
}
// This method will be called when a MessageEvent is posted (in the UI thread for Toast)
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(NotificationEvent event) {
Log.v("onMessageEvent","Run");
Toast.makeText(MainActivity.this, event.getBody(), Toast.LENGTH_SHORT).show();
alertSendActivity("title",event.getBody());
}
@TargetApi(11)
protected void alertSendActivity(final String title,final String data) {
alt = new AlertDialog.Builder(this,
AlertDialog.THEME_DEVICE_DEFAULT_LIGHT).create();
alt.setTitle(title);
alt.setMessage(data);
alt.setCanceledOnTouchOutside(false);
alt.setCancelable(false);
alt.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
alt.dismiss();
}
});
alt.show();
}
protected void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
Run Code Online (Sandbox Code Playgroud)
你打电话unregister()的onStop(),所以当你没有收到事件MainActivity是在后台。
要Activity在后台接收事件,您应该注册onCreate()和注销onDestroy()(而不是onResume()/ onStop())。
将以下行移动到onCreate():
EventBus.getDefault().register(this);
Run Code Online (Sandbox Code Playgroud)
而这个onDestroy():
EventBus.getDefault().unregister(this);
Run Code Online (Sandbox Code Playgroud)
另请查看活动生命周期。
| 归档时间: |
|
| 查看次数: |
2374 次 |
| 最近记录: |