class MainActivity : AppCompatActivity() { //通知服务管理器,用它来弹出或取消一个通知 var manager:NotificationManager? = null var no1 = 1 //为了每次发送通知的id不同,定义了一个步长为2的no1的变量 var no2 = 1 //为了每次发送通知的id不同,定义了一个步长为2的no1的变量 //通知渠道id companion object{ val channelIdNormal = "channelIdNormal" val channelIdImportant = "channelIdImportant" } //创建通知渠道:可以创建多个不同等级的渠道 fun createNotificationChannel(){ manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val normal = NotificationChannel( channelIdNormal, "普通通知", NotificationManager.IMPORTANCE_LOW ) normal.description = "这是普通通知,不太重要" val important = NotificationChannel( channelIdImportant, "重要通知", NotificationManager.IMPORTANCE_HIGH ) important.description = "这是重要通知,建议开启" val channels: MutableList<NotificationChannel> = ArrayList() channels.add(normal) channels.add(important) manager?.createNotificationChannels(channels) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) createNotificationChannel() send1.setOnClickListener{ //利用渠道channelIdNormal发通知 val notificationCompatBuilder = NotificationCompat.Builder( applicationContext, channelIdNormal ) val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher) val notification = notificationCompatBuilder.setTicker("ticker是啥" + no1) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(bitmap) .setContentTitle("通知标题" + no1) .setContentText("通知内容" + no1) .setContentIntent(getPendingIntent())//通知体点击处理 .setWhen(System.currentTimeMillis())//设置通知时间 .setAutoCancel(true) .build() manager?.notify(no1, notification) no1 += 2 } send2.setOnClickListener{ //利用渠道channelIdImportant发通知 val notificationCompatBuilder = NotificationCompat.Builder( applicationContext, channelIdImportant ) val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher) val notification = notificationCompatBuilder.setTicker("ticker是啥?" + no2) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(bitmap) .setContentTitle("通知标题" + no2) .setContentText("通知内容" + no2) .setContentIntent(getPendingIntent())//通知体点击处理 .setWhen(System.currentTimeMillis())//设置通知时间 .setAutoCancel(true) .build() manager?.notify(no2, notification) no2 += 2 } } //点击通知体后启动应用到指定activity(TaskStackBuilder解决返回直接到系统屏幕的尴尬) fun getPendingIntent(): PendingIntent { val intent = Intent(this, DetailActivity::class.java) val stackBuilder = TaskStackBuilder.create(this) //<activity android:name=".DetailActivity" //android:parentActivityName=".MainActivity"/> stackBuilder.addParentStack(DetailActivity::class.java) stackBuilder.addNextIntent(intent) return stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ) } }
API26以后的Notification
最新推荐文章于 2024-03-05 18:11:15 发布