我希望您知道基于 FCM 的消息传递创建了两种类型的通知
首先,我们从 on 开始创建的通知onMessageReceived()
方法,这里需要注意的一点是onMessageReceived()
如果应用程序位于前台,则会被触发。
其次,当应用程序处于后台时,FCM 会创建自己的默认通知,在本例中onMessageReceived()
不会被拦截,因此我们不能自己设置待处理的意图。
注意:当您在“数据”消息的情况下向您的应用程序发送“通知”推送消息时,上述类型就会发挥作用onMessageReceived()
无论应用程序处于前台还是后台都会触发(从 FCM 控制台发送的通知是“通知”类型的推送消息)
回到你的问题,目前尚不清楚你是从 FCM 控制台发送推送消息还是发出 FCM 服务器请求,所以让我们在这里举例说明。
- FCM 控制台发送的消息:
从 FCM 通知面板中的高级部分发送数据有效负载,如下所示
当应用程序位于前台时onMessageReceived()
将会被拦截
使用下面的代码接收数据负载
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Displaying data in log
//It is optional
//Calling method to generate notification
sendNotification(remoteMessage.getData());
}
//This method is only generating push notification
//It is same as we did in earlier posts
private void sendNotification(Map<String, String> messageBody) {
Intent intent = new Intent(this, SplashScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(
this,
0,
setNotificationRoute(messageBody),
PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.sym_def_app_icon)
.setContentTitle(messageBody.get("title"))
.setContentText(messageBody.get("text"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
private Intent setNotificationRoute(Map<String, String> messageBody) {
Intent intent = null;
String type = messageBody.get("type");
if (type != null) {
switch (type) {
case "android": //intercept your payload here to create swit
intent = new Intent(this, MainActivity.class);
break;
default:
break;
}
}
return intent;
}
}
如果应用程序在后台,则在通知时单击应用程序将在“默认”活动上打开,您可以通过在活动的意图过滤器中的应用程序清单中添加以下行来将任何活动设置为默认活动:
<category android:name="android.intent.category.DEFAULT" />
在此活动中,您可以调用以获取意图额外信息,然后获取数据有效负载来决定您需要进行哪个活动。代码如下
.
.
.
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
setNotificationRoute(getIntent().getExtras());
.
.
}
private void setNotificationRoute(Bundle extras) {
String type = extras.getString("type");
Intent intent = null;
if (type != null) {
switch (type) {
case "message":
String room = extras.getString("room");
intent = new Intent(this, MainActivity.class);
startActivity(intent);
break;
default:
break;
}
}
}
-
从 FCM 服务器发送的消息:从上面的 FCM 控制台发送的消息与将以下 json 正文作为 post 请求发送到 FCM 服务器相同:
{
"notification": {
"title": "Hi Tester",
"text": "News for testing",
"sound": "default",
"badge": 0
},
"data":{
"type": "credits"
},
"priority": "high",
"to": "{{device_token}}"
}
对于这种情况,拦截通知的过程将是相同的。