Cordova plugin - JPush
本地通知
本地通知:本地通知不依赖网络,无网络条件下依旧可以触发;可以定时发出通知。
Cordova 本地通知,可以用插件 cordova-plugin-local-notification
实现。
1 | # Plugin Registry |
cordova-plugin-local-notification
插件wiki。
远程实时通知
远程通知:依赖网络,可以根据需要实时推送通知。
当在某种情况下,你需要向 APP 用户推送消息,而且该用户又没有打开 APP 的时候(后台运行)。你怎样才能够发出消息通知用户呢?
极光推送提供了一个 Cordova 通知插件 jpush-phonegap-plugin
,即使 APP 在后台运行状态,也可以实现实时推送通知的功能。
Cordova 插件 jpush-phonegap-plugin
安装 (Android)
先在极光推送官网注册一个账号,然后,在
极光开发者服务
创建一个应用 (因为,在安装插件的时候会用到AppKey
)。应用名称:填 Cordova 配置文件
config.xml
中的<name>
即可。应用包名(Android):填 Cordova 配置文件
config.xml
中的<widget>
中的id
即可。Cordova 应用中添加插件:
cordova-plugin-device
和jpush-phonegap-plugin
。要用到cordova-plugin-device
插件。
1 | # cordova-plugin-device |
注意:AppKey
就是在极光开发者服务中创建应用之后,在应用信息中的 AppKey。
jpush-phonegap-plugin 使用
jpush-phonegap-plugin
在需要在 cordova deviceready
的时候初始化才能够使用。初始化之后,正常情况下,会根据设备产生一个 registration ID
(相对不同设备具有唯一性)。我们可以将这个 registration ID
保存到服务器端,通过这个 registration ID
对特定用户发送通知。也可以,通过设置 tag
等来实现。更多使用可以查看官方文档:JPush 官方文档
插件的一些常用 Cordova 监听事件,如:
jpush.receiveNotification
:Cordova APP 在接收到 jpush 远程通知的时候触发事件。jpush.openNotification
:点击通知栏的 jpush 远程通知的时候触发事件。
1 | jQuery(function($) { |
正常情况下,初始化完之后,我们就可以在极光推送后台创建的项目中手动发送通知了(发送通知的时候,通知内容一定要填,不然设备不会显示通知)。但是,这不是我们想要的。通常,我们需要在服务器后台根据一定的条件自动触发推送条件,并且推送到特定的用户设备上。插件官方提供了服务端 SDK,我们可以通过安装相应的 SDK,通过调用相关的接口来实现服务器端发送通知的功能。如,Python:
安装 Python SDK
1
pip/pip3 install jpush
通过安装的 jpush 模块编写发送通知功能,
jpush_client.py
:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30import jpush
class JPushClient(object):
"""jPush client for Instrument Connect
Requirements: the jpush module must be installed (pip/pip3 install jpush).
More info: https://docs.jiguang.cn/jpush/server/3rd/python_sdk/
"""
def __init__(self, app_key, master_secret, *args, **kwargs):
# AppKey and Master Secret from jiguang project
self.app_key = app_key
self.master_secret = master_secret
def push_notification(self, registration_id, content, *args, **kwargs):
"""Push notification to user via jPush client:
:param registration_id: a list of registration id which binding the user phone
:param content: the notification content that will be send to user
:return:
"""
# Init a jPush object
_jpush = jpush.JPush(self.app_key, self.master_secret)
# Create a push notification
push = _jpush.create_push()
# Setting push audience
push.audience = jpush.audience({
'registration_id': registration_id
})
# Setting push platform
push.platform = jpush.all_
# Setting notification content
push.notification = jpush.notification(alert=content)
push.send()调用编写好的接口,发送通知:
1
2
3
4
5
6
7
8from xxx.jpush_client import JPushClient
# AppKey and Master Secret from your jiguang project
app_key = 'your project AppKey'
master_secret = 'your project Master Secret'
# A list of registration id that you want to send the notification to
registration_id = ['xxx', 'xxx']
content = 'hello'
JPushClient(app_key, master_secret).push_notification(registration_id, content)
更多 Python SDK 的使用可以查看 ipush-api-python-client