java.lang.RuntimeException: invalid channel for service notification
在应用中使用台前服务同时创建通知报:
Android 在API26之后原本的NotificationCompat.Builder (Context context)被废弃,创建通知需要使用新的构造器NotificationCompat.Builder (Context context, String channelId)
String CHANNEL_ID = "com.example.test"; String CHANNEL_NAME = "TEST"; NotificationChannel notificationChannel = null; NotificationCompat.Builder builder = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH); NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager.createNotificationChannel(notificationChannel); } Intent intent = new Intent(this, HomeActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder = new NotificationCompat.Builder(this, CHANNEL_ID). setContentTitle(getResources().getString(R.string.app_name)). setContentText(getResources().getString(R.string.notice_001)). setWhen(System.currentTimeMillis()). setSmallIcon(R.mipmap.app_icon). setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.app_icon)). setContentIntent(pendingIntent).setDefaults(NotificationCompat.FLAG_ONGOING_EVENT) .setPriority(Notification.PRIORITY_MAX); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//SDK版本>=21才能设置悬挂式通知栏 builder.setCategory(String.valueOf(Notification.FLAG_ONGOING_EVENT)) .setVisibility(Notification.VISIBILITY_PUBLIC) .setColor(getResources().getColor(R.color.white)); Intent intent2 = new Intent(); PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent2, 0); builder.setFullScreenIntent(pi, true); } Notification notification = builder.build(); startForeground(1, notification);
注意的是:API28以后,申请前台服务需要静态注册权限,不然的话会报对应的权限异常
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
效果: