### Example: Set Push Time for Weekdays Source: https://docs.jiguang.cn/jpush/client/Android/android_api Example demonstrating how to set the push time for weekdays (Monday to Friday) from 10 AM to 11 PM. ```java Set days = new HashSet(); days.add(1); days.add(2); days.add(3); days.add(4); days.add(5); JPushInterface.setPushTime(getApplicationContext(), days, 10, 23); ``` -------------------------------- ### Install SDK using CocoaPods Source: https://docs.jiguang.cn/jpush/client/iOS/ios_guide_new Use this command to install the SDK when working with the JiguangDemo project. This project uses CocoaPods for SDK management. ```bash pod install ``` -------------------------------- ### Live Window Message Example (Flight Scenario) Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push Example payload for a live window message in a flight scenario on HMOS devices. ```APIDOC ## HMOS Live Window Message (Flight Scenario) ### Description Send a live window message for a flight status update on HMOS devices. ### Request Body ```json { "notification" : { "hmos" : { "push_type":7, "hm_payload": { "activityId": 1, "operation": 0, "event": "FLIGHT", "status": "DEPART", "activityData": { "notificationData": { "keywords": { "flightNo": "MU1471" }, "type": 5, "contentTitle": "航班{{status}}", "contentText": [ { "text": "航班号:" }, { "text": "{{flightNo}}", "foregroundColor": "#FF317AF7" } ], "clickAction": { "actionType": 0 }, "firstTextBlock": { "firstLine": "12:00", "secondLine": "上海虹桥" }, "lastTextBlock": { "firstLine": "14:20", "secondLine": "成都天府" }, "displayHorizontalLine": true, "spaceIcon": "space.png", "extend": { "type": 3, "pic": "flight.png", "clickAction": { "actionType": 1, "action": "xxxxxxx" } } }, "capsuleData": { "type": 1, "status": 1, "icon": "icon.svg", "bgColor": "#FF317AF7", "remind": "EXPAND", "title": "即将出发", "content": "请尽快前往机场" } } } } } } ``` ``` -------------------------------- ### User Statistics Response Example Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_report Example JSON response for user statistics, showing time unit, start date, duration, and aggregated user data items. ```json < HTTP/1.1 200 OK < {"time_unit":"DAY","start":"2014-06-10","duration":3,"items":[{"time":"2024-08-13","hmos": {"active": 7,"new": 5,"online": 11}},{"time":"2014-06-11","android":{"active":1}},{"time":"2014-06-12","android":{"active":1,"online":2}}]} ``` -------------------------------- ### JPush SDK Setup with Advertising Identifier Source: https://docs.jiguang.cn/jpush/client/iOS/ios_guide_new Use this setup method when you need to provide an advertising identifier for JPush SDK initialization. ```objective-c + (void)setupWithOption:(NSDictionary *)launchingOption appKey:(NSString *)appKey channel:(NSString *)channel apsForProduction:(BOOL)isProduction advertisingIdentifier:(NSString *)advertisingId; ``` -------------------------------- ### Install pako for Data Compression Source: https://docs.jiguang.cn/jpush/client/QuickApp/quick_push_guide Install the pako Node.js library using npm to enable data compression, which helps reduce traffic for the JPush SDK. ```bash npm install pako --save ``` -------------------------------- ### Stop and Resume Push Example Source: https://docs.jiguang.cn/jpush/client/Android/android_api Example demonstrating how to use stopPush and resumePush within an Android Activity. It shows button click listeners to trigger these actions. ```java public class MainActivity extends InstrumentedActivity implements OnClickListener { private Button mStopPush; private Button mResumePush; @Override public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.main); initView();} // 初始化按钮 private void initView() {mStopPush = (Button)findViewById(R.id.stopPush); mStopPush.setOnClickListener(this); mResumePush = (Button)findViewById(R.id.resumePush); mResumePush.setOnClickListener(this); } @Override public void onClick(View v) {switch (v.getId()) { // 点击停止按钮后,极光推送服务会被停止掉 case R.id.stopPush: JPushInterface.stopPush(getApplicationContext()); break; // 点击恢复按钮后,极光推送服务会恢复正常工作 case R.id.resumePush: JPushInterface.resumePush(getApplicationContext()); break; } } } ``` -------------------------------- ### JPush SDK Initialization and Privacy Handling Example Source: https://docs.jiguang.cn/jpush/client/Android/android_guide This example shows how to initialize the JPush SDK within your Application class, including handling privacy policy consent and setting debug mode. It also demonstrates conditional initialization based on user consent. ```java public class ExampleApplication extends Application { @Override public void onCreate() { super.onCreate(); JPushInterface.setDebugMode(true); // 调整点一:调用启用推送业务功能代码前增加setAuth调用 boolean isPrivacyReady; // app根据是否已弹窗获取隐私授权来赋值 if(!isPrivacyReady){ // JCore 5.0.4之前版本需要显式设置false if (JCoreInterface.getJCoreSDKVersionInt() < 504) { // 5.0.4版本号对应504 JCollectionAuth.setAuth(context, false); } // 所有版本在未授权时都不应初始化SDK return; } JPushInterface.init(); // 调整点二:App用户同意了隐私政策授权,并且开发者确定要开启推送服务后调用 // JCore 5.0.4+会自动处理授权状态,可不需要显式设置true JCollectionAuth.setAuth(context, true); } } ``` -------------------------------- ### JPush SDK Setup without Advertising Identifier Source: https://docs.jiguang.cn/jpush/client/iOS/ios_guide_new Use this setup method when you do not need to provide an advertising identifier for JPush SDK initialization. ```objective-c + (void)setupWithOption:(NSDictionary *)launchingOption appKey:(NSString *)appKey channel:(NSString *)channel apsForProduction:(BOOL)isProduction; ``` -------------------------------- ### Scheduled Push Template Request Example Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push_template This example demonstrates how to schedule a push notification using a template. It includes parameters for the template ID, audience, message content, and trigger time for a daily recurring push. ```json //完整示例 { "id": "c65b34b96512", "params": [{ "keys": { "title": "这是推送给第⼀个regid的标题", "content": "这是第⼀个regid的内容" }, "audience": { "registration_id": [ "13065ffa4ee8411496f" ] }, "options": { "test_model": true } }], "schedule_name": "定时⽂件推送示例", "trigger": { "periodical": { "start": "2023-10-19 12:00:00", "end": "2023-11-19 18:30:00", "time": "18:05:00", "time_unit": "day", "frequency": 1 } } } ``` -------------------------------- ### Full Request Example with Multiple Audiences Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push_template This example demonstrates a full request payload for sending a push notification using a template, targeting multiple distinct audiences within the same request. Note the constraints on combining audience types. ```json { "id": "c65b34b96512", // 创建模板后,极光生产的模板ID "params": [{ "keys": { // 创建模板时,开发者设置的变量参数 "title": "这是推送给第⼀个regid的标题", "content": "这是第⼀个regid的内容" }, "audience": { // 本次推送,实际想推送的人群 "registration_id": [ "13065ffa4ee8411496f" ] }, "options": { "test_model": true, // 表示是否测试模式消息,false:正式消息(默认值),true:测试消息 } }, { "keys": { // 创建模板时,开发者设置的变量参数 "title": "这是推送给第⼆个regid的标题", "content": "这是第⼆个regid的内容" }, "audience": { // 本次推送,实际想推送的人群 "registration_id": [ "170976fa8a754363cd1" ] }, "options": { "test_model": true, // 表示是否测试模式消息,false:正式消息(默认值),true:测试消息 } } ] } ``` -------------------------------- ### Geofence Trigger Details Example Source: https://docs.jiguang.cn/jpush/client/Android/android_api Example JSON structure for geofence trigger details, including operational status, geofence information, and timing data. ```JSON { "op": "add", "geofenceid": "5543826e95", "name": "gdv22021040802", "radius": 1000, "status": "inside", "repeat": true, "repeat_week_num": 10, "repeat_day_num": 10, "repeat_time": 3600, "expiration": 1627766421, "type": 2, "lon": 113.9544839625204, "lat": 22.84907665318461, "lastTime": 1617896526398, // 当前触发时间 "lastTimeWeek": "2021-15", // 自然周 "weekNum": 3, // 当周触发次数 "lastTimeDay": "2021-098", // 自然天 "dayNum": 3, // 当天触发次数 "lastGeoStatus": "in" // 当前是在圈内圈外 } ``` -------------------------------- ### Authentication Example Source: https://docs.jiguang.cn/jpush/server/push/server_overview Example of how to authenticate with the JPush API using HTTP Basic Authentication with curl. It shows how to construct the Authorization header using appKey and masterSecret. ```APIDOC ## POST /v3/push ### Description This endpoint is used for sending push notifications. Authentication is required using HTTP Basic Authentication. ### Method POST ### Endpoint https://api.jpush.cn/v3/push ### Parameters #### Request Body - **platform** (string) - Required - The platform to send the push notification to (e.g., "all", "android", "ios"). - **audience** (string) - Required - The audience for the push notification (e.g., "all", "tag", "alias"). - **notification** (object) - Required - The notification content. - **alert** (string) - Required - The alert message to display. ### Request Example ```bash curl --insecure -X POST -v https://api.jpush.cn/v3/push -H "Content-Type: application/json" -u "7d431e42dfa6a6d693ac2d04:5e987ac6d2e04d95a9d8f0d1" -d '{"platform":"all","audience":"all","notification":{"alert":"Hi,JPush!"}}' ``` ### Response #### Success Response (200) - **message_id** (string) - The ID of the message. #### Response Example ```json { "message_id": "1234567890" } ``` ### Rate Limiting Information in Headers - **X-Rate-Limit-Limit** (integer) - The maximum number of requests allowed in the current time window. - **X-Rate-Limit-Remaining** (integer) - The number of requests remaining in the current time window. - **X-Rate-Limit-Reset** (integer) - The number of seconds until the time window resets. ``` -------------------------------- ### Update Schedule Task (Full Example) Source: https://docs.jiguang.cn/jpush/server/push/rest_api_push_schedule A complete example of a schedule task payload for updating. This includes details for periodical triggers and push configurations. ```json { "name": "定时推送示例", "enabled": true, "trigger": { "periodical": { "start":"2014-09-17 12:00:00", "end": "2014-10-18 12:00:00", "time": "12:00:00", "time_unit": "WEEK", "frequency": 2, "point": ["WED","FRI"] } }, "push": { "platform":"ios", "options":{"apns_production":false}, "audience":"all", "notification" : {"alert":"定时任务更新"} } } ``` -------------------------------- ### Batch Single Push Request Body Example Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push_single A comprehensive example of the request body for the Batch Single Push API, demonstrating the structure for multiple push targets with various notification and message options. ```json { "pushlist":{ "cid1":{ "platform": "all", "target": "aliasvalue1", // 此处填写的是 regid 值或者 alias 值 "notification": {... // 省略参数同 push api 部分}, "message": {... // 省略参数同 push api 部分}, "sms_message":{... // 省略参数同 push api 部分}, "options": {... // 省略参数同 push api 部分}, "callback":{... // 省略参数同 push api 部分} }, "cid2":{ "platform": "all", "target": "aliasvalue2", // 此处填写的是 regid 值或者 alias 值 "message": {...}, "notification_3rd":{...}, "options": { "notification_3rd_ver": "v2" // 自定义消息转厂商通知功能需特别注意此字段,具体参考 push api 文档说明;省略其它参数同 push api 部分 } "callback":{...} }, ... } } ``` -------------------------------- ### Broadcast Push Example Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push_template This example shows how to send a broadcast push notification to all users. The 'audience' field must be set to 'all', and the 'params' array should contain only one JSON object. ```json { "id": "c65b34b96512", "params": [ { "keys": { "title": "这是推送给第⼀个regid的标题", "content": "这是第⼀个regid的内容" }, "audience": "all", "options": { "test_model": true, // 表示是否测试模式消息,false:正式消息(默认值),true:测试消息 }, "trace_id": "8de06fh-8djfgg" } ] } ``` -------------------------------- ### Tag Push Example Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push_template This example demonstrates pushing notifications to users associated with specific tags. The 'audience' field should be an object with a 'tag' array. The 'params' array should contain only one JSON object for tag-based pushes. ```json { "id": "c65b34b96512", "params": [ { "keys": { "title": "这是推送给tag的标题", "content": "这是第tag的内容" }, "audience": {"tag":["tag1"]}, "options": { "test_model": true, // 表示是否测试模式消息,false:正式消息(默认值),true:测试消息 }, "trace_id": "8de06fh-8djfgg" } ] } ``` -------------------------------- ### Registration ID Push Example Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push_template This example demonstrates pushing notifications to specific registration IDs. The 'audience' field should be an object with a 'registration_id' array. The total number of registration IDs across all objects in the 'params' array cannot exceed 1000. ```json { "id": "c65b34b96512", "params": [ { "keys": { "title": "这是推送给第⼀个regid的标题", "content": "这是第⼀个regid的内容" }, "audience": {"registration_id":["13065ffa4ee8411496f"]}, "options": { "test_model": true, // 表示是否测试模式消息,false:正式消息(默认值),true:测试消息 }, "trace_id": "98ode06fh-8dgg" }, { "keys": { "title": "这是推送给第二个regid的标题", "content": "这是第二个regid的内容" }, "audience": {"registration_id":["8914afdsa31"]}, "options": { "test_model": true, // 表示是否测试模式消息,false:正式消息(默认值),true:测试消息 }, "trace_id": "8de06fh-8djfgg" }, ] } ``` -------------------------------- ### Initialize Quick Push SDK Source: https://docs.jiguang.cn/jpush/client/QuickApp/quick_push_api Initialize the SDK with your app key and channel. This should be called in the onCreate method of your app. Subsequent calls to other SDK interfaces can be made using `this.$app.JPushInterface`. ```javascript this.JPushInterface=JPushInterface.init(this,"官网中创建应用后分配的appkey","自定义channel"); ``` -------------------------------- ### onNotifyMessageUnShow Source: https://docs.jiguang.cn/jpush/client/Android/android_api Callback for when a notification is not displayed. This method is invoked when a notification is not shown, for example, when the foreground display is disabled. It's available starting from JPush Android SDK v3.5.8. ```APIDOC ## onNotifyMessageUnShow ### Description Callback for when a notification is not displayed. This method is invoked when a notification is not shown, for example, when the foreground display is disabled. It's available starting from JPush Android SDK v3.5.8. ### Method Definition public void onNotifyMessageUnShow(Context context, NotificationMessage message) ### Parameters #### Path Parameters * **context** (Context) - Application Context. * **message** (NotificationMessage) - The notification content that was not displayed. ``` -------------------------------- ### Start a Live Activity Source: https://docs.jiguang.cn/jpush/client/iOS/ios_guide_new Initiate a Live Activity by creating an instance of your attributes and content state, then calling Activity.request. This will display the activity on the lock screen. Handle potential errors during the request. ```swift // 初始状态 let initialContentState = JGLAAttributes.ContentState(eventStr: "begin", eventTime: 1) let activityAttributes = JGLAAttributes(name: "LiveActivity", number: "1") do { // 创建Activity let jgActivity = try Activity.request(attributes: activityAttributes, contentState: initialContentState, pushType:PushType.token) print("Requested a Live Activity \(String(describing: jgActivity.id)).") } catch (let error) { print("Error requesting Live Activity \(error.localizedDescription).") } ``` -------------------------------- ### Example: Set and Get Background Long Connection Source: https://docs.jiguang.cn/jpush/client/Android/android_api Demonstrates how to disable the long connection in the background and then retrieve the current setting. Ensure JCore SDK version is 5.4.0 or higher for this to be effective. ```java JPushInterface.setKeepLongConnInBackground(context, false); boolean keep = JPushInterface.getKeepLongConnInBackground(context); ``` -------------------------------- ### JPushMessage.getErrorCode() Source: https://docs.jiguang.cn/jpush/client/Android/android_api Gets the return code for the operation. A return code of 0 indicates success. Refer to the error code definition for other codes. This method is available starting from JPush Android SDK v3.0.7. ```APIDOC ## JPushMessage.getErrorCode() ### Description Gets the return code for the operation. 0 indicates success; refer to error code definitions for other codes. ### Method public int getErrorCode(); ### Supported Versions JPush Android SDK v3.0.7 and later. ``` -------------------------------- ### Card Refresh Message Example Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push Example payload for refreshing a card on HMOS devices. ```APIDOC ## HMOS Card Refresh Message ### Description Send a message to refresh a card component on HMOS devices. ### Request Body ```json { "notification" : { "hmos" : { "push_type":1, "hm_payload": { "formData": { "123": 96, "class": "123" }, "version": 922337203, "images": [ { "keyName": "hello", "url": "https://xxx.png", "require": 1 } ], "formId": 0, "moduleName": "testName", "formName": "testFormName", "abilityName": "testAbilityName" } } } } ``` ``` -------------------------------- ### 添加华为插件 Source: https://docs.jiguang.cn/jpush/client/Android/android_3rd_guide 在应用 module 的 build.gradle 文件底部添加此代码行,以启用 gradle 插件。 ```gradle apply plugin: 'com.huawei.agconnect' ``` -------------------------------- ### Server Payload Example Source: https://docs.jiguang.cn/jpush/client/iOS/ios_new_fetures Example of a server-side payload for a push notification, including the 'category' field to trigger client-side actions. ```JSON {"aps":{"alert":"example", "sound":"default", "badge": 1, "category":"identifier"}} ``` -------------------------------- ### JPush Example: Setting Notification Silence Time Source: https://docs.jiguang.cn/jpush/client/Android/android_api Example of how to set the notification silence time from 10:30 PM to 8:30 AM using JPushInterface.setSilenceTime. ```java JPushInterface.setSilenceTime(getApplicationContext(), 22, 30, 8, 30); ``` -------------------------------- ### HarmonyOS Live Window Message Example (Flight Scenario) Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push Send a live window message for HarmonyOS, specifically for flight scenarios. This includes activity data, capsule data, and event details. ```json { "notification" : { "hmos" : { "push_type":7, "hm_payload": { "activityId": 1, "operation": 0, "event": "FLIGHT", "status": "DEPART", "activityData": { "notificationData": { "keywords": { "flightNo": "MU1471" }, "type": 5, "contentTitle": "航班{{status}}", "contentText": [ { "text": "航班号:" }, { "text": "{{flightNo}}", "foregroundColor": "#FF317AF7" } ], "clickAction": { "actionType": 0 }, "firstTextBlock": { "firstLine": "12:00", "secondLine": "上海虹桥" }, "lastTextBlock": { "firstLine": "14:20", "secondLine": "成都天府" }, "displayHorizontalLine": true, "spaceIcon": "space.png", "extend": { "type": 3, "pic": "flight.png", "clickAction": { "actionType": 1, "action": "xxxxxxx" } } }, "capsuleData": { "type": 1, "status": 1, "icon": "icon.svg", "bgColor": "#FF317AF7", "remind": "EXPAND", "title": "即将出发", "content": "请尽快前往机场" } } } } } } ``` -------------------------------- ### 配置 mavenCentral 支持和 agconnect 依赖 Source: https://docs.jiguang.cn/jpush/client/Android/android_3rd_guide 在 Project 根目录的主 gradle 文件中配置 mavenCentral 支持和 agconnect 依赖。 ```gradle buildscript { repositories { google() mavenCentral() maven {url 'https://developer.huawei.com/repo/'} } } buildscript { dependencies { classpath 'com.huawei.agconnect:agcp:1.9.1.301' } } allprojects { repositories { google() mavenCentral() maven {url 'https://developer.huawei.com/repo/'} } } ``` -------------------------------- ### Upload Certificate (with Dev and Prod) Source: https://docs.jiguang.cn/jpush/server/push/rest_api_admin_api_v1 Upload both development and production certificates for a given appKey. Requires providing passwords and file paths for both certificate types. ```shell curl https://admin.jpush.cn/v1/app/ffbb0932c267d938941e470b/certificate -F "devCertificatePassword=your dev certificate passowrd" -F "proCertificatePassword=your pro certificate passowrd" -F "devCertificateFile=@your dev certificate file" -F "proCertificateFile=@your pro certificate file" -u '{devKey}:{devSecret}' ``` -------------------------------- ### Install lodash.clonedeep for Object Copying Source: https://docs.jiguang.cn/jpush/client/QuickApp/quick_push_guide Install the lodash.clonedeep Node.js library using npm to facilitate object copying, which is a dependency for the JPush SDK. ```bash npm install lodash.clonedeep --save ``` -------------------------------- ### Initialize JPush SDK in Quick App Source: https://docs.jiguang.cn/jpush/client/QuickApp/quick_push_guide Initialize the JPush SDK in your Quick App's main entry file (app.ux). This involves setting the debug mode and calling the init method with your AppKey and channel. It's recommended to make JPushInterface globally accessible. ```javascript import { JPushInterface } from './libs/jpush-quickapp-1.0.0' export default { showMenu: util.showMenu, createShortcut: util.createShortcut, onCreate(){ JPushInterface.setDebugMode(true); this.JPushInterface = JPushInterface.init(this, "your appkey", "test-channel") } } ``` -------------------------------- ### Message Statistics Response Example Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_report Example JSON response for message statistics, detailing received, target, and click counts for Android and iOS platforms. ```json < HTTP/1.1 200 OK < Content-Type: application/json < [ { "android": {"received":1,"target":4,"online_push":1,"click":null,"msg_click":null}, "ios": {"apns_sent":2,"apns_target":2,"apns_received":1,"click":null,"target":10,"received":8,"msg_click": 50}, "msg_id":"269978303" } ] ``` -------------------------------- ### Example: Trigger Notification State Check Source: https://docs.jiguang.cn/jpush/client/Android/android_api This code example demonstrates how to actively check the current application's notification switch status and report any changes. ```java // 触发通知状态检查,如果有变化上报 JPushInterface.triggerNotificationStateCheck(context); ``` -------------------------------- ### 配置小米通道参数 Source: https://docs.jiguang.cn/jpush/client/Android/android_3rd_guide 在应用 module 的 gradle 文件中 defaultConfig 节点添加小米的 AppKey 和 AppID。自 xiaomi-v5.5.3 版本起,参数不需要添加前缀 'MI-'。 ```gradle manifestPlaceholders = [ // 设置manifest.xml中的变量 XIAOMI_APPKEY : "您的应用对应的小米的APPKEY",// 小米平台注册的appkey,xiaomi-v5.5.3版本开始,不需要添加前缀 “MI-” XIAOMI_APPID : "您的应用对应的小米的APPID", // 小米平台注册的appid,xiaomi-v5.5.3版本开始,不需要添加前缀 “MI-” ] ``` -------------------------------- ### Third-Party Channel Configuration Example Source: https://docs.jiguang.cn/jpush/practice/push_strategy This JSON structure shows how to configure push delivery strategies for various third-party channels within the `third_party_channel` field. Each key represents a vendor, and its value contains specific distribution strategy parameters. ```json "third_party_channel":{ "xiaomi":{ "distribution":"jpush", "distribution_fcm":"fcm", "distribution_customize":"first_ospush", }, "huawei":{ "distribution":"secondary_push", "distribution_fcm":"jpush", "distribution_customize":"first_ospush", }, "honor":{ "distribution":"secondary_push", "distribution_fcm":"jpush", "distribution_customize":"first_ospush" }, "meizu":{ "distribution":"jpush", "distribution_fcm":"pns" }, "fcm":{ // 这个参数不支持 distribution_fcm 字段 "distribution":"jpush" }, "oppo":{ "distribution":"ospush", "distribution_fcm":"secondary_fcm_push", }, "vivo":{ "distribution":"jpush", "distribution_fcm":"secondary_pns_push", }, "hmos":{ // 这个参数只支持distribution字段,下发策略对鸿蒙平台通知(notification)和鸿蒙平台自定义消息(message)均生效 "distribution":"jpush" } } ``` -------------------------------- ### Check Push Status Callback Example Source: https://docs.jiguang.cn/jpush/client/Android/android_api Example of how to handle the callback for getPushStatus in JPushMessageReceiver. It logs whether the push service is stopped, not stopped, or if an error occurred. ```java // 调用获取推送状态 JPushInterface.getPushStatus(context); // 在 JPushMessageReceiver 中接收回调 @Override public void onCommandResult(Context context, CmdMessage cmdMessage) { if (cmdMessage != null && cmdMessage.cmd == 2003) { if (cmdMessage.errorCode == 0) { Log.d(TAG, "推送服务未停止"); } else if (cmdMessage.errorCode == 1) { Log.d(TAG, "推送服务已停止"); } else { Log.e(TAG, "获取推送状态失败,错误码: " + cmdMessage.errorCode + ", 错误信息: " + cmdMessage.msg); } } } ``` -------------------------------- ### 配置 mavenCentral 支持 Source: https://docs.jiguang.cn/jpush/client/Android/android_3rd_guide 在 Project 根目录的主 gradle 文件中配置 mavenCentral 支持。新建 project 默认配置已支持。 ```gradle buildscript { repositories { mavenCentral() } } allprojects { repositories { mavenCentral() } } ``` -------------------------------- ### 初始化极光推送 SDK Source: https://docs.jiguang.cn/jpush/client/jghgzy_a_i_h 在用户同意隐私政策后,调用此方法初始化极光推送 SDK。确保在调用前已处理好用户授权和隐私政策同意事宜。 ```java JPushInterface.init(); ``` -------------------------------- ### Start Real-time Activity Push Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push Use this payload to remotely start a new real-time activity. The audience can be specified using broadcast, tag, alias, or registration_id. ```json // 远程创建实时活动 { "cid": "7094b4c628a0b98974ec1949-711261d4-5f17-2f6d-a855-9b26e5e5a890", "platform": ["ios"], "audience": { "tag": [ "深圳", "广州"] // 创建实时活动,audience 支持:广播、tag、alias、registration_id }, "live_activity": { "ios": { "event": "start", "content-state":{ "currentHealthLevel": 100, "eventDescription": "Adventure has begun!" }, "attributes-type": "AdventureAttributes", "attributes":{ "currentHealthLevel": 100, "eventDescription": "Adventure has begun!" }, "alert":{ "title":"David is on an adventure!", "body":"David found a sword!", "sound":"chime.aiff" } } }, "options": { "apns_production": false } } ``` -------------------------------- ### 配置小米通道依赖 Source: https://docs.jiguang.cn/jpush/client/Android/android_3rd_guide 在应用 module 的 gradle 文件中 dependencies 节点添加小米通道的 SDK 依赖。请确保厂商版本与 JPush SDK 版本保持一致。 ```gradle implementation 'cn.jiguang.sdk.plugin:xiaomi:5.x.x' //说明:JPush SDK v5.2.4 由于特殊原因,引用方式如下 //implementation 'cn.jiguang.sdk.plugin:xiaomi:5.2.4.a' ``` -------------------------------- ### 配置华为推送依赖 Source: https://docs.jiguang.cn/jpush/client/Android/android_3rd_guide 在应用 module 的 gradle 中 dependencies 节点添加此代码,可根据华为发布的版本更新选择最新版本。 ```gradle implementation 'cn.jiguang.sdk.plugin:huawei:5.x.x' //5.9.0版本开始会自动拉取华为依赖包 ``` -------------------------------- ### Server-Side iOS Push Payload Example Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push Example of a JSON payload sent from the server to JPush for iOS notifications. Includes alert, sound, badge, and custom extras. ```json { "notification" : { "ios" : { "alert" : "hello, JPush!", "sound" : "sound.caf", "badge" : 1, "extras" : { "news_id" : 134, "my_key" : "a value" } } } } ``` -------------------------------- ### 配置签名证书 Source: https://docs.jiguang.cn/jpush/client/Android/android_3rd_guide 在 build.gradle 中配置在华为后台添加的指纹证书对应的签名。HMS 服务必须要求 app 签名才能注册成功。 ```gradle signingConfigs { release { storeFile file("release.keystore")//签名文件的path storePassword "123456" keyAlias "android.keystore" keyPassword "123456" } } buildTypes { release { minifyEnabled true proguardFiles 'proguard-rules.pro' signingConfig signingConfigs.release } debug{ minifyEnabled false signingConfig signingConfigs.release } } ``` -------------------------------- ### Install crypto-js for Data Encryption Source: https://docs.jiguang.cn/jpush/client/QuickApp/quick_push_guide Install the crypto-js Node.js library using npm to add data encryption, enhancing the security of data transmitted by the JPush SDK. ```bash npm install crypto-js --save ``` -------------------------------- ### Create Push Plan Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push_plan Creates a new push plan with a specified name and description. ```APIDOC ## POST /v3/push_plan/create ### Description Creates a new push plan with a specified name and description. ### Method POST ### Endpoint /v3/push_plan/create ### Parameters #### Request Body - **name** (string) - Required - The name of the push plan. - **description** (string) - Optional - A description for the push plan. ### Response #### Success Response (200) - **code** (int) - 0 for success, otherwise an error code. - **message** (string) - Success message or error description. ``` -------------------------------- ### Client-Side Received APNs Payload Example Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push Example of the payload received by an iOS client from APNs, after being processed by JPush. Shows how JPush fields are mapped and custom extras are included. ```json { "_j_msgid" = 813843507; aps = { alert = "hello,JPush!"; badge = 1; sound = "sound.caf"; }; "my_key" = "a value"; "news_id" = 134; } ``` -------------------------------- ### Request Headers for Batch Single Push Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push_single Example request headers for initiating a batch single push using either RegID or Alias methods. ```http POST /v3/push/batch/regid/single HTTP/1.1 Authorization: Basic N2Q0MzFlNDJkZmE2YTZkNjkzYWMyZDA0OjVlOTg3YWM2ZDJlMDRkOTVhOWQ4ZjBkMQ== ``` ```http POST /v3/push/batch/alias/single HTTP/1.1 Authorization: Basic N2Q0MzFlNDJkZmE2YTZkNjkzYWMyZDA0OjVlOTg3YWM2ZDJlMDRkOTVhOWQ4ZjBkMQ== ``` -------------------------------- ### Immediate Push Template Response Example Source: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push_template This snippet shows a successful response for an immediate push notification using a template, including details for multiple recipients. It also illustrates potential error responses for specific registration IDs. ```json HTTP/2 200 { "code": 0, "message": "success", "data": { "push_list": [{"code": 0, "message_id": "2252000892313098" }, { "code": 0, "message_id": "1098252000313050" }, { "code": 1011, "message_id": "22520008923130", "message": "cannot find user by this audience or has been inactive for morethan 255 days " }, { "code": 1003, "message_id": "2252000003001231", "message": "The registration_id aaaa is invalid!" } ] } } ``` ```json HTTP/2 400 { "code": 10004, "message": "Missing parameters" } ``` -------------------------------- ### Example of Page Enter/Leave Calls Source: https://docs.jiguang.cn/jpush/client/iOS/ios_api This Objective-C example demonstrates how to integrate page enter and leave tracking into a ViewController's lifecycle methods. It shows calling pageEnterTo: in viewDidAppear: and pageLeave: in viewDidDisappear:. ```objective-c // 例如可以在 ViewController 的 viewDidAppear: 和 viewDidDisappear: 方法中配套调用 - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [JPUSHService pageEnterTo:@"AViewController"]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [JPUSHService pageLeave:@"AViewController"]; } ```