在《第一行代码》第二版的学习中,当我们学习到8.2.2通知的进阶技巧的通知播放自定义音频时,当我们按照书里的写法(如下)写时,我们发现并没有任何的效果
Notification notification = new NotificationCompat.Builder(MainActivity.this,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))
.setContentIntent(pi)
.setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Big_Easy.ogg")))
.setAutoCancel(true)//取消通知
.build();
这是因为《第一行代码》第二版使用的是sdk26以前的版本,在sdk26以后的版本谷歌推出了NotificationChannel渠道的概念,必须先通过向 createNotificationChannel()
传递 NotificationChannel
的实例在系统中注册应用的通知渠道,然后才能在 Android 8.0 及更高版本上提供通知。(详情参见创建通知 | Android 开发者 | Android Developers)
所以,为了解决这一问题我们必须使用NotificationChannel来完成通知声音,通知震动的使用。
因为这是仅仅是为了测试,这里我就使用系统自带的音频来完成测试。