转载请注明出处:https://blog.csdn.net/u011038298/article/details/84346108
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build
import java.util.*
/**
* 应用程序
*/
class BaseApplication : Application() {
override fun onCreate() {
super.onCreate()
createNotificationChannel()
}
/**
* 创建通知栏渠道
*/
private fun createNotificationChannel() {
/**
* 在API 26+ 创建NotificationChannel
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val list = ArrayList<HashMap<String, String>>()
var hashMap: HashMap<String, String> = HashMap()
hashMap["name"] = "聊天"
hashMap["description"] = "聊天消息通知"
hashMap["channel"] = Constant.notifyChannelChat
list.add(hashMap)
hashMap = HashMap()
hashMap["name"] = "订阅"
hashMap["description"] = "订阅消息通知"
hashMap["channel"] = Constant.notifyChannelSubscription
list.add(hashMap)
hashMap = HashMap()
hashMap["name"] = "推荐"
hashMap["description"] = "推荐消息通知"
hashMap["channel"] = Constant.notifyChannelRecommend
list.add(hashMap)
hashMap = HashMap()
hashMap["name"] = "新闻"
hashMap["description"] = "新聞消息通知"
hashMap["channel"] = Constant.notifyChannelNews
list.add(hashMap)
hashMap = HashMap()
hashMap["name"] = "其他"
hashMap["description"] = "其他消息通知"
hashMap["channel"] = Constant.notifyChannelOther
list.add(hashMap)
val notificationManager = getSystemService(NotificationManager::class.java)
for (i in list.indices) {
val map = list[i]
val textName = MapUtil.getMapValue(map, "name")
val textDescription = MapUtil.getMapValue(map, "description")
val textChannel = MapUtil.getMapValue(map, "channel")
val channelChat = NotificationChannel(textChannel, textName, NotificationManager.IMPORTANCE_DEFAULT).apply {
description = textDescription
}
notificationManager.createNotificationChannel(channelChat)
}
}
}
}
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Button
import java.util.*
/**
* 主界面
*/
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.btn_notification).setOnClickListener {
val map = HashMap<String, String>()
map["channel"] = "1"
map["title"] = "张三"
map["content"] = "你最近还好吗?"
map["big_text"] = "-------------------------------------------------------------"
// https://developer.android.com/training/notify-user/build-notification?hl=zh-cn#java
NotificationUtil.sendNotification(this, map)
}
}
}
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import android.support.v4.app.NotificationCompat
import android.support.v4.app.NotificationManagerCompat
import android.text.TextUtils
import java.util.*
/**
* 通知栏工具类
*/
object NotificationUtil {
fun sendNotification(context: Context?, map: Map<String, String>?) {
if (context != null && map != null) {
val channel = MapUtil.getMapValue(map, "channel", "0")
val channelId = Constant.notifyChannelOther
when (channel) {
"0" -> Constant.notifyChannelOther
"1" -> Constant.notifyChannelChat
"2" -> Constant.notifyChannelNews
"3" -> Constant.notifyChannelRecommend
"4" -> Constant.notifyChannelSubscription
}
val title = MapUtil.getMapValue(map, "title")
val content = MapUtil.getMapValue(map, "content")
// 设置通知内容,构造函数要求您提供通道ID。这是与Android 8.0(API级别26)及更高版本兼容所必需的,但旧版本会忽略这一点
var mBuilder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(title)
.setContentText(content)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
val bigText = MapUtil.getMapValue(map, "big_text")
// 如果bigText的值不为空
if (!TextUtils.isEmpty(bigText)) {
// 如果您希望通知更长,可以通过添加样式模板来启用可扩展通知
mBuilder.setStyle(NotificationCompat.BigTextStyle().bigText(bigText))
}
// 为应用中的活动创建明确的意图
val intent = Intent(context, NotificationClickReceiver::class.java).apply {
action = NotificationClickReceiver.noticeClick
putExtras(MapUtil.getBundle(map))
}
val pendingIntent = PendingIntent.getBroadcast(context, Random().nextInt(1000), intent, PendingIntent.FLAG_UPDATE_CURRENT)
mBuilder.setContentIntent(pendingIntent)
// 显示通知,注意:从Android 8.1(API级别27)开始,应用程序无法每秒发出超过一次的通知。
// 如果您的应用在一秒钟内发布了多个通知,则它们都会按预期显示,但每秒只有第一个通知发出声音
with(NotificationManagerCompat.from(context)) {
// notificationId is a unique int for each notification that you must define
notify(Random().nextInt(1000), mBuilder.build())
}
}
}
}
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast
/**
* 监听通知栏点击事件
*/
class NotificationClickReceiver : BroadcastReceiver() {
companion object {
const val noticeClick = "android.intent.action.noticeClick"
}
override fun onReceive(context: Context?, intent: Intent?) {
if (context != null && intent != null && intent.action != null && intent.action == noticeClick) {
// 通知栏被点击
val bundle = intent.extras
if (bundle != null) {
Toast.makeText(context, "收到消息", Toast.LENGTH_SHORT).show()
}
}
}
}
import android.os.Bundle
import android.text.TextUtils
/**
* Map工具类
*/
object MapUtil {
/**
* 根据map的key取map的值
*/
fun getMapValue(map: Map<String, String>, key: String): String {
// 因为map为非安全的,map的key和value有可能为null,所以要加入判断,在取值时可以附加一个空字符串来避免空指针
return if (map.containsKey(key)) map[key] + "" else ""
}
/**
* 根据map的key取map的值,当map的值为空时取传过来的默认值
*/
fun getMapValue(map: Map<String, String>, key: String, defaultValue: String): String {
// 因为map为非安全的,map的key和value有可能为null,所以要加入判断,在取值时可以附加一个空字符串来避免空指针
return if (map.containsKey(key)) {
val value = map[key]
return when {value != null -> value
else -> defaultValue
}
} else {
defaultValue
}
}
/**
* 把map转换成bundle
*/
fun getBundle(map: Map<String, String>): Bundle {
val bundle = Bundle()
for ((key, value) in map) {
if (!TextUtils.isEmpty(key)) {
bundle.putString(key, value)
}
}
return bundle
}
}
/**
* 常量类
*/
object Constant {
// 通知渠道ID:即时通讯
const val notifyChannelChat = "chat"
// 通知渠道ID:订阅笋盘
const val notifyChannelSubscription = "subscription"
// 通知渠道ID:物件推荐
const val notifyChannelRecommend = "recommend"
// 通知渠道ID:地产新闻
const val notifyChannelNews = "news"
// 通知渠道ID:其他通知
const val notifyChannelOther = "other"
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="">
<application
android:name=".BaseApplication">
<receiver android:name=".NotificationClickReceiver">
<intent-filter>
<action android:name="android.intent.action.noticeClick" />
</intent-filter>
</receiver>
</application>
</manifest>