今天看着《第一行代码》,准备实现一下书中所说的notification通知功能。非常简单的代码如下所示 结果运行起来,无论怎么样点击button,都不会产生通知。一开始怀疑是模拟器的问题,于是我在手机上尝试,结果仍然显示不出来。这时我心想不应该啊,书上写的怎么会错呢?于是我决定看一下NotificationManager源码看看到底是哪里出了问题。 点开notify方法,发现它其实调用的是notifyAsUser方法,不过看了notifyAsUser方法我还是看不出来为什么显示不出来。忽然看到下面的fixNotification方法中提到了Build.VERSION_CODES,于是我就想到有没有可能是安卓版本的问题?点击Build进去,搜索NotificationManager之后,我终于找到了原因。在安卓版本8.0(O)前面的注释中写到: 原来在8.0版本之后需要使用notification channels,于是我修改代码 运行完,就可以成功显示了,记录一下这个小坑, 希望可以帮助到大家@Override public void onClick(View v) { switch(v.getId()){ case R.id.send_notice: NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); Notification notification = new NotificationCompat.Builder(this) .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(); manager.notify(1,notification); break; default: break; } }
* <li>The {@link android.app.NotificationManager} now requires the use of notification channels.</li>
Notification notification = null; NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ String id = "channelId"; String name = "channelName"; NotificationChannel channel = new NotificationChannel(id,name,NotificationManager.IMPORTANCE_LOW); manager.createNotificationChannel(channel); notification = new Notification.Builder(this) .setChannelId(id) .setContentTitle("This is content title O") .setContentText("This is content text O") .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher)) .build(); }else{ notification = new NotificationCompat.Builder(this) .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(); } manager.notify(1,notification);
本网页所有视频内容由 imoviebox边看边下-网页视频下载, iurlBox网页地址收藏管理器 下载并得到。
ImovieBox网页视频下载器 下载地址: ImovieBox网页视频下载器-最新版本下载
本文章由: imapbox邮箱云存储,邮箱网盘,ImageBox 图片批量下载器,网页图片批量下载专家,网页图片批量下载器,获取到文章图片,imoviebox网页视频批量下载器,下载视频内容,为您提供.
阅读和此文章类似的: 全球云计算