Android 8.0 系统及其以上版本创建最基本的Notification

Android 8.0版本Notification有了重大改变,如果像《第一行代码》中写的一样,肯定是不行的,如:


NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); 
                Notification notifiction = new NotificationCompat.Builder(this)
                        .setContentTitle("This is a title")
                        .setContentText("This is a text")
                        .setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .build();
                notificationmanager.notify(1,notification);

Android O 版本新机制:

官方文档:

NotificationCompat.Builder的构造方法需要一个channelID,Android O版本及其以上必须有,低版本就可以忽略了。 

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle(textTitle)
        .setContentText(textContent)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT);

 创建channel:

String CHANNEL_ID = "my_channel_01";
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    CharSequence name = "my_channel_name";
                    String description = "my_channel_description";
                    int importance = NotificationManager.IMPORTANCE_DEFAULT;
                    NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
                    channel.setDescription(description);
                    NotificationManager notificationManager = getSystemService(NotificationManager.class);
                    notificationManager.createNotificationChannel(channel);
                    Notification notification = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID)
                            .setContentTitle("This is content title")
                            .setContentText("This is content text")
                            .setWhen(System.currentTimeMillis())
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                            .build();
                    notificationManager.notify(1,notification);
                }

设置一个CHANNEL_ID,然后进行版本控制,定义name,description,使用Notification的构造方法,创建一个NotificationChannel实例,然后调用createNotifiationChannel方法,在最后创建notification时别忘记CHANNEL_ID

。这样创建一个最基本的通知基于完成了。

你可能感兴趣的:(Android 8.0 系统及其以上版本创建最基本的Notification)