capacitor-plugin-jpush
TypeScript icon, indicating that this package has built-in type declarations

1.0.7 • Public • Published

capacitor-plugin-jpush

简体中文 | English

一款基于 Capacitor 3.0+ 的极光推送插件,如果有使用上的问题,欢迎提 issue,我会尽力解决,也欢迎原生开发的大神贡献你的代码。 如果这个插件帮助到了你,请不要吝啬你的 star,万分感谢!!

重要更新:0.x 版本无需手动初始化极光推送服务,在 capacitor.config.ts中配置了 appKey,应用启动时便会自动注册极光服务。 1.x 版本开始需要手动调用 startJPush 方法注册极光服务。

1.0 之后的版本开始支持 Capacitor5,0.x 版本仅支持 Capacitor4及更早版本。

关于产商通道:Android 目前暂未支持产商通道推送。

关于版本问题:不知道为什么,1.0.0 - 1.0.4 的版本在 2020 年就已经有版本记录了,所以这几个版本都跳过了,这个仓库是 2023-04-23 创建的,不知道为啥 2020 年有版本记录,也许是之前有人创建过同名包后来又注销了。

安装

npm install capacitor-plugin-jpush
npx cap sync

使用

capacitor.config.ts 配置你的极光推送 Appkey 等相关信息, 并且确保你的应用包名和极光后台设置的一致:

/// <reference types="capacitor-plugin-jpush" />

import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
  plugins: {
    JPush: {
      // your application appKey on JPush
      appKey: '',
      channel: '',
    },
  },
};

export default config;

或者在 capacitor.config.json 中配置:

{
  "plugins": {
    "JPush": {
      "appKey": "",
      "channel": ""
    }
  }
}

IOS设置

在 iOS 上,您必须启用推送通知功能。 详见 Setting Capabilities 文档如何启用推送功能(如未启用,会导致 JPush 无法注册 deviceToken)。

你本机的 Xcode 需要使用 Xcode 14 及以上版本,请注意升级!

在打开了推送通知功能之后, 添加以下代码到你应用的 AppDelegate.swift 文件:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
}

// add the following code to applicationDidBecomeActive function
NotificationCenter.default.post(name: Notification.Name(rawValue: "didBecomeActiveNotification"), object: nil)

然后找到极光推送的依赖包文件, 也就是 JPUSHService.h,点击此文件,在编辑器右边窗口找到 Target MemberShip,将 CapacitorPluginJPush 勾选中,并将它的值设置为 Public 如下图所示(如果没有找到该依赖文件,请在你的前端项目先运行命令 npx cap sync ios,如果是 Ionic 项目,则是运行 ionic cap sync ios):

https://user-images.githubusercontent.com/29945352/235104201-a39bdb6e-314d-423a-beb7-2869f3b27679.png

Android设置

Android 13 之后系统必须要有推送通知权限才可以收到推送消息,所以你可以通过 checkPermissions() 方法来检查你的应用是否开启了通知权限,如果没有,则可以通过 requestPermissions() 来启用通知权限,如果用户拒绝了,可以通过调用 openNotificationSetting() 方法来打开通知权限设置页面,

在 Android 12 及更老的设备,系统默认就是启用了推送通知权限。

在你安卓应用下找到 variables.gradle 文件,将 compileSdkVersiontargetSdkVersion 值设置为 33 ,如果已经是 33 可以忽略此步骤:

android studio

将以下代码添加到你应用 app 文件夹下的 build.gradle:

manifestPlaceholders = [
  JPUSH_PKGNAME: applicationId,
]

JPUSH_PKGNAME

代码示例

import { Capacitor } from '@capacitor/core';
import { JPush } from 'capacitor-plugin-jpush';

const JPushSetup = async () => {
  if (Capacitor.isNativePlatform()) {
    // 推送事件监听
    const receivedEvent = await JPush.addListener(
      'notificationReceived',
      data => {
        console.log(data);
      },
    );
    // 若不需要监听,移除即可
    receivedEvent.remove();

    JPush.addListener('notificationOpened', data => {
      console.log(data);
    });

    // 检测是否有通知权限
    JPush.checkPermissions().then(async ({ permission }) => {
      console.log(permission);
      if (permission !== 'granted') {
        // 申请通知权限
        JPush.requestPermissions().then(res => {
          console.log(res.permission);
          if(res.permission === "granted") {
            // 初始化极光推送
            await JPush.startJPush();
          }
        });
        return;
      }
      // 初始化极光推送
      await JPush.startJPush();
    });
  }
};

const JPushMethods = async () => {
  // 设置推送别名
  await JPush.setAlias({
    alias: 'alias',
  });

  // getRegistrationID
  const { registrationId } = await JPush.getRegistrationID();
  console.log(registrationId);

  // ......
};

API

startJPush()

startJPush() => Promise<void>

启动极光推送服务,即使没有获取到通知权限,也会进行推送服务初始化


setDebugMode(...)

setDebugMode(isDebug: boolean) => Promise<void>

开启 debug 模式 log日志

Param Type
isDebug boolean

setAlias(...)

setAlias(options: AliasOptions) => Promise<void>

设置推送别名,可作为推送消息的目标对象

Param Type
options AliasOptions

deleteAlias(...)

deleteAlias(options?: DeleteAlias | undefined) => Promise<void>

删除推送别名

Param Type
options DeleteAlias

addTags(...)

addTags(options: SetTagsOptions) => Promise<void>

设置推送标签

Param Type
options SetTagsOptions

deleteTags(...)

deleteTags(options: SetTagsOptions) => Promise<void>

删除推送标签

Param Type
options SetTagsOptions

cleanTags()

cleanTags() => Promise<void>

setBadgeNumber(...)

setBadgeNumber(options?: SetBadgeNumberOptions | undefined) => Promise<void>

设置 APP 角标数字,设为 0 即清空角标

Param Type
options SetBadgeNumberOptions

removeListeners()

removeListeners() => Promise<void>

getRegistrationID()

getRegistrationID() => Promise<{ registrationId: string; }>

获取设备的注册 ID,若服务重新注册,则返回的 ID 是不一样的

Returns: Promise<{ registrationId: string; }>


checkPermissions()

checkPermissions() => Promise<PermissionStatus>

检查通知权限状态

Returns: Promise<PermissionStatus>


requestPermissions()

requestPermissions() => Promise<PermissionStatus>

申请通知权限

Returns: Promise<PermissionStatus>


openNotificationSetting()

openNotificationSetting() => Promise<void>

打开推送通知权限设置页面(目前仅安卓支持)


addListener('notificationReceived', ...)

addListener(eventName: 'notificationReceived', listenerFunc: (notificationData: ReceiveNotificationData) => void) => Promise<PluginListenerHandle> & PluginListenerHandle

监听推送消息

Param Type
eventName 'notificationReceived'
listenerFunc (notificationData: ReceiveNotificationData) => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle


addListener('notificationOpened', ...)

addListener(eventName: 'notificationOpened', listenerFunc: (notificationData: ReceiveNotificationData) => void) => Promise<PluginListenerHandle> & PluginListenerHandle

监听消息栏通知被点击

Param Type
eventName 'notificationOpened'
listenerFunc (notificationData: ReceiveNotificationData) => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle


Interfaces

AliasOptions

Prop Type
alias string
sequence number

DeleteAlias

Prop Type
sequence number

SetTagsOptions

Prop Type
tags string[]

SetBadgeNumberOptions

Prop Type
badge number

PermissionStatus

Prop Type Description
permission PermissionState prompt: 首次申请,询问。 prompt-with-rationale: 每次都询问。 granted: 已获取权限。 denied:权限已拒绝。

PluginListenerHandle

Prop Type
remove () => Promise<void>

ReceiveNotificationData

Prop Type
title string
content string
subTitle string
rawData { [x: string]: any; aps: { alert: { body: string; subTitle: string; title: string; }; badge: number; sound: string; }; }

Type Aliases

PermissionState

'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'

Readme

Keywords

Package Sidebar

Install

npm i capacitor-plugin-jpush

Weekly Downloads

3

Version

1.0.7

License

MIT

Unpacked Size

493 kB

Total Files

53

Last publish

Collaborators

  • zhuxian