您必须考虑到,当收到通知时,应用程序可能处于前台或后台,并且处理方式会有所不同。
您无法从该服务获取活动,相反,您必须告诉它在单击通知时哪个活动出现在前台并获取“附加”数据。
例如在通知服务器(nodejs)中使用这样的配置:
var message = {
notification: {
title: title,
body: text
},
data: {
title: title,
body: text,
latitude: latitude,
longitude: longitude,
name: name
},
android: {
priority: 'high',
notification: {
sound: 'default',
clickAction: '.PetNotificationActivity'
},
},
apns: {
payload: {
aps: {
sound: 'default'
},
},
},
tokens: registrationTokens
};
在该示例中,PetNotificationActivity 是我希望在打开通知时将其置于前台的活动。
并且,在 PetNotificationActivity 中类似这样的内容(用于后台/封闭应用案例):
public class PetNotificationActivity extends AppCompatActivity {
....
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pet_notification);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String latitudeValue = bundle.getString("latitude");
String longitudeValue = bundle.getString("longitude");
String nameValue = bundle.getString("name");
...
}
}
在服务中是这样的(对于前台情况):
public class PetNotificationService extends FirebaseMessagingService {
...
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getData().size() > 0) {
sendNotification(remoteMessage);
}
}
private void sendNotification(RemoteMessage remoteMessage) {
String title = remoteMessage.getData().get("title");
String messageBody = remoteMessage.getData().get("body");
String latitude = remoteMessage.getData().get("latitude");
String longitude = remoteMessage.getData().get("longitude");
String name = remoteMessage.getData().get("name");
Intent intent = new Intent(this, PetNotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("latitude", latitude);
intent.putExtra("longitude", longitude);
intent.putExtra("name", name);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
...
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
...
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}
}
Handling messages 上的 FCM 文档