Android 14后如何使用通知和前台服务

127 阅读1分钟

通知 Notification 官网: developer.android.google.cn/develop/ui/…

权限

创建通知 NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle(textTitle) .setContentText(textContent) .setPriority(NotificationCompat.PRIORITY_DEFAULT);

创建渠道并设置重要性

NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); channel.setDescription(description); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel);

服务官网: developer.android.google.cn/develop/bac…

启动服务: startForegroundService(intent)

将服务提升到前台 ServiceCompat.startForeground() ,会在服务的 onStartCommand() 方法中调用

参数: 服务。 一个正整数,用于唯一标识状态栏中的服务通知。 Notification 对象本身。 用于标识服务所执行工作的前台服务类型 (不同的服务类型还需要申请声明另外的权限)