2

我想使用Firebase通知服务获取通知消息。我从Firebase发送消息,没关系。活动在后台时如何接收事件总线事件

我想要得到这个通知,如果用户在MainActivity中运行,我也想使用对话框显示弹出窗口。

如果用户运行其他活动,例如SettingActivityProfileActivity,则无论如何通知处理和用户运行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); 
} 

回答

2

你调用onStop()unregister(),所以您没有收到事件时MainActivity是在后台。

接收事件,即使Activity是在后台,你应该在onCreate()注册和注销onDestroy()(而非onResume()/onStop())。

移动以下行onCreate()

EventBus.getDefault().register(this); 

而且这样一来onDestroy()

EventBus.getDefault().unregister(this); 

还检查了Activity Lifecycle

+0

您节省了我的时间。谢谢 !! – TeyteyLan