uniapp 对接极光推送

19 阅读3分钟
// 使用方法 如果onLaunch里面有用户id,就调用,如果没有就在登录成功之后进行调用
import config from '@/config'
// #ifdef APP-PLUS
const jpushModule = uni.requireNativePlugin("JG-JPush")
// #endif

import { checkNotifyPermission } from '@/utils/common'

const systemInfo = uni.getSystemInfoSync()
const {
	platform,
	deviceBrand
} = systemInfo
// console.log("systemInfo", systemInfo);

// 用户端=C 
const tagList = ['C']
// 注册id
let registerID = ''
const sequence = 1
// 语音实例
let innerAudioContext = null
// jpush收到的语音数
const jPushStorageKey = 'jPushUnReadCount'
export const startJpush = (startQuery = {}) => {
	if (!config.openJpush) {
		return
	}
	const {
		userId
	} = startQuery
	if (!userId) {
		console.error('无用户userId,停止调用极光推送')
		return
	}
	const openNotifyStatus = checkNotifyPermission()
	console.log("userId", userId,openNotifyStatus);
	if (!openNotifyStatus) {
		console.error('没有授权,停止调用极光推送')
		return
	}
	// #ifdef APP-PLUS
	// 设置 debug 模式
	jpushModule.setLoggerEnable(true);
	// 初始化函数
	jpushModule.initJPushService();
	// 监听链接状态
	jpushModule.addConnectEventListener(result => {
		console.log("jpush连接", result)
	})
	// 检测通知权限
	const {
		notificationAuthorized
	} = uni.getAppAuthorizeSetting()
	// console.log('notificationAuthorized', notificationAuthorized);
	switch (notificationAuthorized) {
		// 表示请求授权被拒绝,无法再次请求授权;(此情况需要引导用户打开系统设置,在设置页中打开权限)
		case 'denied':
			let cancelNotify = uni.getStorageSync('cancelNotify')
			if (cancelNotify !== '1') {
				uni.showModal({
					title: '通知提示',
					content: '我们需要通知权限以便及时为您推送重要信息,是否前往打开?',
					success: (res) => {
						if (res.confirm) {
							jpushModule.openSettingsForNotification()
						} else if (res.cancel) {
							console.log('用户点击取消');
							uni.setStorageSync('cancelNotify', '1')
						}
					}
				});
			}
			break;
		case 'not determined':
			if (platform === 'android') {
				plus.android.requestPermissions(
					['android.permission.POST_NOTIFICATIONS'],
					function(result) {
						console.log("开始获取权限", result);
					},
					function(error) {
						console.error('检查权限出错:', error);
					}
				);
			} else if (platform === 'ios') {
				const UIApplication = plus.ios.import("UIApplication");
				const app = UIApplication.sharedApplication();
				if (app.currentUserNotificationSettings) {
					const settings = app.currentUserNotificationSettings();
					settings.plusGetAttribute("types");
					plus.ios.deleteObject(settings);
				} else {
					app.enabledRemoteNotificationTypes();
				}
				plus.ios.deleteObject(app);
				plus.ios.deleteObject(UIApplication);
			}
			break;
		default:
			break;
	}

	console.log('platform', platform,deviceBrand);


	// 获取 RegistrationID,只有当应用程序成功注册到 JPush 的服务器时才返回对应的值,否则返回空字符串
	// jpushModule.getRegistrationID(result => {
	// 	console.log("获取极光注册id", result);
	// 	registerID = result.registerID
	// })

	if (userId) {
		// 设置标签
		// jpushModule.addTagAliasListener(result => {
		// 	console.warn('标签监听回调:', result);
		// })
		jpushModule.addTags({
			tags: tagList,
			sequence
		})
		// 设置别名
		// jpushModule.addTagAliasListener(result => {
		// 	console.log('别名监听回调:', result);
		// })
		jpushModule.setAlias({
			alias: userId,
			sequence
		})
	}
	
	// 小米设置自定义铃声
	if (platform === 'android' && deviceBrand==='xiaomi') {
		jpushModule.setChannelAndSound({
			channel: '订单语音提醒',
			channel_id: 'xxx',
			sound: 'sound'
		})
	}
	// OPPO设置自定义铃声
	if (platform === 'android' && deviceBrand==='oppo') {
		jpushModule.setChannelAndSound({
			channel: '抢单大厅来单',
			channel_id: 'xxx',
			sound: 'sound'
		})
	}
	// 华为设置自定义铃声
	if (platform === 'android' && deviceBrand==='huawei') {
		jpushModule.setChannelAndSound({
			channel: '订单语音提醒',
			channel_id: 'xxx',
			sound: 'sound'
		})
	}
	jpushModule.setBadge(0)
	// 通知事件回调
	jpushModule.addNotificationListener(result => {
		console.log("通知事件回调", result);
		const {
			// 唯一标识通知消息的 ID
			messageID,
			// 对应 Portal 推送通知界面上的“通知标题”字段
			title,
			// 对应 Portal 推送通知界面上的“通知内容”字段
			content,
			// 对应 Portal 推送消息界面上的“可选设置”里的附加字段,一般是后端附加的字段
			extras,
			// 对应原生返回的通知内容,如需要更多字段请查看该字段内容
			iOS,
			// 对应原生返回的通知内容,如需要更多字段请查看该字段内容
			android,
			// 分为notificationArrived和notificationOpened两种, 区分 是 通知收到 还是 点击通知
			notificationEventType
		} = result
		switch (notificationEventType) {
			// 通知收到,自行处理后续逻辑,比如存储数据库
			case 'notificationArrived':
				// console.log("开始增加缓存未读数");
				// let unReadCount = uni.getStorageSync(jPushStorageKey)
				// unReadCount++
				// uni.setStorageSync(jPushStorageKey, unReadCount)
				// jpushModule.setBadge(Number(unReadCount))
				// console.log("unReadCount", unReadCount);

				if (extras?.voice) {
					if (innerAudioContext) {
						try {
							innerAudioContext.pause();
							innerAudioContext.destroy()
							innerAudioContext = null
						} catch (e) {
							//TODO handle the exception
						}
					}
					const innerAudioContext = uni.createInnerAudioContext();
					innerAudioContext.autoplay = false;
					innerAudioContext.src = extras.voice
					innerAudioContext.play()
					innerAudioContext.onPlay(() => {
						console.log('开始播放');
					});
					innerAudioContext.onError((res) => {
						console.error('播放错误', res);
					});
				}
				break;
				// 点击通知
			case 'notificationOpened':
				// console.log("开始减少缓存未读数");
				// let count = uni.getStorageSync(jPushStorageKey)
				// count--
				// uni.setStorageSync(jPushStorageKey, count)
				// jpushModule.setBadge(Number(count))
				// console.log("count", count);
				/**
				 * 对extras字段做出区分,
				 * @pageUrl 即将跳转的页面链接
				 * @notifyType 通知类型 navigateTo==跳转普通页面 switchTab==跳转tabbar页面
				 * @voice 音频url
				 */
				const pageUrl = extras?.pageUrl
				const notifyType = extras?.notifyType
				let navigateKeys = ['navigateTo', 'switchTab']
				if (navigateKeys.includes(notifyType) && pageUrl) {
					switch (notifyType) {
						case 'navigateTo':
							uni.navigateTo({
								url: pageUrl
							})
							break;
						case 'switchTab':
							uni.switchTab({
								url: pageUrl
							})
							break;
						default:
							break;
					}
				}

				break;
			default:
				break;
		}

	});

	// #endif
}