8.0后通知增加channel机制,需要对不同版本进行适配

    实现了一个适配Androi8.0的通知类

    1. public class MyNotification {
    2. /**
    3. * 发送通知方法
    4. */
    5. public static void sendNotification(Context context, int notifNum) {
    6. // 通知功能
    7. NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    8. // 新版适配
    9. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    10. NotificationChannel nChannel = new NotificationChannel("channel001", "通道001", NotificationManager.IMPORTANCE_HIGH);
    11. nManager.createNotificationChannel(nChannel);
    12. Notification notification = getNotificationWithChannel("通知", "这是当前通知计数" + notifNum, "channel001", context);
    13. nManager.notify(0x001, notification);
    14. }
    15. // 旧版
    16. else {
    17. Notification notification = getNotification("通知", "这是当前通知计数" + notifNum, context);
    18. nManager.notify(0x001, notification);
    19. }
    20. System.out.println("notification异步任务启动输出测试");
    21. }
    22. /**
    23. * 新版适配
    24. */
    25. @TargetApi(Build.VERSION_CODES.O)
    26. public static Notification getNotificationWithChannel(String Title, String Content, String ChannelId, Context context) {
    27. Notification.Builder builder = new Notification.Builder(context, ChannelId);
    28. return builder.setContentTitle(Title)
    29. .setContentText(Content)
    30. .setWhen(System.currentTimeMillis())
    31. .setSmallIcon(R.drawable.img0)
    32. .build();
    33. }
    34. /**
    35. * 旧版方法
    36. */
    37. public static Notification getNotification(String Title, String Content, Context context) {
    38. NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    39. return builder.setContentTitle(Title)
    40. .setContentText(Content)
    41. .setWhen(System.currentTimeMillis())
    42. .setSmallIcon(R.drawable.img0)
    43. .build();
    44. }
    45. }