用kotlin实现类似微信的notification通知悬浮框

公司项目有个聊天的功能,需要实现这个notification通知悬浮框的功能,做的时候发现不同的系统,有些不同。

//当程序在后台时,接收到消息的通知
fun notification(neirong: String, time: Long){//两个参数分别时通知内容和时间
    var manager=context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
    var mUri= Settings.System.DEFAULT_NOTIFICATION_URI
    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);
    }
    var intent= Intent(context, MainActivity::class.java)
    var pi =PendingIntent.getActivity(context,1,intent,PendingIntent.FLAG_UPDATE_CURRENT)//PendingIntent.FLAG_UPDATE_CURRENT  Intent.FLAG_ACTIVITY_NEW_TASK
    if(NotificationManagerCompat.from(context).areNotificationsEnabled()){
        if(context!=null){
            var notification= NotificationCompat.Builder(context,"1")
            notification.setContentTitle("通知")
            notification .setContentText(neirong)
            notification .setSmallIcon(R.drawable.notifytubiao)
            Log.e("xinxi","当前sdk版本:"+Build.VERSION.SDK_INT)
            notification.setLargeIcon(BitmapFactory.decodeResource(Resources.getSystem(),R.drawable.ic_launcher))
            notification.setWhen(time)//System.currentTimeMillis()
            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(Notification.VISIBILITY_PUBLIC);
                notification .setFullScreenIntent(pi, true)
            }
           notification.setDefaults(NotificationCompat.DEFAULT_ALL);//闪灯
            manager.notify(1, notification .build())
        }
    }else{

    }
}
 
 

到这里基本可以实现悬浮的通知了,但是还是有个Bug,如果用户禁止了悬浮通知后,软件会在后台通知触发的时候就会直接打开PendingIntent


这个问题我也还没有解决,如果有人解决麻烦说一声。

猜你喜欢

转载自blog.csdn.net/weixin_40119478/article/details/80605507