要解决安卓前台通知消失的问题,可以使用以下代码示例:
NotificationCompat.Builder
的setOngoing(true)
方法将通知设置为常驻通知,这样即使用户清除了最近任务列表,通知也不会消失。NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My Notification")
.setContentText("This is an ongoing notification")
.setOngoing(true);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, builder.build());
NotificationManager
的cancel(notificationId)
方法。NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(notificationId);
PendingIntent
中添加一个取消通知的操作。// 创建取消通知的Intent
Intent cancelIntent = new Intent(this, CancelNotificationReceiver.class);
cancelIntent.setAction("CANCEL_NOTIFICATION");
cancelIntent.putExtra("notificationId", notificationId);
PendingIntent cancelPendingIntent = PendingIntent.getBroadcast(this, 0, cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// 创建通知
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My Notification")
.setContentText("This is an ongoing notification")
.setOngoing(true)
.setContentIntent(cancelPendingIntent); // 设置点击通知时的操作
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, builder.build());
BroadcastReceiver
来接收取消通知的广播,并在接收到广播时调用NotificationManager
的cancel(notificationId)
方法。public class CancelNotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("CANCEL_NOTIFICATION".equals(intent.getAction())) {
int notificationId = intent.getIntExtra("notificationId", 0);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(notificationId);
}
}
}
请注意,以上代码示例仅为参考,具体实现可能需要根据实际需求进行调整。
上一篇:安卓嵌入式开发
下一篇:安卓嵌套自定义控件的XML属性