.... ..问题: android8.0的技术革新中,需要在以往notification的基础上添加notificationChannel传输通道,否则会报错:Failed to post notification on channel “null”
... ..解决办法:1.如果代码中大量使用notification,需要将该方法新建一个类更佳
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
public class NotificationUtils extends ContextWrapper {
private NotificationManager manager;
public static final String id = "channel_1";
public static final String name = "channel_name_1";
public NotificationUtils(Context context){
super(context);
}
public void createNotificationChannel(){
NotificationChannel channel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
getManager().createNotificationChannel(channel);
}
private NotificationManager getManager(){
if (manager == null){
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
return manager;
}
public Notification.Builder getChannelNotification(String title, String content){
return new Notification.Builder(getApplicationContext(), id)
.setContentTitle(title)
.setContentText(content)
.setSmallIcon(android.R.drawable.stat_notify_more) ;
}
public NotificationCompat.Builder getNotification(String title, String content){
return new NotificationCompat.Builder(getApplicationContext())
.setContentTitle(title)
.setContentText(content)
.setSmallIcon(android.R.drawable.stat_notify_more);
}
public void sendNotification(String title, String content){
if (Build.VERSION.SDK_INT>=26){
createNotificationChannel();
Notification notification = getChannelNotification
(title, content).build();
getManager().notify(1,notification);
getManager().createNotificationChannel(mChannel);
}else{
Notification notification = getNotification(title, content).build();
getManager().notify(1,notification);
getManager().createNotificationChannel(mChannel);
}
}
}
... ..类中调用:
NotificationUtils notificationUtils = new NotificationUtils(this);
notificationUtils.sendNotification("测试标题", "测试内容");
网友评论