2016-07-28 70 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使用。