Android8.0通知适配

《Android第一行代码(第2版)》中8.2节使用通知,MainActivity中使用:

Notification.Builder builder = new Notification.Builder(this, "channel_1");
                Notification notification =
                        builder.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))
                                .setAutoCancel(true)
                                .setContentIntent(pi)
                                .build();

测试机为Android8.0.0版本,发现无法运行,查看文章得知Android Oreo的通知写法与Android 7有所不同,正确写法为:

Notification.Builder builder = new Notification.Builder(this, "channel_1");
                Notification notification =
                        builder.setContentTitle("This is content title")
                                .setContentText("This is content text")
                                .setWhen(System.currentTimeMillis())
                                .setSmallIcon(android.R.drawable.stat_notify_more)
                                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                                .setAutoCancel(true)
                                .setContentIntent(pi)
                                .build();

通知兼容写法参考:

http://blog.csdn.net/z642385985/article/details/78583980?locationNum=9&fps=1

另外,取消系统状态上的通知图标方法,本书中提到两种方法,但经测试后,只有一种方法可用:

.setAutoCancel(true)



你可能感兴趣的:(Android)