You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android:将FCM推送消息保存至SharedPreferences实现持久化显示

解决FCM消息持久化到SharedPreferences的问题

我来帮你搞定这个问题!要让FCM消息在Activity销毁后还能随时查看,把消息数据存到SharedPreferences里就可以了,下面是具体的实现步骤和代码示例:

第一步:在Activity中保存FCM消息到SharedPreferences

当你通过FCM通知的Intent打开ActivityResult时,先从Intent里取出消息内容,然后把它存入SharedPreferences。这样即使Activity被销毁,数据也会保留在本地。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_result);

    // 从FCM传递的Intent中获取消息标题和内容
    Intent incomingIntent = getIntent();
    String fcmTitle = incomingIntent.getStringExtra("fcm_title"); // 这里的key要和通知构建时的key一致
    String fcmMessage = incomingIntent.getStringExtra("fcm_message");

    // 初始化SharedPreferences,用一个专属的名称来区分存储的内容
    SharedPreferences fcmPrefs = getSharedPreferences("FCM_Saved_Messages", MODE_PRIVATE);
    SharedPreferences.Editor editor = fcmPrefs.edit();

    // 只有当Intent里确实有消息数据时才保存
    if (fcmTitle != null && fcmMessage != null) {
        editor.putString("latest_title", fcmTitle);
        editor.putString("latest_message", fcmMessage);
        editor.apply(); // 异步保存,比commit()更高效,适合大多数场景
    }

    // 调用方法显示保存的消息
    showSavedMessage(fcmPrefs);
}

// 专门用来读取并显示SharedPreferences里的消息
private void showSavedMessage(SharedPreferences prefs) {
    // 读取保存的消息,第二个参数是默认值(没有数据时显示空字符串)
    String savedTitle = prefs.getString("latest_title", "");
    String savedMessage = prefs.getString("latest_message", "");

    // 假设你在布局里有对应的TextView来展示消息
    TextView titleTv = findViewById(R.id.tv_notification_title);
    TextView messageTv = findViewById(R.id.tv_notification_content);

    // 如果有保存的消息,就显示到界面上
    if (!savedTitle.isEmpty() && !savedMessage.isEmpty()) {
        titleTv.setText(savedTitle);
        messageTv.setText(savedMessage);
    }
}

第二步:确保FCM通知的Intent携带消息数据

要注意在构建FCM通知的PendingIntent时,一定要把消息的标题和内容作为Extra传进去,这样Activity才能接收到数据。比如在你的FirebaseMessagingService的onMessageReceived方法里:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    // 获取FCM推送的通知内容
    String notificationTitle = remoteMessage.getNotification().getTitle();
    String notificationBody = remoteMessage.getNotification().getBody();

    // 构建打开ActivityResult的Intent
    Intent resultIntent = new Intent(this, ActivityResult.class);
    // 把消息数据放入Intent的Extra中
    resultIntent.putExtra("fcm_title", notificationTitle);
    resultIntent.putExtra("fcm_message", notificationBody);
    // 设置Intent的Flags,确保打开的是正确的Activity实例
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

    // 创建PendingIntent
    PendingIntent pendingIntent = PendingIntent.getActivity(
            this,
            0,
            resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
    );

    // 构建通知(记得先创建通知渠道,适配Android 8.0+)
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "YOUR_CHANNEL_ID")
            .setSmallIcon(R.drawable.ic_notification_icon)
            .setContentTitle(notificationTitle)
            .setContentText(notificationBody)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);

    // 发送通知
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(1, notificationBuilder.build());
}

额外注意点

  • 如果需要保存多条FCM消息,可以用Gson把消息列表转换成JSON字符串,再存入SharedPreferences,读取时再转成List对象。
  • 确保SharedPreferences的名称和存储用的Key是固定的,这样每次都能正确读取到数据。
  • 针对Android 8.0及以上版本,一定要提前创建通知渠道,否则通知可能无法正常显示。

内容的提问来源于stack exchange,提问作者Asmaa Mohamed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:36:58