2016-07-28 105 views
1

當應用程序通過單擊通知位於前臺或後臺時,應用程序將調用onMessageReceived事件。我使用click_action通知。對嗎?通過單擊通知調用Firebase onMessageReceived

我在應用程序處於前臺時創建通知,當我單擊通知時,它會再次執行該方法並創建另一個通知。

回答

2

onMessageReceived是一種在Android客戶端從Firebase Cloud接收消息時調用的方法。通常,我們創建一個函數來在此方法中建立通知。

而當我們點擊通知時會發生什麼,我們可以使用pendingIntent。

我們可以看到this github repo

public class MyFirebaseMessagingService extends FirebaseMessagingService { 

private static final String TAG = "MyFirebaseMsgService"; 

// [START receive_message] 
@Override 
public void onMessageReceived(RemoteMessage remoteMessage) { 


    // TODO(developer): Handle FCM messages here. 
    Log.d(TAG, "From: " + remoteMessage.getFrom()); 

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

    // Check if message contains a notification payload. 
    if (remoteMessage.getNotification() != null) { 
     Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); 
    } 

    // Also if you intend on generating your own notifications as a result of a received FCM 
    sendNotification(remoteMessage.getNotification().getBody()); 
} 
// [END receive_message] 

/** 
* Create and show a simple notification containing the received FCM message. 
* 
* @param messageBody FCM message body received. 
*/ 
private void sendNotification(String messageBody) { 
    Intent intent = new Intent(this, MainActivity.class); 
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, 
      PendingIntent.FLAG_ONE_SHOT); 

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
      .setSmallIcon(R.drawable.ic_stat_ic_notification) 
      .setContentTitle("FCM Message") 
      .setContentText(messageBody) 
      .setAutoCancel(true) 
      .setSound(defaultSoundUri) 
      .setContentIntent(pendingIntent); 

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

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); 
} 
} 
2

無論onMessageReceived被稱爲取決於兩件事情,從谷歌的例子:

  • 數據電文總是導致onMessageReceived被稱爲
  • 當應用處於前臺時發出通知消息導致onMessageReceived被調用

當您的應用程序在後臺併發送通知消息時,會顯示自動生成的通知。

查看更多關於兩種類型的FCM消息here

click_action可用於指定在用戶點擊自動生成的通知時啓動哪個Activity,如果未指定,則啓動默認Activity。 click_action目前只能通過REST API使用。