001 Android8.0通知适配

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);
}

@RequiresApi(api = Build.VERSION_CODES.O)
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;
}
@RequiresApi(api = Build.VERSION_CODES.O)
public Notification.Builder getChannelNotification(String title, String content){
    return new Notification.Builder(getApplicationContext(), id)
            .setContentTitle(title)
            .setContentText(content)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setDefaults(Notification.DEFAULT_SOUND)
            .setAutoCancel(true);
}
public NotificationCompat.Builder getNotification_25(String title, String content){
    return new NotificationCompat.Builder(getApplicationContext())
            .setContentTitle(title)
            .setContentText(content)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setAutoCancel(true);
}
public void sendNotification(String title, String content){
    if (Build.VERSION.SDK_INT>=26){
        createNotificationChannel();
        Notification notification = getChannelNotification
                (title, content).build();
        getManager().notify(1,notification);
    }else{
        Notification notification = getNotification_25(title, content).build();
        notification.defaults = Notification.DEFAULT_SOUND
                | Notification.DEFAULT_VIBRATE;// 设置默认为系统声音
        notification.flags = Notification.FLAG_AUTO_CANCEL;// 点击后自动消失
        getManager().notify(1,notification);
    }
}

}

你可能感兴趣的:(001 Android8.0通知适配)