Android-Notification

Notification

使用示例:

Intent intent = new Intent(this, NotificationActivity.class);

/**

* 参数1:Content

* 参数2:一般不用,传入0

* 参数3:Intent

* 参数4:确定PendingIntent的行为,一般传入0

*/

PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);

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))

    .setContentIntent(pi)//设置通知的意图(点击事件)

    .setAutoCancel(true)//设置通知点击后自动取消

    //设置通知提示音

    .setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Luna.ogg")))

    //设置通知时震动,long型数组内值分别为静止时长,振动时长,以此类推(单位:毫秒)

    .setVibrate(new long[]{0, 1000, 1000, 1000})

    //注意在清单文件中声明权限

    // 参数1:指示灯颜色、参数2:指示灯亮起时长、参数3:指示灯暗去时长

    .setLights(Color.GREEN, 1000, 1000)//设置通知时指示灯

    //使用通知的默认设置
    
    //.setDefaults(NotificationCompat.DEFAULT_ALL)

    //设置通知的长文字显示

    .setStyle(new NotificationCompat.BigTextStyle().bigText("this is a long                 
    notification,this is a long notification" +

        ",this is a long notification,this is a long notification," +
   
        "this is a long notification,this is a long notification"))

    //设置通知显示大图片

    .setStyle(new NotificationCompat.BigPictureStyle().bigPicture

        (BitmapFactory.decodeResource(getResources(),R.drawable.big_img)))

    //设置通知重要程度

    .setPriority(NotificationCompat.PRIORITY_MAX)

    .build();

manager.notify(1, notification);

【问题】

通知demo同样的代码能在安卓8.0以下运行,不能在8.0上运行,报以下错误:

原因就是:NotificationChannel是Android O新增的特性,为了兼容老代码,如果channelId为null的话,Android O会把通知归到“Other Channel”上。

Tip:将targetSdkVersion提到26以上的话,就必须设置channel了,不能为null。

解决:

注:通过这种方式创建后出现API一些问题:有些方法已过时,如下示:

此方式不能在安卓8.0以下运行!

解决版本适配问题,参阅博客:

https://blog.csdn.net/qq_34149526/article/details/82718708

猜你喜欢

转载自blog.csdn.net/qq_34149526/article/details/82718636
今日推荐