2

Firebase Notificationサービスを使用して通知メッセージを取得したいとします。 Firebaseからのメッセージを送信しています。大丈夫です。アクティビティがバックグラウンドのときにイベントバスイベントを受信する方法

ユーザーがMainActivityで実行している場合、この通知を受け取ってもらいたいのですが、ダイアログを使用してポップアップを表示したいと思います。

ユーザーが他のアクティビティ(例:SettingActivityまたはProfileActivity)を実行した場合は、通知ハンドルとユーザ実行MainActivityのポップアップが突然表示されます。

これを行うには、Greenbot Eventbusを使用しています。私が内部にいるときMainActivityと通知が来るので、それはOKです。しかし、私は別の内にいるとき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

MainActivityが背景にあるときに、イベントを受信しないようにするには、onStop()unregister()を呼んでいます。 Activityがバックグラウンドで動作している場合でも、あなたは(というonResume()/onStop()よりも)onDestroy()onCreate()に登録し、登録解除すべきイベントを受信する

onDestroy()

EventBus.getDefault().register(this); 

そして、この1:

onCreate()に次の行を移動し

EventBus.getDefault().unregister(this); 

をもActivity Lifecycleをチェックしてください。

+0

私の時間を保存しました。ありがとうございました !! – TeyteyLan

関連する問題