Android 写通知栏方法

1、实例化 NotificaitonManager

NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

Android 8.0以上需要设定channel 否则不显示

 String channelID = "1";
        String channelName = "channel_name";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    
    
            NotificationChannel channel =  new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
            mNotificationManager.createNotificationChannel(channel);
        }//判断系统

2.初始化 Notificaiton

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);  
3.设置build属性。

初始化 Pending Intent

public PendingIntent getDefalutIntent(int flags){
    
    
        Intent intent;//定义跳转
        intent = new Intent(MainActivity.this,Main2Activity.class);
        PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, intent, flags);
        return pendingIntent;
    }
mBuilder.setContentTitle("测试标题")//设置通知栏标题
	.setContentText("测试内容") //设置通知栏显示内容
	.setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL)) //设置通知栏点击意图
//	.setNumber(number) //设置通知集合的数量
	.setTicker("测试通知来啦") //通知首次出现在通知栏,带上升动画效果的
	.setWhen(System.currentTimeMillis())//通知产生的时间,会在通知信息里显示,一般是系统获取到的时间(这是一个方法,需要自定义)
	.setPriority(Notification.PRIORITY_DEFAULT) //设置该通知优先级
//	.setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消  
	.setOngoing(false)//ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
	.setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合
	//Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission
	.setSmallIcon(R.drawable.ic_launcher);//设置通知小ICON
	.

last
发送通知:

 Notification notify = mBuilder.build();
        notify.flags = Notification.FLAG_AUTO_CANCEL;//设定点击后取消
        mNotificationManager.notify(1,notify);

猜你喜欢

转载自blog.csdn.net/u014627911/article/details/105184061
今日推荐