FCM (Firebase Cloud Messaging) 是Google提供的跨平台消息传递解决方案,允许服务器向客户端应用发送消息和通知。在Android应用中,FCM通知可以包含两种形式的数据:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 检查是否通过通知启动
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
Object value = getIntent().getExtras().get(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
// 处理特定数据
if (key.equals("custom_key")) {
String customData = getIntent().getExtras().getString("custom_key");
// 使用自定义数据
}
}
}
}
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// 检查消息是否包含数据负载
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
// 获取特定数据
String customValue = remoteMessage.getData().get("custom_key");
// 处理数据...
}
// 检查消息是否包含通知负载
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
}
原因:当应用在后台时,系统会优先处理通知消息,而忽略数据消息。 解决方案:
原因:服务器发送的数据格式与客户端预期不符。 解决方案:
原因:某些厂商设备会限制后台服务。 解决方案:
// 在FirebaseMessagingService中
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// 数据消息处理
Map<String, String> data = remoteMessage.getData();
if (!data.isEmpty()) {
// 处理数据
}
// 通知消息处理
RemoteMessage.Notification notification = remoteMessage.getNotification();
if (notification != null) {
// 可以在这里创建自定义通知
sendNotification(notification.getTitle(), notification.getBody(), data);
}
}
private void sendNotification(String title, String messageBody, Map<String, String> data) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// 将数据添加到Intent
for (Map.Entry<String, String> entry : data.entrySet()) {
intent.putExtra(entry.getKey(), entry.getValue());
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);
// 创建通知...
}
// 在MainActivity中
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
processFCMData(intent);
}
private void processFCMData(Intent intent) {
if (intent.getExtras() != null) {
// 处理来自通知的数据
}
}
通过以上方法,您可以有效地在Android应用中获取和处理FCM通知中的数据。
没有搜到相关的文章