1.权限<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
fun sendTest(){
manager=getSystemService(NOTIFICATION_SERVICE) as NotificationManager
var mUri= Settings.System.DEFAULT_NOTIFICATION_URI
//设置NotificationChannel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) //如果系统是8.0以上的就需要用到NotificationChannel
{
var mChannel= NotificationChannel("1", "hh", NotificationManager.IMPORTANCE_LOW)
mChannel.setDescription("description of this notification");
mChannel.setSound(mUri, Notification.AUDIO_ATTRIBUTES_DEFAULT);
mChannel.enableVibration(true)
mChannel.enableLights(true)
mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
manager.createNotificationChannel(mChannel);
}
//跳转activity意图
var intent= Intent(applicationContext, MainActivity::class.java)
var pi =PendingIntent.getActivity(applicationContext,1,intent,PendingIntent.FLAG_UPDATE_CURRENT)//PendingIntent.FLAG_UPDATE_CURRENT Intent.FLAG_ACTIVITY_NEW_TASK
if(NotificationManagerCompat.from(applicationContext).areNotificationsEnabled()){
if(applicationContext!=null){
var notification= NotificationCompat.Builder(applicationContext,"1")
var remoteViews = RemoteViews(packageName,R.layout.notifica)
var intentbtn = Intent()
intentbtn.action = "Delete"
intentbtn.putExtra("test","test")
//自定义view中的点击事件只能靠广播来进行业务的处理,即点击->发送广播->onReceive处理
val pendingIntent = PendingIntent.getBroadcast(
applicationContext,
100,
intentbtn,
PendingIntent.FLAG_UPDATE_CURRENT
)
remoteViews.setOnClickPendingIntent(R.id.tv_delete, pendingIntent)
notification.setContent(remoteViews)
notification.setContentTitle("通知")
notification .setContentText("content")
notification .setSmallIcon(R.drawable.ic_launcher_background)
notification.setLargeIcon(BitmapFactory.decodeResource(Resources.getSystem(),R.drawable.ic_launcher_foreground))
notification .setPriority(NotificationCompat.PRIORITY_DEFAULT);
notification.setLights(0xff00ff00.toInt(), 3000, 1000);
notification.setAutoCancel(true)
notification .setChannelId("1")
notification .setNumber(15)
notification.setContentIntent(pi)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){//悬挂式Notification,5.0后显示
notification.setCategory(NotificationCompat.CATEGORY_MESSAGE);
notification.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notification .setFullScreenIntent(pi, true)
}
notification.setDefaults(NotificationCompat.DEFAULT_ALL); //闪灯
manager.notify(1, notification .build())
}
}else{
}
}
```