NotificationManager中FLAG_UPDATE_CURRENT与FLAG_CANCEL_CURRENT 区别

本文详细解析了 Android 中 PendingIntent 的两种旗帜 FLAG_UPDATE_CURRENT 和 FLAG_CANCEL_CURRENT 的使用区别。前者用于更新多个通知中的 Intent 数据至最新状态,而后者仅响应首个通知。

 

 

问:今天下午我把PendingIntent.FLAG_UPDATE_CURRENT和PendingIntent.FLAG_CANCEL_CURRENT的区别测试出来了,前者不创建PendingIntent,Intent中的数据全清空,后者新建PendingIntent,而Intent中的数据全清空,我现在不懂的是,什么时候用前者,什么时候用后者呢? 

 

 

答:PendingIntent contentIntent = PendingIntent.getActivity(context, 
num, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

对于FLAG_UPDATE_CURRENT,如果上面的num为常量, 
则对于先后出现的若干Notification,则所有对应的Intent里面的extra被更新为最新的, 
就是全部同一为最后一次的。 

相反,如果num每次不一样,则里面的Inent的数据没被更新。 


对于FLAG_CANCEL_CURRENT,则只响应最前面的第一条Notifiacation,后面所有的不响应..

 

package com.example.notificationdemo; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.NotificationCompat; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; public class MainActivity extends AppCompatActivity { private static final String TAG = "NotificationDemo"; private static final int NOTIFYID_1 = 1; private static final String CHANNEL_ID = "default_channel"; // UI Components private Button btnShowNormal; private Button btnCloseNormal; // Notification related private NotificationManager notificationManager; private Bitmap largeBitmap; private NotificationCompat.Builder notificationBuilder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EdgeToEdge.enable(this); // Initialize views initViews(); // Setup notification system initNotificationSystem(); // Set click listeners setupClickListeners(); } private void initViews() { btnShowNormal = findViewById(R.id.btn_show_normal); btnCloseNormal = findViewById(R.id.btn_close_normal); // Apply window insets for edge-to-edge experience ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> { Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); return insets; }); } private void initNotificationSystem() { // Get NotificationManager service notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Create notification channel (required for Android 8.0+) createNotificationChannel(); // Load large bitmap for big picture style (handle potential OOM) try { largeBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.large_notification_icon); } catch (OutOfMemoryError e) { Log.e(TAG, "Failed to load large bitmap: " + e.getMessage()); largeBitmap = null; } } private void createNotificationChannel() { // Create the NotificationChannel, but only on API 26+ (Android 8.0) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.default_channel_name); String description = getString(R.string.default_channel_description); int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); channel.setDescription(description); // Register the channel with the system notificationManager.createNotificationChannel(channel); } } private void setupClickListeners() { // Show notification button btnShowNormal.setOnClickListener(v -> showNotification()); // Cancel notification button btnCloseNormal.setOnClickListener(v -> cancelNotification()); } @SuppressLint("UnspecifiedImmutableFlag") private void showNotification() { try { // Create an explicit intent for an Activity in your app Intent intent = new Intent(this, NotificationTargetActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // Create pending intent (handle different Android versions) PendingIntent pendingIntent; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE ); } else { pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT ); } // Build notification notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setContentTitle("普通通知") .setContentText("这是普通通知的内容") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) .setAutoCancel(true); // Add large icon if available if (largeBitmap != null) { notificationBuilder.setLargeIcon(largeBitmap); } // Add sound, vibration, and lights notificationBuilder.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notification_sound)) .setVibrate(new long[]{0, 300, 200, 300}) .setLights(0xFF00FF00, 1000, 1000); // Show notification notificationManager.notify(NOTIFYID_1, notificationBuilder.build()); } catch (Exception e) { Log.e(TAG, "Failed to show notification: " + e.getMessage()); Toast.makeText(this, "通知发送失败", Toast.LENGTH_SHORT).show(); } } private void cancelNotification() { try { notificationManager.cancel(NOTIFYID_1); Toast.makeText(this, "通知已取消", Toast.LENGTH_SHORT).show(); } catch (Exception e) { Log.e(TAG, "Failed to cancel notification: " + e.getMessage()); } } @Override protected void onDestroy() { super.onDestroy(); // Clean up resources if (largeBitmap != null && !largeBitmap.isRecycled()) { largeBitmap.recycle(); largeBitmap = null; } } }这是MainActivity的代码
最新发布
09-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值