blzb-android/app/src/main/java/com/cheng/blzb/manager/NotificationHelper.kt

106 lines
3.6 KiB
Kotlin

package com.cheng.blzb.manager
import android.app.Activity
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.fragment.app.FragmentManager
import com.cheng.blzb.R
import com.cheng.blzb.ui.dialog.TipDialog
import com.example.base.extensions.toast
import com.example.base.utils.Utils
object NotificationHelper {
private val notificationManager by lazy { Utils.getApp().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager }
private const val DEFAULT_CHANNEL_ID = "default"
private const val MESSAGE_CHANNEL_ID = "message"
private var _notificationId = 1000
/**
* 创建默认通知通道
*/
fun createDefaultChannel() {
createNotificationChannel(DEFAULT_CHANNEL_ID, "Default", NotificationManager.IMPORTANCE_DEFAULT)
}
/**
* 消息通知
*/
fun createMessageNotification(context: Context): Notification {
val channelId = createNotificationChannel(MESSAGE_CHANNEL_ID, "Message", NotificationManager.IMPORTANCE_HIGH)
val builder = NotificationCompat.Builder(context, channelId)
return builder
.setContentTitle("")
.setContentText("")
.setSmallIcon(R.mipmap.ic_launcher_icon)
.setCategory(Notification.CATEGORY_MESSAGE)
.build()
}
/**
* 取消通知
*/
fun cancelNotification(id: Int) {
notificationManager.cancel(id)
}
/**
* 创建通知通道
*
* @param channelId
* @param channelName
* @return
*/
private fun createNotificationChannel(channelId: String, channelName: String, importance: Int): String {
val channel = NotificationChannel(channelId, channelName, importance)
notificationManager.createNotificationChannel(channel)
return channelId
}
fun getNotificationId(): Int {
return ++_notificationId
}
/**
* 判断通知权限是否开启
*/
fun isNotificationEnabled(context: Context): Boolean {
return NotificationManagerCompat.from(context).areNotificationsEnabled()
}
/**
* 通知被禁用时显示提示
*/
fun showDisabledTip(activity: Activity, fm: FragmentManager) {
val f = TipDialog.newInstance("请开启通知权限", "未避免错过重要消息,请在设置中打开【允许通知】", "去设置", "取消", cancelable = false)
f.setOnSelectListener {
if (it == DialogEnum.CLICK_CANCEL) {
try {
//8.0及以上
val intent = Intent()
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
intent.putExtra(Settings.EXTRA_APP_PACKAGE, activity.packageName)
activity.startActivity(intent)
} catch (e: Exception) {
val intent = Intent()
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
intent.setData(Uri.fromParts("package", activity.packageName, null))
activity.startActivity(intent)
}
}
}
f.show(fm, TipDialog::class.java.simpleName)
}
}