解决android 通知不显示问题

在学习《第一行》代码的时候,学到使用通知章节时书上的代码不能在手机上显示通知。
原因:NotificationCompat.Builder()过时
解决办法:android 8.0 在NotificationCompat.Builder()中添加一个chanlId参数,在写的时候添加上。
在每次使用通知时对系统版本进行判断(否则会报错)8.0及以上需要设好“channelId”(唯一与后面的NotificationCompat.Builder()相同)、“channelName”(用户看得到的信息)、“importance”(重要等级)这三个重要参数,然后创建到NotificationManager

//MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener{

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       Button sendNotice =(Button) findViewById(R.id.send_notic);
       sendNotice.setOnClickListener(this);
   }
   @Override
   public void onClick(View v){
       switch (v.getId()){
           case R.id.send_notic:
               NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
               
               //需添加的代码
               if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                   String channelId = "default";
                   String channelName = "默认通知";
                   manager.createNotificationChannel(new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH));
               }
              //
               Notification notification =new NotificationCompat.Builder(this,"default")
                       .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;

       }
   }
}
  • 21
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值