2016-12-07 2 views
3

В Firebase onMessageReceived(RemoteMessage remoteMessage) этот метод будет вызываться, когда ваше приложение находится в Foreground. Итак, при нажатии на уведомление вы можете открыть другое действие, скажем NotiicationActivity.Firebase onMessageReceived (RemoteMessage remoteMessage), не вызывается, когда приложение находится в фоновом режиме

Но что, если ваше приложение находится в фоновом режиме, этот метод не будет вызываться, и при нажатии на уведомление будет открыта только деятельность Launcher.

Так, как открыть NotificationActivity при нажатии уведомления, даже если наше приложение находится в фоновом режиме.

Мой код заключается в следующем:

public class MyFirebaseMessagingService extends FirebaseMessagingService { 

    private static final String TAG = "MyFirebaseMsgService"; 

    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 
     Log.d(TAG, "From: " + remoteMessage.getFrom()); 

     if (remoteMessage.getData().size() > 0) { 
      Log.d(TAG, "Message data payload: " + remoteMessage.getData()); 
     } 

     if (remoteMessage.getNotification() != null) { 
      Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); 
     } 

     sendNotification(remoteMessage.getNotification().getBody()); 

    } 

    private void sendNotification(String messageBody) { 
     Intent intent = new Intent(this, NewActivity.class); 
     intent.putExtra("key", messageBody); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, 
      PendingIntent.FLAG_ONE_SHOT); 
     Bitmap icon2 = BitmapFactory.decodeResource(getResources(), 
      R.mipmap.ic_launcher); 

     Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
     .setSmallIcon(R.mipmap.ic_launcher) 
     .setContentTitle("FCM Sample") 
     .setContentText(messageBody) 
     .setAutoCancel(true) 
     .setLargeIcon(icon2) 
     .setSound(defaultSoundUri) 
     .setContentIntent(pendingIntent); 

     NotificationManager notificationManager = 
     (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

     notificationManager.notify(new Random().nextInt() /* ID of notification */, notificationBuilder.build()); 
    } 
} 
+0

Прочитайте этот ответ: sloved вопрос [здесь ссылка] (http://stackoverflow.com/questions/ 40626233/firebase-onmessagereceived-not-called-when-app-isactive/40626866 # 40626866) –

ответ

3

onMessageReceived только срабатывает, когда приложение находится на переднем плане. Если приложение связано с фоном, вы все равно сможете получать уведомление, но onMessageReceived не будет запущен.

Поэтому мое предложение, на принимающей деятельности, вы можете получить данные из уведомления с помощью:

getIntent().getExtras(); 

Это должно работать соответствующим образом. Надеюсь, что это помогает :)

+0

Спасибо, что работает, я просто сделал это. 'if (getIntent(). GetExtras()! = Null) { // Я написал здесь. Целевое намерение = новое намерение (MainActivity.this, NotificationActivity.class); startActivity (намерение); } ' – Shekhar

+0

Не беспокойтесь @Shekhar, пожалуйста, проголосуйте, чтобы другие знали, что это решение работает. Спасибо. – kenix

0

попробовать и следуйте ссылке ниже:

Firebase Cloud Messaging for Android

+0

Этот учебник работает только тогда, когда ваше приложение находится на переднем плане. Я хочу открыть NotificationActivity, даже если приложение находится в фоновом режиме или даже не запущено. – Shekhar

0

В вашем sendNotification() метод:

private void showNotification(String message){ 
    Intent intent=new Intent(this, NotificationActivity.class); 
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    intent.putExtra("key", messageBody); 
    PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT); 

    NotificationCompat.Builder builder=new NotificationCompat.Builder(this) 
      .setAutoCancel(true) 
      .setContentTitle("FCM Sample") 
      .setContentText(message) 
      .setLargeIcon(icon2) 
      .setContentIntent(pendingIntent); 
    NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
    manager.notify(0,builder.build()); 

} 
Смежные вопросы

 Смежные вопросы