You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Android Studio中禁用Firebase推送通知的自动清除(点击通知打开UserDetailsActivity前不删除通知)

解决Firebase推送通知点击前禁止清除的问题

Hey there! I see you're trying to make sure your Firebase push notification doesn't get cleared before the user taps it to open UserDetailsActivity. Let's walk through fixing your current implementation step by step.

现有代码的问题点

  • 自动清除设置错误:你用了setAutoCancel(true),这会让系统在用户点击通知后立刻清除它,更关键的是用户仍能手动滑动清除通知,不符合你“打开界面前禁止删除”的需求。
  • 错误启动ActivitystartService(new Intent(getApplicationContext(),UserDetailsActivity.class))是完全错误的用法——UserDetailsActivity是Activity而非Service,且这些调用完全多余,因为你已经通过PendingIntent关联了点击通知启动Activity的逻辑。
  • PendingIntent兼容性:你的PendingIntent.FLAG_ONE_SHOT虽能运行,但在Android 12及以上版本,建议配合PendingIntent.FLAG_IMMUTABLE(无需修改Intent内容时)来保证兼容性。

修改后的完整代码

@Override 
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) { 
    super.onMessageReceived(remoteMessage); 
    Log.d(TAG, "From: " + remoteMessage.getFrom()); 
    Log.d("msg", "onMessageReceived: " + remoteMessage.getData().get("message") + " hey " + remoteMessage.getSentTime()); 

    if (remoteMessage.getData().size() > 0) { 
        Log.d(TAG, "Message data payload: " + remoteMessage.getData()); 
        if("Pagamento".equals(remoteMessage.getData().get("title"))){ 
            HashMap<String,String> map = new HashMap<>(); 
            map.put("title", remoteMessage.getData().get("title")); 
            String parametro1 = remoteMessage.getData().get("Parametro1"); 
            String[] separator = parametro1.split(":"); 
            String orderId = separator[1]; 
            map.put("orderId", orderId); 

            Intent intent = new Intent(this, UserDetailsActivity.class); 
            intent.putExtra("pushNotification", map);
            // 添加NEW_TASK确保在Service中启动Activity生效
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
            // 传递通知ID,方便后续清除
            int notificationId = (int) remoteMessage.getSentTime();
            intent.putExtra("notificationId", notificationId);

            // 配置PendingIntent,适配Android 12+
            int pendingIntentFlags = PendingIntent.FLAG_UPDATE_CURRENT;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                pendingIntentFlags |= PendingIntent.FLAG_IMMUTABLE;
            }
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, pendingIntentFlags); 

            String channelId = "Default"; 
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId) 
                    .setSmallIcon(R.mipmap.ic_push_notificatioin) 
                    .setContentTitle(remoteMessage.getNotification().getTitle()) 
                    .setContentText(remoteMessage.getNotification().getBody()) 
                    .setAutoCancel(false) // 关闭点击自动清除
                    .setOngoing(true) // 设置为持续通知,用户无法手动滑动清除
                    .setContentIntent(pendingIntent); 

            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 
                NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT); 
                manager.createNotificationChannel(channel); 
            } 

            manager.notify(notificationId, builder.build()); 

            Log.d(TAG, "Message data payload processed"); 
        } 
    } 

    if (remoteMessage.getNotification() != null) { 
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); 
        // 无需重复启动Activity,PendingIntent已处理点击逻辑
    } 
}

关键改动说明

  1. 禁止通知被提前清除

    • 替换setAutoCancel(true)setAutoCancel(false),避免点击后立刻清除通知。
    • 添加setOngoing(true),将通知设为“持续通知”,用户无法手动滑动删除,完美满足“打开界面前禁止删除”的需求。
  2. 修正Activity启动逻辑

    • 删除所有错误的startService调用,依赖PendingIntent处理点击启动Activity的逻辑。
    • 给Intent添加FLAG_ACTIVITY_NEW_TASK,因为在FirebaseMessagingService(Service组件)中启动Activity必须添加此标志。
  3. 后续手动清除通知
    由于设置了setOngoing(true)setAutoCancel(false),通知不会自动清除,需在UserDetailsActivity中手动清除:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_details);
    
        // 获取推送时传递的通知ID并清除通知
        int notificationId = getIntent().getIntExtra("notificationId", -1);
        if(notificationId != -1){
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.cancel(notificationId);
        }
    }
    

这样修改后,通知会一直显示在状态栏,用户无法手动删除,只有点击打开UserDetailsActivity后才会被清除,完全符合你的需求!

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

火山引擎 最新活动