轉載請註明出處: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>