Some checks failed
Uniapp 自动化打包 CI/CD / 打包 Uniapp 项目 (push) Has been cancelled
67 lines
2.0 KiB
JavaScript
67 lines
2.0 KiB
JavaScript
// utils/notification-permission.js
|
||
export default {
|
||
// 检查通知权限
|
||
checkPermission(callback) {
|
||
if (plus.os.name !== "Android") {
|
||
callback(true) // iOS 默认返回 true,另外可以用 APNs 检查
|
||
return
|
||
}
|
||
|
||
try {
|
||
let NotificationManagerCompat = plus.android.importClass("androidx.core.app.NotificationManagerCompat")
|
||
let context = plus.android.runtimeMainActivity()
|
||
let manager = NotificationManagerCompat.from(context)
|
||
callback(manager.areNotificationsEnabled())
|
||
} catch (e) {
|
||
console.error("检查通知权限出错:", e)
|
||
callback(false)
|
||
}
|
||
},
|
||
|
||
// 打开通知权限设置页面
|
||
openPermissionSetting() {
|
||
if (plus.os.name !== "Android") return
|
||
|
||
try {
|
||
let main = plus.android.runtimeMainActivity()
|
||
let Intent = plus.android.importClass("android.content.Intent")
|
||
let Settings = plus.android.importClass("android.provider.Settings")
|
||
|
||
let intent = new Intent()
|
||
if (parseInt(plus.device.sdkVersion) >= 33) {
|
||
// Android 13 及以上
|
||
intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
|
||
intent.putExtra(Settings.EXTRA_APP_PACKAGE, main.getPackageName())
|
||
} else {
|
||
// Android 8 ~ 12
|
||
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS")
|
||
intent.putExtra("app_package", main.getPackageName())
|
||
intent.putExtra("app_uid", main.getApplicationInfo().uid)
|
||
}
|
||
main.startActivity(intent)
|
||
} catch (e) {
|
||
console.error("跳转通知设置页失败:", e)
|
||
}
|
||
},
|
||
|
||
// 统一方法:检查并申请
|
||
ensurePermission(next) {
|
||
this.checkPermission((enabled) => {
|
||
if (enabled) {
|
||
next && next() // 已有权限,继续逻辑
|
||
} else {
|
||
uni.showModal({
|
||
title: "通知权限未开启",
|
||
content: "请开启通知权限以接收消息提醒",
|
||
confirmText: "去开启",
|
||
success: (res) => {
|
||
if (res.confirm) {
|
||
this.openPermissionSetting()
|
||
}
|
||
}
|
||
})
|
||
}
|
||
})
|
||
}
|
||
}
|