2
我想使用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));
}
}
}
MainActiviy
@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);
}
您節省了我的時間。謝謝 !! – TeyteyLan