I have already create notification channel but still Crash at Android 8.1.0 Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification.
private void startForeground() {
Log.d("mqttservice", "mqttservice startForeground");
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
Log.i("MqttService", " startForeground, channelId == XP, channelName == XPMotors");
try {
final String channelId = "XP";
String channelName = "XPMotors";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
channel.setShowBadge(false);
NotificationManager manager = (NotificationManager) MqttService.this.getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) {
manager.createNotificationChannel(channel);
NotificationChannel c = manager.getNotificationChannel("XP");
//create失败时再次创建
if (c == null) {
manager.createNotificationChannel(channel);
}else{
}
c = manager.getNotificationChannel("XP");
if (c != null) {
Notification notification = new NotificationCompat.Builder(MqttService.this, channelId)
.setContentTitle("小鹏汽车")
.setContentText("正在运行中")
.setSmallIcon(R.mipmap.app_icon)
.setPriority(NotificationManager.IMPORTANCE_DEFAULT)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(100, notification);
} else {//走这里的话 可能会anr
Log.d("mqttservice", "mqttservice stopself");
}
}
} catch (Throwable e) {
Log.e("MqttService", " Exception == " + e.toString());
}
}
}