Android SDK API
Unified push service standard interface
Unified push service (Unified Push Service, abbreviation UPS) technical standards, aiming to establish a unified standard for domestic message push services, provide end users with a better mobile phone experience, and better solve the message push needs of application developers.
from JPush 3.5.8 Version starts, new cn.jpush.android.ups.JPushUPSManager class that provides conformance to UPS Standard interface.
Registration interface
Note 1: This interface is compatible with JPushInterface.init It is not recommended to mix the interfaces. You can use this interface directly instead. JPushInterface.init interface.
Note 2:manifest configured in appkey Pass in the interface appkey It is recommended to keep it consistent, if not, use manifest The interface configured in will prevail.
Note 3: If manifest middle appkey If the configuration is empty, the interface passed in appkey shall prevail.
Interface definition
public static void registerToken (Context context, String appID,String appKey, String appSecret, UPSRegisterCallBack callback);
Parameter description
- context: application context
- appId: existJiguangGenerated when registering the application on the official website APPKEY
- appKey: fill null That’s it
- appSecret: Just fill in the blanks
- callback: The result callback of this interface. If the status code is 0, it means the call is successful. Other values are failure.
Instructions for use
- If the developer actively calls registerToken method or other means context Parameter methods will be completedSDKRegister and activateJPushpush service
Special reminder: Consider APP For online compliance, developers must be APP The user agrees to the privacy policy and the developer identifies asAppAfter the user starts to provide the push service, the registration interface is called and used.JiguangServe.
About APP Privacy policy suggestions and instructions, please refer to JPushSDKCompliance Guidelines。
Anti-registration interface
Note: After calling this interface, all Push SDK Features provided. Need to pass registerToken You can restore the interface or reinstall the application.
Interface definition
public static void unRegisterToken (Context context, UPSUnRegisterCallBack callback);
Parameter description
- context: application context
- callback: Deregistration result. A status code of 0 indicates that the call was successful, and other values indicate failure.
Stop push service
called this API back,JPush The push service is completely stopped. The specific performance is:
- Can't receive push message
- JPushall other API The calls are invalid and need to be called cn.jpush.android.ups.JPushUPSManager.turnOnPush recover.
Interface definition
public static void turnOffPush (Context context, UPSTurnCallBack callback);
Parameter description
- context: application context
- callback: Close the service result. A status code of 0 indicates that the call was successful, and other values indicate failure.
Restore push service
called this API back,JPushFully restored to normal operation.
Interface definition
public static void turnOnPush (Context context, UPSTurnCallBack callback);
Parameter description
- context: application context
- callback: Result of service restoration. A status code of 0 indicates that the call was successful, and other values indicate failure.
Set debug mode API
Function description
Note: This interface needs to be in init Call before the interface to avoid the situation where some logs are not printed. In the case of multi-process, it is recommended to use customized Application middle onCreate call in.
Interface definition
public static void setDebugMode(boolean debug);
Parameter description
- debug for true will print debug level logs,false will only print warning Logs above level
Enable push service function API
Function description
JPushservice, calling this API After that, turn onJPush Push service will start collecting and reportingSDKUser personal information necessary for business functions. It is recommended to customize Application in onCreate call in. Should API Support dynamic settingsJiguang AppKey with various manufacturers AppId。 Note: If you use this interface configuration AppKey To enable the push service, then build.gradle in file JPUSH_APPKEY Then no further configuration is required, that is JPUSH_APPKEY: ""。
Interface definition
public static void init(Context context, JPushConfig config);
Parameter description
context applied ApplicationContext
config Configuration object, specific reference JPushConfig Class description.
Interface usage instructions
- If the developer actively calls init method or other means context Parameter methods will be enabledJPushPush service.
Special reminder: Consider APP For online compliance, developers must be APP The user agrees to the privacy policy and the developer identifies asAppAfter the user starts to provide the push service, the registration interface is called and used.JiguangServe.
About APP Privacy policy suggestions and instructions, please refer to JPushSDKCompliance Guidelines。
code example
boolean isPrivacyReady; // app根据是否已弹窗获取隐私授权来赋值
if(!isPrivacyReady){
//用户同意隐私政策前,不要调用任何极光API接口
}else{
//App用户同意了隐私政策授权,并且开发者确定要开启推送业务功能后调用
JPushInterface.init()
}
Stop and resume push service API
Supported versions
Versions supported starting from:JPush Android SDK v1.3.3
Function description
JPush SDK The push service provided is enabled by default.
Developer App The push service can be stopped by calling API come to stopJPushServe. When needed againJPushWhen serving, you must call the restore push service API。
Note: The effect of this interface depends on the integrated SDK It varies from version to version.
- SDK ≥ v5.0.0 version, the status of stopping the push service will be saved to the server;
Messages pushed during the period when the push service is stopped will be directly discarded. Even if you subsequently reply to the push service, you will no longer receive push messages during the period when the service is stopped. - SDK < v5.0.0 版本,停止推送服务的状态不会保存到服务器上;
The functional behavior is similar to the effect of a network interruption, that is: messages pushed while the push service is stopped, and after the push service is restored, if the pushed messages are still within the retained time range, the client will receive offline messages.
Stop push service
called this API back,JPush The push service is completely stopped. The specific performance is:
- JPushall other API All calls are invalid and cannot be passed. JPushInterface.init Restore, need to call resumePush recover.
Interface definition
public static void stopPush(Context context);
Parameter description
- context applied ApplicationContext
Restore push service
Restore push service.
called this API back,JPushFully restored to normal operation.
Interface definition
public static void resumePush(Context context);
Parameter description
context applied ApplicationContext
Check if push is stopped (new)
Supported versions
Versions supported starting from:JPush Android SDK v6.0.0
Function description
Asynchronously obtains the status of the push service (whether it is stopped). Result passed onCommandResult The callback method returns.
Interface definition
public static void getPushStatus(Context context);
Parameter description
- context applied ApplicationContext
Callback description
Result passed JPushMessageReceiver of onCommandResult Method callback, specific reference Interaction event callback method.
Callback parameter description:
- cmd: 2003
- errorCode: 0 means not stopped, 1 means stopped, otherscode Indicates other exceptions
- msg: "not stop" means not stopped,"stopped" means stopped
code example
// 调用获取推送状态
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);
}
}
}
Check if push is stopped (abandoned)
- JPush Android SDK v1.5.2 Supported by the above versions.
- There are loopholes in the implementation and use of this method, so it is JPush Android SDK v6.0.0 The version is obsolete, please use
getPushStatusmethod substitution.
interface definition (from v6.0.0 Begin to be abandoned)
@Deprecated
public static boolean isPushStopped(Context context);
Parameter description
- context applied ApplicationContext
code example
The following code comes from JPush Android Example。
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();}
// Initialize button
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()) {
// After clicking the stop button,JPushThe service will be stopped
case R.id.stopPush:
JPushInterface.stopPush(getApplicationContext());
break;
// After clicking the restore button,JPushThe service will resume normal operation
case R.id.resumePush:
JPushInterface.resumePush(getApplicationContext());
break;
}
}
}
Apply for the necessary permission interface ( Android 6.0 and above)
Supported versions
Versions supported starting from:JPush Android SDK v4.9.0
Function description
exist Android 6.0 On systems and above, you need to requestJPush SDK Required permissions. The details are as follows:
"android.permission.POST_NOTIFICATIONS"
Implementation method
Interface definition
public static void requestRequiredPermission(Activity activity);
Parameter description
- activity currently applied Activity context.
Apply for optional permission interface ( Android 6.0 and above)
Supported versions
Versions supported starting from:JPush Android SDK v2.1.0
Function description
exist Android 6.0 and above systems, you need to request some used permissions.JPush SDK Some of the ones used need to request the following permissions, because these permissions are needed to make statistics more accurate and have richer functions. It is recommended that developers call them.
"android.permission.READ_PHONE_STATE"
"android.permission.WRITE_EXTERNAL_STORAGE"
"android.permission.READ_EXTERNAL_STORAGE"
"android.permission.ACCESS_FINE_LOCATION"
Implementation method
Interface definition
public static void requestPermission(Context context);
Parameter description
- context currently applied Activity context
Label operation callback
tag The operation of adding, deleting, checking and modifying will call back the result in this method.
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
Interface definition
public void onTagOperatorResult(Context context, JPushMessage jPushMessage);
Parameter definition
- jPushMessage
- tag The message result body returned by related operations, please refer to JPushMessage Class description.
Query tag binding status callback
Method - onCheckTagOperatorResult
Query a tag The operation with the current user's binding status will call back the result in this method.
Interface definition
public void onCheckTagOperatorResult(Context context, JPushMessage jPushMessage);
Parameter definition
- jPushMessage
- check tag The message result body returned by the operation bound to the current user, please refer to JPushMessage Class description.
Alias operation callback
alias Related operations will call back the results in this method.
method definition
public void onAliasOperatorResult(Context context, JPushMessage jPushMessage);
Parameter definition
- jPushMessage
- alias The message result body returned by related operations, please refer to JPushMessage Class description.
Set mobile phone number callback
Setting the mobile phone number will call back the result in this method.
Supported versions
Versions supported starting from:JPush Android SDK v3.1.1
method definition
public void onMobileNumberOperatorResult(Context context, JPushMessage jPushMessage)
Parameter definition
- context
- applied Application Context。
- jPushMessage
- Set the message result body returned by the mobile phone number, please refer to JPushMessage Class description.
Custom message callback
It is also an in-app reminder callback.
Supported versions
Versions supported starting from:JPush Android SDK v3.3.0
illustrate:
If needed in older version Receiver take over cn.jpush.android.intent.MESSAGE_RECEIVED broadcast
You can not override this method, or override this method and call super.onMessage
If you override this method, there is no call super, the broadcast will not be sent to the old version Receiver
method definition
public void onMessage(Context context, CustomMessage customMessage)
Parameter definition
- context
- applied Application Context。
- CustomMessage
- Receive custom message content
Manufacturer VOIP Transparent callback
Supported versions
Versions supported starting from:JPush Android SDK v6.1.0
Support vendors
Current onVoipMessage Acceptable VOIP The transparent manufacturer channels include: Xiaomi, Honor, OPPO、VIVO. Each manufacturer needs to completeJiguangside corresponding channel with VOIP The callback can only take effect after the capability is integrated.
Function description
when passedJiguangManufacturer issued VOIP When the class transparent message reaches the client,SDK This method will be called back. Client via VoipDataMessage Get fields that can be used directly locally.
method definition
public void onVoipMessage(Context context, VoipDataMessage voipDataMessage)
Parameter definition
- context
- applied Application Context。
- VoipDataMessage
- Manufacturer VOIP Transparent message body (
cn.jpush.android.api.VoipDataMessage)。 - getMessageId(): message ID, corresponding to payload in msg_id。
- getExtraData(): Extended data, corresponding to payload in extraData。
- getPlatform(): Vendor channel type (
byte), used to distinguish sources of information.
- Manufacturer VOIP Transparent message body (
Description: Not configured JPushMessageReceiver During an in-process callback,SDK Possibly via broadcast cn.jpush.android.intent.VOIP_MESSAGE_RECEIVED(JPushInterface.ACTION_VOIP_MESSAGE_RECEIVED) delivery,Extras and JPushInterface.EXTRA_MSG_ID、EXTRA_EXTRA、EXTRA_TYPE_PLATFORM Consistent constants; **Recommend unified inheritance JPushMessageReceiver deal with. **
code example
@Override
public void onVoipMessage(Context context, VoipDataMessage voipDataMessage) {
if (voipDataMessage == null) {
return;
}
String msgId = voipDataMessage.getMessageId();
String extra = voipDataMessage.getExtraData();
byte platform = voipDataMessage.getPlatform();
}
Notification callback received
Supported versions
Versions supported starting from:JPush Android SDK v3.3.0
illustrate:
If needed in older version Receiver take over cn.jpush.android.intent.NOTIFICATION_RECEIVED broadcast
You can not override this method, or override this method and call super.onNotifyMessageArrived
If you override this method, there is no call super, the broadcast will not be sent to the old version Receiver
method definition
public void onNotifyMessageArrived(Context context, NotificationMessage message)
Parameter definition
- context
- applied Application Context。
- NotificationMessage
- Received notification content
Click notification callback
Supported versions
Versions supported starting from:JPush Android SDK v3.3.0
illustrate:
If needed in older version Receiver take over cn.jpush.android.intent.NOTIFICATION_OPENED broadcast
You can not override this method, or override this method and call super.onNotifyMessageOpened
If you override this method, there is no call super, the broadcast will not be sent to the old version Receiver
method definition
public void onNotifyMessageOpened(Context context, NotificationMessage message)
Parameter definition
- context
- applied Application Context。
- NotificationMessage
- Clicked notification content
Click notification button callback
Supported versions
Versions supported starting from:JPush Android SDK v5.9.0
method definition
public void onNotifyButtonClick(Context context, NotificationCustomButton notificationCustomButton)
Parameter definition
- context
- applied Application Context。
- NotificationCustomButton
- Clicked custom notification button content, including button name, action type, action content and other information
Clear notification callback
Supported versions
Versions supported starting from:JPush Android SDK v3.3.0
illustrate:
Deleting multiple notifications at the same time may not trigger the clear notification callback multiple times.
There will be a callback only if the user manually clears it. There will be no callback if the interface is cleared.
method definition
public void onNotifyMessageDismiss(Context context, NotificationMessage message)
Parameter definition
- context
- applied Application Context。
- NotificationMessage
- Cleared notification content
Notification not showing callback
Supported versions
Versions supported starting from:JPush Android SDK v3.5.8
illustrate:
1.3.5.8 Later, it will support the function of specifying that the front desk does not display when pushing. When the notification is not displayed, the interface will be called back.
method definition
public void onNotifyMessageUnShow(Context context, NotificationMessage message)
Parameter definition
- context
- applied Application Context。
- NotificationMessage
- Notification content not shown
Registration success callback
Supported versions
Versions supported starting from:JPush Android SDK v3.3.0
method definition
public void onRegister(Context context, String registrationId)
Parameter definition
- context
- applied Application Context。
- registrationId
- registration id
Long connection status callback
Supported versions
Versions supported starting from:JPush Android SDK v3.3.0
method definition
public void onConnected(Context context, boolean isConnected)
Parameter definition
- context
- applied Application Context。
- isConnected
- Long connection status
Interaction event callback
Supported versions
Versions supported starting from:JPush Android SDK v3.3.0
method definition
public void onCommandResult(Context context, CmdMessage cmdMessage)
Parameter definition
context
- applied Application Context。
CmdMessage
- Interactive event callback information.
| cmd | errorCode | msg | DESCRIPTION |
|---|---|---|---|
| 0 | fail code | Failure message | Registration failed |
| 1000 | 0 | error message | Custom message display error |
| 2003 | 0 / 1 / Others | not stop / stopped / Other exceptions | isPushStopped and getPushStatus Status callback |
| 2004 | 0 / 1 | connected / not connect | getConnectionState Asynchronous callback |
| 2005 | 0 | correspond rid | getRegistrationID Asynchronous callback |
| 2006 | 0 | set success | onResume Set callback |
| 2007 | 0 | set success | onStop Set callback |
| 2008 | 0 | success | After applying a cold start,SDK Callback when the push business function is successfully launched for the first time (only called once) |
| 10000 | 0 | none | Manufacturer token Register callback, pass extra Correspondence is available platform and token information |
Notifying MultiAction callback
Supported versions
Versions supported starting from:JPush Android SDK v3.3.2
illustrate:
If needed in older version Receiver take over cn.jpush.android.intent.NOTIFICATION_CLICK_ACTION broadcast
You can not override this method, or override this method and call super.onMultiActionClicked
If you override this method, there is no call super, the broadcast will not be sent to the old version Receiver
method definition
public void onMultiActionClicked(Context context,Intent intent)
Parameter definition
- context
- applied Application Context。
- intent
- Triggered after click Intent
Note: Note that no further adjustments are allowed in this method. super.onMultiActionClicked, because it will lead to logical confusion
Notification switch status callback
Supported versions
Versions supported starting from:JPush Android SDK v3.5.0
illustrate:
This method will be called back when the following conditions are triggered.
1.sdk After each startup, the notification switch status will be checked and called back to the developer through this method. 2.when sdk When a notification status change is detected, a callback will be made to the developer through this method.
method definition
public void onNotificationSettingsCheck(Context context,boolean isOn,int source)
Parameter definition
- context
- applied Application Context。
- isOn
- Notification switch status
- source
- Trigger scene, 0 is sdk Start, 1 indicates that notification switch status change is detected
illustrate: sdk Due to system differences, the internal method of detecting the status of the notification switch may have compatibility issues (inaccurate judgment) on a small number of models.
Pull fence list callback
Supported versions
Versions supported starting from:JPush Android SDK v4.0.7
method definition
public void onGeofenceReceived(Context context, String geofences)
Parameter definition
- context
- applied Application Context。
- geofences
- Geofence list. When the returned fence list is empty, it means that there is no fence service in the current status.
fence array
The fence returned by the transparent transmission request background json array
An example of an array of fences:
[
{
"geofenceid": "a4e6cec303",
"name": "回调围栏 3",
"center": {
"lon": "113.87500970263449",
"lat": "22.777723585199613"
},
"radius": 1000,
"status": "in",
"repeat": true,
"repeat_week_num": 0,
"repeat_day_num": 0,
"repeat_time": 0,
"expiration": 1635581786,
"type": 2, //2 标识回调类型
"create_time": 1600330718
},
{
"geofenceid": "26349557cd",
"name": "回调类型",
"center": {
"lon": "113.90311563111466",
"lat": "22.55477581705612"
},
"radius": 350,
"status": "in",
"repeat": true,
"repeat_week_num": 0,
"repeat_day_num": 0,
"repeat_time": 0,
"expiration": 1632992234,
"type": 2,
"create_time": 1600074007
}
]
trigger fence callback
Supported versions
Versions supported starting from:JPush Android SDK v4.0.7
method definition
public void onGeofenceRegion(Context context, String geofence, double longitude, double latitude)
Parameter definition
- context
- applied Application Context。
- geofence
- Trigger fence details
- longitude
- longitude when triggered
- latitude
- Dimensions when triggered
Trigger fence details
String Trigger fence details json,go through SDK Processing will add some local status
An example of triggering fence details:
{
"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" // 当前是在圈内圈外
}
In-app message display callback
The in-app message is successfully displayed, and the result will be called back in this method.
Supported versions
Versions supported starting from:JPush Android SDK v5.0.0
Interface definition
public void onInAppMessageShow(Context context, NotificationMessage message);
Parameter definition
- context
- applied Application Context。
- NotificationMessage
- Content displayed in in-app messages
In-app message click callback
If the in-app message is clicked by the user, the result will be called back in this method.
Supported versions
Versions supported starting from:JPush Android SDK v5.0.0
Interface definition
public void onInAppMessageClick(Context context, NotificationMessage message);
Parameter definition
- context
- applied Application Context。
- NotificationMessage
- In-app message click content
JPushMessageReceiver callback class
Supported version
This method is 3.0.7 New callback methods added after version (5.2.0--5.3.1 The version between is modified toJPushMessageServiceWay),5.4.0 Restore after versionJPushMessageReceiverWay
Function description
Class - cn.jpush.android.service.JPushMessageReceiver
- Related callback classes in the new message callback method.
- new tag and alias The operation callback will be triggered in the subclass of this class defined by the developer.
- The callback for mobile phone number setting will be triggered in the subclass of this class defined by the developer.
- New callback method and old customization Receiver compatible:
configured this Receiver In the future, by default, broadcasts will also be sent to old Receiver of
for onMessage、onVoipMessage、onNotifyMessageArrived、onNotifyMessageOpened、onMultiActionClicked
If these methods are overridden, you need to call super will be sent to the old Receiver
This class is the callback parent class. Developers need to inherit this class and exist Manifest Medium configuration For your corresponding implemented class, the result of the interface operation will be called back in the following method in the class you configured.
Note: Although this callback class is based on BroadcastReceiver, but in order to speed up the callback, in sdk The process will be judged internally. When the triggering process is consistent with the process configured by the component, the process will be used internally. java The callback method of the object, so it will not be generated android The life cycle of the component, so it is not recommended to declare it in this class Handler property
**JPushMessageServiceMethod: If you want to useServiceMethod, requires: **
- Supported version range:5.2.0--5.3.1
- Inherit classes from:JPushMessageReceiver Modify to JPushMessageService
- in manifest file:cn.jpush.android.intent.RECEIVER_MESSAGE-->cn.jpush.android.intent.SERVICE_MESSAGE
Message callback description (obsolete)
Supported versions
Starting version: initially.
Function description
JPush SDK Receive the push and forward it to the developer through broadcast App, so that developers can handle it flexibly.
This action is not necessary. Define only when needed by the user Receiver class to handle SDK Come broadcast.
If you don’t do this action, you don’t write customization. Receiver, not here either AndroidManifest.xml Configure this in Receiver, the default behavior is:
- If a pushed custom message is received, it will not be processed.
- The notification can be received normally and the user clicks to open the main interface of the application.
**if used JPush Android SDK v3.3.0 In and later versions, the default behavior of notification clicks changes as follows: **
- If rewritten onNotifyMessageOpened then call back to this method
- if not overridden onNotifyMessageOpened Then call back to the configuration cn.jpush.android.intent.NOTIFICATION_OPENED broadcast receiver middle
- Do not rewrite onNotifyMessageOpened There is no configuration action There is no response when clicking
**if used JPush Android SDK v3.5.0 In and later versions, the default behavior of notification clicks changes as follows: **
- Do not rewrite onNotifyMessageOpened There is no configuration action Click to jump to the home page
**if used JPush Android SDK v4.6.0 In and later versions, the default behavior of notification clicks changes as follows: **
- When there is a notification to jump to the target address, it will no longer be broadcast. extras Parameter, if there is no notification of the jump target address, broadcast extras parameter(onNotifyMessageOpened method)
receive broadcast
If all types of broadcasts are received, you need to AndroidManifest.xml Add the following configuration information:
<receiver
android:name="Your Receiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="cn.jpush.android.intent.REGISTRATION" />
<action android:name="cn.jpush.android.intent.MESSAGE_RECEIVED" />
<action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED" />
<action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED" />
<action android:name="cn.jpush.android.intent.NOTIFICATION_CLICK_ACTION" />
<action android:name="cn.jpush.android.intent.CONNECTION" />
<category android:name="You package Name" />
</intent-filter>
</receiver>
each Receiver action Detailed explanation is as follows.
Action - JPushInterface.ACTION_REGISTRATION_ID
string value
"cn.jpush.android.intent.REGISTRATION"
Function description
SDK Towards JPush Server Registration ID obtained from registration.
Generally speaking, this broadcast message may not be processed.
to integrate deeplyJPush, the developer wants to save it himself App Users and JPush user relationship, accept this broadcast and obtain Registration ID and save it with App uid The relationship is on the developer's own application server.
useJPushThe alias and label functions provided are simpler and lighter binding App Users and JPush For user methods, please refer to the documentation:Tutorial on using aliases and tags.
Intent parameter
JPushInterface.EXTRA_REGISTRATION_ID
SDK Towards JPush Server The globally unique ID obtained by registration can be used to send messages and notifications to the corresponding client.
Bundle bundle = intent.getExtras(); String title = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);Bundle bundle = intent.getExtras(); String title = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);This code block is shown in the floating window
Action - JPushInterface.ACTION_MESSAGE_RECEIVED
string value
"cn.jpush.android.intent.MESSAGE_RECEIVED"
Function description
Custom message received Push。
SDK Custom messages are only delivered and will not be displayed on any interface.
If the developer wants to push a custom message Push, you need to AndroidManifest.xml Configure this here Receiver action, and in my own writing BroadcastReceiver receive processing.
Intent parameter
JPushInterface.EXTRA_TITLE
Save the title of the message pushed by the server.
correspond API message content title field.
Portal Not displayed on the push message interface
Bundle bundle = intent.getExtras(); String title = bundle.getString(JPushInterface.EXTRA_TITLE);
JPushInterface.EXTRA_MESSAGE
Save the message content pushed by the server.
correspond API message content message field.
correspond Portal The "Customized message content" field on the push message interface.
Bundle bundle = intent.getExtras(); String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);Bundle bundle = intent.getExtras(); String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);This code block is shown in the floating window
JPushInterface.EXTRA_EXTRA
Save additional fields pushed down by the server. This is a JSON String.
correspond API message content extras field.
correspond Portal Additional fields in the "Optional Settings" on the push message interface.
Bundle bundle = intent.getExtras(); String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);Bundle bundle = intent.getExtras(); String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);This code block is shown in the floating window
JPushInterface.EXTRA_MSG_ID
JPush Android SDK v1.6.1 Supported by the above versions.
The ID that uniquely identifies the message can be used for reporting statistics, etc.
Bundle bundle = intent.getExtras(); String file = bundle.getString(JPushInterface.EXTRA_MSG_ID);Bundle bundle = intent.getExtras(); String file = bundle.getString(JPushInterface.EXTRA_MSG_ID);This code block is shown in the floating window
Action - JPushInterface.ACTION_NOTIFICATION_RECEIVED
string value
"cn.jpush.android.intent.NOTIFICATION_RECEIVED"
Function description
Notification received Push。
If the content of the notification is empty, the notification will not be displayed on the notification bar.
However, this broadcast Intent There will still be. Developers can obtain other information besides the notification content.
Intent parameter
JPushInterface.EXTRA_NOTIFICATION_TITLE
Save the title of the notification pushed by the server.
correspond API notification content title field.
correspond Portal The "Notification Title" field on the push notification interface.
Bundle bundle = intent.getExtras(); String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);Bundle bundle = intent.getExtras(); String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);This code block is shown in the floating window
JPushInterface.EXTRA_ALERT
Save the notification content pushed by the server.
correspond API notification content alert field.
correspond Portal The "Notification content" field on the push notification interface.
Bundle bundle = intent.getExtras(); String content = bundle.getString(JPushInterface.EXTRA_ALERT);Bundle bundle = intent.getExtras(); String content = bundle.getString(JPushInterface.EXTRA_ALERT);This code block is shown in the floating window
JPushInterface.EXTRA_EXTRA
JPush Android SDK v1.2.9 Supported by the above versions.
Save additional fields pushed down by the server. This is a JSON String.
correspond API notification content extras field.
correspond Portal Additional fields in the "Optional Settings" on the push message interface.
Bundle bundle = intent.getExtras(); String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);Bundle bundle = intent.getExtras(); String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);This code block is shown in the floating window
JPushInterface.EXTRA_NOTIFICATION_ID
JPush Android SDK v1.3.5 Supported by the above versions.
notification bar Notification ID, can be used to clear Notification
If the server content (alert) field is empty, then Notification ID is 0
Bundle bundle = intent.getExtras(); int notificationId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);Bundle bundle = intent.getExtras(); int notificationId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);This code block is shown in the floating window
JPushInterface.EXTRA_RICHPUSH_HTML_PATH
JPush Android SDK v1.4.0 Supported by the above versions.
Rich media notification push download HTML file path, used to display WebView。
Bundle bundle = intent.getExtras(); String fileHtml = bundle.getString(JPushInterface.EXTRA_RICHPUSH_HTML_PATH);Bundle bundle = intent.getExtras(); String fileHtml = bundle.getString(JPushInterface.EXTRA_RICHPUSH_HTML_PATH);This code block is shown in the floating window
JPushInterface.EXTRA_RICHPUSH_HTML_RES
JPush Android SDK v1.4.0 Supported by the above versions.
The file name of the image resource downloaded by rich media notification push. Multiple file names are separated by ",". and "JPushInterface.EXTRA_RICHPUSH_HTML_PATH” on the same path.
Bundle bundle = intent.getExtras(); String fileStr = bundle.getString(JPushInterface.EXTRA_RICHPUSH_HTML_RES); String[] fileNames = fileStr.split(",");Bundle bundle = intent.getExtras(); String fileStr = bundle.getString(JPushInterface.EXTRA_RICHPUSH_HTML_RES); String[] fileNames = fileStr.split(",");This code block is shown in the floating window
JPushInterface.EXTRA_MSG_ID
JPush Android SDK v1.6.1 Supported by the above versions.
The ID that uniquely identifies the notification message can be used for reporting statistics, etc.
Bundle bundle = intent.getExtras(); String file = bundle.getString(JPushInterface.EXTRA_MSG_ID);Bundle bundle = intent.getExtras(); String file = bundle.getString(JPushInterface.EXTRA_MSG_ID);This code block is shown in the floating window
JPushInterface.EXTRA_BIG_TEXT
JPush Android SDK v3.0.0 The above versions support, support api 16 and above rom。
The content of the large text in the large text notification style.
Bundle bundle = intent.getExtras(); String bigText = bundle.getString(JPushInterface.EXTRA_BIG_TEXT);Bundle bundle = intent.getExtras(); String bigText = bundle.getString(JPushInterface.EXTRA_BIG_TEXT);This code block is shown in the floating window
JPushInterface.EXTRA_BIG_PIC_PATH
JPush Android SDK v3.0.0 The above versions support, support api 16 and above rom。
It can support the path of local images or fill in the address of network images.
The path/address of the large image in the large image notification style.
Bundle bundle = intent.getExtras(); String bigPicPath = bundle.getString(JPushInterface.EXTRA_BIG_PIC_PATH);Bundle bundle = intent.getExtras(); String bigPicPath = bundle.getString(JPushInterface.EXTRA_BIG_PIC_PATH);This code block is shown in the floating window
JPushInterface.EXTRA_INBOX
JPush Android SDK v3.0.0 The above versions support, support api 16 and above rom。
What is obtained is a JSONObject,json of each key Corresponding value Will be displayed item by item as text items.
The contents of the inbox in the inbox notification style.
Bundle bundle = intent.getExtras(); String inboxJson = bundle.getString(JPushInterface.EXTRA_INBOX);Bundle bundle = intent.getExtras(); String inboxJson = bundle.getString(JPushInterface.EXTRA_INBOX);This code block is shown in the floating window
JPushInterface.EXTRA_NOTI_PRIORITY
JPush Android SDK v3.0.0 The above versions support, support api 16 and above rom。
The default is 0, the range is -2 ~ 2, other values will be ignored and the default will be used.
The priority of the notification.
Bundle bundle = intent.getExtras(); String prio = bundle.getString(JPushInterface.EXTRA_NOTI_PRIORITY);Bundle bundle = intent.getExtras(); String prio = bundle.getString(JPushInterface.EXTRA_NOTI_PRIORITY);This code block is shown in the floating window
JPushInterface.EXTRA_NOTI_CATEGORY
JPush Android SDK v3.0.0 The above versions support, support api 21 and above rom。
completely dependent on rom manufacturer for each category processing strategies, such as the sorting of the notification bar.
Notification categories.
Bundle bundle = intent.getExtras(); String prio = bundle.getString(JPushInterface.EXTRA_NOTI_CATEGORY);Bundle bundle = intent.getExtras(); String prio = bundle.getString(JPushInterface.EXTRA_NOTI_CATEGORY);This code block is shown in the floating window
Action - JPushInterface.ACTION_NOTIFICATION_OPENED
string value
"cn.jpush.android.intent.NOTIFICATION_OPENED"
Function description
The user clicked on the notification. Generally, users do not need to configure this receiver action。
If the developer is AndroidManifest.xml This is not configured in receiver action,So,SDK will open the application's main Activity, equivalent to the effect of the user clicking on the desktop icon.
If the developer is AndroidManifest.xml This is configured in receiver action, then when the user clicks on the notification,SDK Can't make moves. Developers should write their own BroadcastReceiver Processed in a class, such as opening a Activity 。
Intent parameter
JPushInterface.EXTRA_NOTIFICATION_TITLE
Save the title of the notification pushed by the server.
correspond API notification content title field.
correspond Portal The "Notification Title" field on the push notification interface.
Bundle bundle = intent.getExtras(); String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);Bundle bundle = intent.getExtras(); String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);This code block is shown in the floating window
JPushInterface.EXTRA_ALERT
Save the notification content pushed by the server.
correspond API notification content alert field.
correspond Portal The "Notification content" field on the push notification interface.
Bundle bundle = intent.getExtras(); String content = bundle.getString(JPushInterface.EXTRA_ALERT);Bundle bundle = intent.getExtras(); String content = bundle.getString(JPushInterface.EXTRA_ALERT);This code block is shown in the floating window
JPushInterface.EXTRA_EXTRA
JPush Android SDK v1.2.9 Supported by the above versions.
Save additional fields pushed down by the server. This is a JSON String.
correspond API message content extras field.
correspond Portal Additional fields in the "Optional Settings" on the push message interface.
Bundle bundle = intent.getExtras(); String type = bundle.getString(JPushInterface.EXTRA_EXTRA);Bundle bundle = intent.getExtras(); String type = bundle.getString(JPushInterface.EXTRA_EXTRA);This code block is shown in the floating window
JPushInterface.EXTRA_NOTIFICATION_ID
JPush Android SDK v1.3.5 Supported by the above versions.
notification bar Notification ID, can be used to clear Notification
Bundle bundle = intent.getExtras(); int notificationId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);Bundle bundle = intent.getExtras(); int notificationId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);This code block is shown in the floating window
JPushInterface.EXTRA_MSG_ID
JPush Android SDK v1.6.1 Supported by the above versions.
The ID that uniquely identifies the adjustment message can be used for reporting statistics, etc.
Bundle bundle = intent.getExtras(); String file = bundle.getString(JPushInterface.EXTRA_MSG_ID);Bundle bundle = intent.getExtras(); String file = bundle.getString(JPushInterface.EXTRA_MSG_ID);This code block is shown in the floating window
Action - JPushInterface.ACTION_NOTIFICATION_CLICK_ACTION
string value
"cn.jpush.android.intent.NOTIFICATION_CLICK_ACTION"
Function description
The user clicked a custom button in the notification bar. (JPush Android SDK v3.0.0 Supported by above versions)
Developers using normal notifications do not need to configure this receiver action. Only used by developers MultiActionsNotificationBuilder When building a notification bar with a button, you can use this action Capture the user's click on the notification bar button and process it yourself.
Intent parameter
JPushInterface.EXTRA_NOTIFICATION_ACTION_EXTRA
SDK 3.0.0 Supported by the above versions.
Get additional information carried by the notification bar button click event.
Corresponding use MultiActionsNotificationBuilder.addJPushAction Added button information.
private void setAddActionsStyle() {MultiActionsNotificationBuilder builder = new MultiActionsNotificationBuilder(PushSetActivity.this); builder.addJPushAction(R.drawable.jpush_ic_richpush_actionbar_back, "first", "my_extra1"); builder.addJPushAction(R.drawable.jpush_ic_richpush_actionbar_back, "second", "my_extra2"); builder.addJPushAction(R.drawable.jpush_ic_richpush_actionbar_back, "third", "my_extra3"); JPushInterface.setPushNotificationBuilder(10, builder); Toast.makeText(PushSetActivity.this, "AddActions Builder - 10", Toast.LENGTH_SHORT).show();}private void setAddActionsStyle() {MultiActionsNotificationBuilder builder = new MultiActionsNotificationBuilder(PushSetActivity.this); builder.addJPushAction(R.drawable.jpush_ic_richpush_actionbar_back, "first", "my_extra1"); builder.addJPushAction(R.drawable.jpush_ic_richpush_actionbar_back, "second", "my_extra2"); builder.addJPushAction(R.drawable.jpush_ic_richpush_actionbar_back, "third", "my_extra3"); JPushInterface.setPushNotificationBuilder(10, builder); Toast.makeText(PushSetActivity.this, "AddActions Builder - 10", Toast.LENGTH_SHORT).show();}This code block is shown in the floating windowObtain the corresponding additional information, determine which button it is, and process it yourself.
else if (JPushInterface.ACTION_NOTIFICATION_CLICK_ACTION.equals(intent.getAction())){Log.d(TAG, "[MyReceiver] The user clicked the notification bar button"); String nActionExtra = intent.getExtras().getString(JPushInterface.EXTRA_NOTIFICATION_ACTION_EXTRA); // Developers vary according to Action portable extra fields to assign different actions. if(nActionExtra==null){Log.d(TAG,"ACTION_NOTIFICATION_CLICK_ACTION nActionExtra is null"); return; } if (nActionExtra.equals("my_extra1")) {Log.d(TAG, "[MyReceiver] The user clicks the notification bar button 1");} else if (nActionExtra.equals("my_extra2")) {Log.d(TAG, "[MyReceiver] The user clicks the notification bar button two");} else if (nActionExtra.equals("my_extra3")) {Log.d(TAG, "[MyReceiver] The user clicks the notification bar button three");} else {Log.d(TAG, "[MyReceiver] The user clicks the notification bar button is undefined");} }else if (JPushInterface.ACTION_NOTIFICATION_CLICK_ACTION.equals(intent.getAction())){Log.d(TAG, "[MyReceiver] The user clicked the notification bar button"); String nActionExtra = intent.getExtras().getString(JPushInterface.EXTRA_NOTIFICATION_ACTION_EXTRA); // Developers vary according to Action portable extra fields to assign different actions. if(nActionExtra==null){Log.d(TAG,"ACTION_NOTIFICATION_CLICK_ACTION nActionExtra is null"); return; } if (nActionExtra.equals("my_extra1")) {Log.d(TAG, "[MyReceiver] The user clicks the notification bar button 1");} else if (nActionExtra.equals("my_extra2")) {Log.d(TAG, "[MyReceiver] The user clicks the notification bar button two");} else if (nActionExtra.equals("my_extra3")) {Log.d(TAG, "[MyReceiver] The user clicks the notification bar button three");} else {Log.d(TAG, "[MyReceiver] The user clicks the notification bar button is undefined");} }This code block is shown in the floating window
Action - JPushInterface.ACTION_CONNECTION_CHANGE
string value
"cn.jpush.android.intent.CONNECTION"
Function description
JPush The service's connection status changes. (Note: does not refer to Android The system's network connection status. )
Intent parameter
JPushInterface.EXTRA_CONNECTION_CHANGE
JPush Android SDK v1.6.3 Supported by the above versions.
Get current JPush The connection status of the service.
Bundle bundle = intent.getExtras(); boolean connected = bundle.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);Bundle bundle = intent.getExtras(); boolean connected = bundle.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);This code block is shown in the floating window
Developer customization Receiver code example
public void onReceive(Context context, Intent intent) {Bundle bundle = intent.getExtras();
Log.d(TAG, "onReceive -" + intent.getAction());
if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
Log.d(TAG, "[MyReceiver] take over Registration Id:" + regId);}else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {Log.d(TAG, "A custom message was received. The message content is:" + bundle.getString(JPushInterface.EXTRA_MESSAGE));
// Custom messages will not be displayed in the notification bar, and developers must write code to handle them.
} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {Log.d(TAG, "Notification received");
// You can do some statistics or other work here
} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {Log.d(TAG, "The user clicked to open the notification");
// Here you can write your own code to define the user's behavior after clicking
Intent i = new Intent(context, TestActivity.class); // Customize the opening interface
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
} else {Log.d(TAG, "Unhandled intent -" + intent.getAction());
}
}
For more sample codes, please refer to Android SDK Compressed package in example project.
JPushMessage Result class (new callback)
Supported version
JPush Android SDK v3.0.7 Callback method added after version.
Function description
Class - cn.jpush.android.api.JPushMessage
- The result class of the relevant callback in the new message callback method. Use this class object to obtain the corresponding operation result.
- Currently only new tag and alias Operation callbacks will involve this class.
Query alias
Passed or queried by the developer alias。
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
method definition
public String getAlias();
Query tag
Passed or queried by the developer tags。
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
method definition
public Set<String> getTags();
Get operation return code
The return code of the corresponding operation, 0 means success. For other return codes, please refer to the error code definition.
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
method definition
public int getErrorCode();
get Sequence
passed in when the developer calls the interface sequence, through the sequence Developers can obtain the corresponding operations from the developer's own cache.
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
method definition
public int getSequence();
Query the binding status of tags
What developers want to query tag The status bound to the current user.
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
method definition
public boolean getTagCheckStateResult();
Query the label of binding status
Developers want to query the binding status tag。
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
method definition
public String getCheckTag();
Get mobile number
The mobile phone number passed in when the developer calls the setting interface.
Supported versions
Versions supported starting from:JPush Android SDK v3.1.1
method definition
public String getMobileNumber();
NotificationChannel Configuration
Supported versions
Versions supported starting from:JPush Android SDK v3.3.4
Function description
Android8.0 No notice will be given in the future NotificationChannel.开发者可以自行定义 NotificationChannel, and then in API You can specify it when pushing channelId Push; exist Android8.0 For models and above, the notification will first search for the corresponding channelId of channel, the notification’s importance level, sound, vibration, and breathing light are determined by channel Decide; if not found channelId, or within the silent time, use the defaultJiguang channel。
Customize NotificationChannel Example
private void initChannel(){if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (nm != null){NotificationChannelGroup notificationChannelGroup = new NotificationChannelGroup("MyGroupId", "自定义通知组");
nm.createNotificationChannelGroup(notificationChannelGroup);
NotificationChannel notificationChannel = new NotificationChannel("MyChannelId", "自定义通知", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setGroup("MyGroupId");
notificationChannel.enableLights(true);
notificationChannel.enableVibration(true);
notificationChannel.setSound("android.resource:// 包名 /raw/ 铃声文件", null); // 设置自定义铃声
nm.createNotificationChannel(notificationChannel);
}
}
}
Custom ringtone configuration
Supported versions
Versions supported starting from:JPush Android SDK v3.3.8
Function description
This feature enables a custom ringtone to sound when the user receives a push notification.
- The ringtone file needs to be placed in the application project /res/raw/ under directory
- exist portal Fill in the file name of the custom ringtone. Note that no previous directory or suffix is required.
- Note that if the push is specified channel_id, then the ringtone effect is changed from the existing one on the phone channel The ringtone effect shall prevail. Since there are certain compatibility issues between different models and manufacturer channels, we recommend that developers create custom channel,exist channel Configure a custom ringtone (as in the example in the previous section), so you can have better control.
- Note that if a silent push time is specified, notifications received during the silent period will have no ringtone even if a custom ringtone is set.
Aliases and tags API
The new alias and label interface supports the functions of adding, deleting, modifying, and querying. 3.0.7 This version is supported starting from 3.0.7 This version will no longer be maintained.
Notice:JiguangAt 2020/03/10 Limit the upper limit of "Alias Settings", allowing up to 10 devices to be bound. If you need a higher limit, please contact business, please read for details announcement。
JPush Android v3.5.8 and above,JPush iOS v3.3.2 and above versions will return error code:6027。
JPush Android v3.5.8 the following,JPush iOS v3.3.2 The following versions will return error codes:6017。
If you are still using an old version with outdated alias and label interfaces, such as JPushInterface. setAliasAndTags and JPushInterface.setAlias interface, if the background detects that the setting exceeds the limit, error code 5 will be called back through the interface.
Function description
温馨提示,设置标签别名请注意处理 call back 结果,只有设置成功才可以向目标推送,否则服务器 API 会返回 1011 错误。
从 3.0.7 版本开始,别名和标签是异步回调,注意在 Androidmanifest 里面配置自定义广播接收器
Alias alias
Give an alias to identify the user who installed the application. to this user in the future Push When sending a message, you can use this alias to specify.
Only one alias can be specified per user.
Within the same application, it is recommended to use different aliases for different users. This way, the user is uniquely identified based on the alias whenever possible.
The system does not limit an alias to specify only one user. If an alias is assigned to multiple users, when sending a message to the specified alias,server side API Messages will be sent to multiple users at the same time.
For example: In a game where a user wants to log in, the alias may be set to userid. During game operation, if it is found that the user has not played the game for 3 days, the user will be userid call server side API Send a notification to the client to remind the user.
Notice:JiguangAt 2020/03/10 Limit the upper limit of "Alias Settings", allowing up to 10 devices to be bound. If you need a higher limit, please contact business, please read for details announcement。
JPush Android v3.5.8 and above,JPush iOS v3.3.2 and above versions will return error code:6027。
JPush Android v3.5.8 the following,JPush iOS v3.3.2 The following versions will return error codes:6017。
Label tag
Label users who have installed the application. Its purpose is mainly to facilitate developers to issue batches based on tags. Push information.
Multiple tags can be assigned to each user.
Example: game, old_page, women
Callback description
new alias alias with tags tag Interface callback trigger cn.jpush.android.service.JPushMessageReceiver, please refer to the detailed callback method. Description of new message callback method。
Filter valid tags
Usage suggestions
set up tags, if one of the tag If it is invalid, the entire setup process fails.
if App of tags will be set dynamically during operation, and there are JPush SDK tag Specified invalid characters,
It is possible that one tag Invalid results in all the tags Update failed.
At this time you can call this method filterValidTags to filter out invalid tags, get a valid tags,
call again JPush SDK of set tags / alias method.
Supported versions
Versions supported starting from:JPush Android SDK v1.5.0
interface definition
public static Set<String> filterValidTags(Set<String> tags);
interface returns
valid tag gather.
Set alias
call this API to set the alias.
What needs to be understood is that this interface is overwriting logic, not incremental logic. That is, new calls will overwrite previous settings.
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
Interface definition
public static void setAlias(Context context, int sequence, String alias);
Parameter definition
sequence
- The user-defined operation sequence number is returned together with the operation result and is used to identify the uniqueness of an operation. It is recommended to use a different numerical sequence number each time.
alias
- Each call sets a valid alias, overwriting the previous setting.
- Valid aliases consist of: letters (case sensitive), numbers, underscores, Chinese characters, special characters @!#$&*+=.|.
- limit:alias Name length is limited to 40 bytes. (To judge the length, you need to use UTF-8 coding)
result callback
See details onAliasOperatorResult method.
Things to note
- init directly after set The operation is very likely to fail and may be obtained in the callback 6022,6002 Wait, you can set a delay of 7 or 8 seconds during testing. In official business, it is usually used with user registration. The delay is basically enough.
- when target alias When there are already 10 devices in the download, you may get an error message when trying to bind again. 6017,6027, you can try calling ours in the background Server delete interface Clear all binding relationships.
Delete alias
call this API to delete the alias.
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
Interface definition
public static void deleteAlias(Context context,int sequence);
Parameter definition
- sequence
- The user-defined operation sequence number is returned together with the operation result and is used to identify the uniqueness of an operation.
result callback
See details onAliasOperatorResult method.
Things to note
- This interface can only clear the current device and target alias binding relationship, if you want to clear the target alias For binding relationships with all devices, please adjust Server delete interface。
Query alias
call this API to query the alias.
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
Interface definition
public static void getAlias(Context context,int sequence);
Parameter definition
- sequence
- The user-defined operation sequence number is returned together with the operation result and is used to identify the uniqueness of an operation.
result callback
See details onAliasOperatorResult method.
Set label
call this API to set the label.
What needs to be understood is that this interface is overwriting logic, not incremental logic. That is, new calls will overwrite previous settings.
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
Interface definition
public static void setTags(Context context, int sequence,Set<String> tags);
Parameter definition
sequence
- The user-defined operation sequence number is returned together with the operation result and is used to identify the uniqueness of an operation.
tags
- Set at least one per call tag, overwrite the previous settings, not add new ones.
- Valid tags consist of: letters (case sensitive), numbers, underscores, Chinese characters, special characters @!#$&*+=.|.
- Limit: each tag The name length is limited to 40 bytes and supports up to 1000 indivual tag, and the total length of a single operation shall not exceed 5000 byte. (To judge the length, you need to use UTF-8 coding)
- A single device supports at most settings 1000 indivual tag。App overall situation tag Unlimited quantity.
result callback
See details onTagOperatorResult method.
Add new tag
call this API to add a new label.
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
Interface definition
public static void addTags(Context context, int sequence,Set<String> tags);
Parameter definition
sequence
- The user-defined operation sequence number is returned together with the operation result and is used to identify the uniqueness of an operation.
tags
- Each call adds at least one new tag。
- Valid tags consist of: letters (case sensitive), numbers, underscores, Chinese characters, special characters @!#$&*+=.|.
- Limit: each tag The name length is limited to 40 bytes and supports up to 1000 indivual tag, and the total length of a single operation shall not exceed 5000 byte. (To judge the length, you need to use UTF-8 coding)
- A single device supports at most settings 1000 indivual tag。App overall situation tag Unlimited quantity.
result callback
See details onTagOperatorResult method.
Delete tag
call this API to delete the specified tag.
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
Interface definition
public static void deleteTags(Context context, int sequence,Set<String> tags);
Parameter definition
sequence
- The user-defined operation sequence number is returned together with the operation result and is used to identify the uniqueness of an operation.
tags
- Delete at least one per call tag。
- Valid tags consist of: letters (case sensitive), numbers, underscores, Chinese characters, special characters @!#$&*+=.|.
- Limit: each tag The name length is limited to 40 bytes and supports up to 1000 indivual tag, and the total length of a single operation shall not exceed 5000 byte. (To judge the length, you need to use UTF-8 coding)
- A single device supports at most settings 1000 indivual tag。App overall situation tag Unlimited quantity.
result callback
See details onTagOperatorResult method.
Clear all tags
call this API to clear all tags.
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
Interface definition
public static void cleanTags(Context context, int sequence);
Parameter definition
- sequence
- The user-defined operation sequence number is returned together with the operation result and is used to identify the uniqueness of an operation.
result callback
See details onTagOperatorResult method.
Query all tags
call this API to query all tags.
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
Interface definition
public static void getAllTags(Context context, int sequence);
Parameter definition
- sequence
- The user-defined operation sequence number is returned together with the operation result and is used to identify the uniqueness of an operation.
result callback
See details onTagOperatorResult method.
Query the binding status of the specified tag
call this API to query the specified tag The status bound to the current user.
Supported versions
Versions supported starting from:JPush Android SDK v3.0.7
Interface definition
public static void checkTagBindState(Context context,int sequence,String tag);
Parameter definition
sequence
- The user-defined operation sequence number is returned together with the operation result and is used to identify the uniqueness of an operation.
tag
- queried tag
result callback
See details onCheckTagOperatorResult method.
Aliases and tags API(old)
1.5.0 ~ 3.0.6 The alias and label interfaces provided by the version are overlay logic, from 3.0.7 The version will no longer be maintained (but will continue to be maintained). Recommended for developers to use 3.0.7 Start offering new tag、alias interface.
Set aliases and tags (with Callback)
call this API to set both alias and label at the same time.
What needs to be understood is that this interface is overwriting logic, not incremental logic. That is, new calls will overwrite previous settings.
After the previous call, if you need to change the alias and label again, you only need to call this again. API That’s it.
Supported versions
Versions supported starting from:JPush Android SDK v1.5.0
Interface definition
public static void setAliasAndTags(Context context,
String alias,
Set<String> tags,
TagAliasCallback callback);
Parameter definition
alias
- null This call does not set this value. (Note: This does not refer to the string "null" )
- "" (empty string) means canceling the previous setting.
- Each call sets a valid alias, overwriting the previous setting.
- Valid aliases consist of: letters (case sensitive), numbers, underscores, Chinese characters, special characters (2.1.6 Support)@!#$&*+=.|.
- limit:alias Name length is limited to 40 bytes. (To judge the length, you need to use UTF-8 coding)
tags
- null This call does not set this value. (Note: This does not refer to the string "null" )
- An empty array or list means canceling the previous settings.
- Set at least one per call tag, overwrite the previous settings, not add new ones.
- Valid label composition: letters (case sensitive), numbers, underlines, Chinese characters, special characters (2.1.6 Support)@!#$&*+=.|.
- Limit: each tag The name length is limited to 40 bytes and supports up to 1000 indivual tag, and the total length of a single operation shall not exceed 7000 byte. (To judge the length, you need to use UTF-8 coding)
callback
- exist TagAliasCallback of gotResult Method, returns the corresponding parameters alias、tags. And return the corresponding status code: 0 for success. For other return codes, please refer to the error code definition.
Set alias
call this API to set the alias.
What needs to be understood is that this interface is overwriting logic, not incremental logic. That is, new calls will overwrite previous settings. In other words, a device can only have one alias.
Supported versions
Versions supported starting from:JPush Android SDK v1.5.0
Interface definition
public static void setAlias(Context context, String alias, TagAliasCallback callback)
Parameter definition
alias
- "" (empty string) means canceling the previous setting.
- Each call sets a valid alias, overwriting the previous setting.
- Valid aliases consist of: letters (case sensitive), numbers, underscores, Chinese characters, special characters (2.1.6 Support)@!#$&*+=.|.
- limit:alias Name length is limited to 40 bytes. (To judge the length, you need to use UTF-8 coding)
callback
- exist TagAliasCallback of gotResult Method, returns the corresponding parameters alias、tags. And return the corresponding status code: 0 for success. For other return codes, please refer to the error code definition.
Set label
call this API to set the label.
What needs to be understood is that this interface is overwriting logic, not incremental logic. That is, new calls will overwrite previous settings.
Usage suggestions
If to be set alias / tags is dynamic, it is possible to call setAliasAndTags time because alias / tags Invalid and the entire call failed.
Calling this method only sets tags, you can exclude potentially invalid alias impact on this call.
Supported versions
Versions supported starting from:JPush Android SDK v1.5.0
Interface definition
public static void setTags(Context context, Set<String> tags, TagAliasCallback callback)
Parameter definition
tags
- An empty array or list means canceling the previous settings.
- Set at least one per call tag, overwrite the previous settings, not add new ones.
- Valid label composition: letters (case sensitive), numbers, underlines, Chinese characters, special characters (2.1.6 Support)@!#$&*+=.|.
- Limit: each tag The name length is limited to 40 bytes and supports up to 1000 indivual tag, and the total length of a single operation shall not exceed 7000 byte. (To judge the length, you need to use UTF-8 coding)
- A single device supports at most settings 1000 indivual tag。App overall situation tag Unlimited quantity.
callback
- exist TagAliasCallback of gotResult Method, returns the corresponding parameters alias, tags. And return the corresponding status code: 0 for success. For other return codes, please refer to the error code definition.
Set callback classes for alias and label methods
Class - TagAliasCallback
Set the callback class for the alias and label methods, which can be found in gotResult Get the result of the callback on the method. callback responseCode = 0, then the setting is confirmed to be successful.
Supported versions
Versions supported starting from:JPush Android SDK v1.5.0
Interface definition
public void gotResult(int responseCode, String alias, Set<String> tags);
Parameter definition
- responseCode
- 0 means the call was successful.
- For other return codes, please refer to the error code definition.
- alias
- Original alias
- tags
- Original label
Error code definition
Please jump to Error code definition list
Related documents
get RegistrationID API
Supported versions
Versions supported starting from:JPush Android SDK v1.6.0
Function description
RegistrationID definition
Integrated JPush SDK The application is successfully registered for the first time to JPush When the serverJPush The server will return a unique identifier of the device to the client - RegistrationID。JPush SDK will be sent as a broadcast RegistrationID to the application.
Applications can use this RegistrationID Save it on your own application server, and then you can RegistrationID to push messages or notifications to the device.
Implementation method
call this API to obtain the corresponding RegistrationID. **Only if the application is successfully registered to JPush The corresponding value is returned only if the server is connected, otherwise an empty string is returned. **
Note:v3.3.0 Version starts, can be done in new callback (onRegister method) to monitor the RegistrationID。
Supported versions
Versions supported starting from:JPush Android SDK v1.6.0
Interface definition
SDK After successful initial registration, the developer can Receiver Listen here Action - cn.jpush.android.intent.REGISTRATION to get the corresponding RegistrationID。
After successful registration, you can also use the function public static String getRegistrationID(Context context) get
Additional notes
pass RegistrationID Perform peer-to-peer push
can pass RegistrationID To push messages and notifications, refer to the documentation Push API v3,set up Audience for RegistrationID can be based on RegistrationID push.
Note: To use this feature, the client App Must be integrated 1.6.0 and above versions JPush Android SDK。
Set mobile number API
Supported versions
Versions supported starting from:JPush Android SDK v3.1.1
Function description
call this API Set mobile phone number for SMS supplementary function. This interface will control the calling frequency, the frequency is 10s Up to 3 times within a period.
Note: SMS supplement only supports domestic services. The number format is 11 digits. +86 Any prefix is acceptable.
Implementation method
Interface definition
public static void setMobileNumber(Context context,int sequence, String mobileNumber);
Parameter definition
- context
- applied ApplicationContext。
- sequence
- The user-defined operation sequence number is returned together with the operation result and is used to identify the uniqueness of an operation.
- mobileNumber
- phone number. If you pass null Or an empty string is used to unbind the number.
- Restrictions: It can only start with "+" or a number; the following content can only contain "-" and numbers.
Callback description
Interface callback trigger cn.jpush.android.service.JPushMessageReceiver, please refer to the detailed callback method. Description of new message callback method。
Manufacturer channel Token Callback description
at home Android In the ecosystem, push channels are maintained by long links between the terminal and the cloud, which are heavily dependent on the survival status of the application process. Nowadays, some mobile phone manufacturers will use their own rom Create a system-level push channel in the system, and then the system distributes it to each app, using this to improve your own rom Push deliverability on. each rom Both provide different callbacks token interface,JPush SDK Provides a unified callback interface.
Special instructions:
If you use JPush Android SDK Version < v6.0.0 版本,获取厂商 token 时,代码取值字段名为 “token”,代码示例:String token = cmdMessage.extra.getString("token");
If you use JPush Android SDK version = v6.0.0 version, get manufacturer token When, the code value field name needs to be changed from "token"Change to "ttoken”, code example:String token = cmdMessage.extra.getString("ttoken");
If you use JPush Android SDK Version > v6.0.0 version, get manufacturer token When, the code value field name can be "token" or "ttoken”, the code example is as above.
Sample code
@Override
public void onCommandResult(Context context, CmdMessage cmdMessage) {
// Registration failed + third-party vendor registration callback
Log.e(TAG,"[onCommandResult]"+cmdMessage);
//cmd for 10000 When indicated as the manufacturer token callback
if(cmdMessage!=null&&cmdMessage.cmd==10000&&cmdMessage.extra!=null){String token = cmdMessage.extra.getString("token");
int platform = cmdMessage.extra.getInt("platform");
String deviceName = "unkown";
switch (platform){
case 1:
deviceName = "Xiaomi";
break;
case 2:
deviceName = "Huawei";
break;
case 3:
deviceName = "Meizu";
break;
case 4:
deviceName = "OPPO";
break;
case 5:
deviceName = "VIVO";
break;
case 6:
deviceName = "ASUS";
break;
case 7:
deviceName = "Glory";
break;
case 8:
deviceName = "FCM";
break;
case 16:
deviceName = "NIO";
break;
}
Log.e(TAG,"get"+deviceName+"of token:"+token);
}
}
Callback timing
exist sdk binding token Callback when successful, when sdk The callback will be triggered again when the version changes.
When there is a callback token for null Situations: 1. When there is a problem with the integration, there will be a callback null. 2. Unable to obtain the manufacturer due to issues such as manufacturer service and other issues token hour.
Configure download channels API
Function description
Dynamic configuration channel(Package download channel), priority ratio AndroidManifest The configuration is high
- channel Indicate the download channel of the application package. To facilitate statistics by channel, the specific value is defined by you, such as Huawei App Market, Xiaomi App Store, etc.
- JPush Android SDK v3.1.5 Supported by the above versions.
Interface definition
public static void setChannel(Context context, String channel);
Parameter description
- context applied ApplicationContext
- channel Hope to configure channel(Package download channel), transfer null Indicates that it is still used AndroidManifest configured in channel
code example
JPushInterface.setChannel(this, "Huawei AppGallery");
Obtaining and switching the in-app message page
Page life cycle monitoring
In-app message display depends on the page, so the life cycle of the page needs to be monitored.
ActivityWay
JiguangSDKinternal meetingActivityLife cycle monitoring and dynamic control processing, developers do not need special processing
FragmentWay
FragmentDevelopers are required to actively call interface classesJPushInterface The following two interfaces perform dynamic control
/**
* EnterFragmentpage, call this interface
* @param context ApplicationContext
* @param fragmentName FragmentFull class name of the page (this.getClass().getCanonicalName())
*/
public static void onFragmentResume(Context context, String fragmentName)
/**
* quitFragmentpage, call this interface
* @param context
* @param fragmentName FragmentFull class name of the page (this.getClass().getCanonicalName())
*/
public static void onFragmentPause(Context context, String fragmentName)
Instructions for use: Because Android Add to Fragment There are four ways in total, and each different adding method requiresFragmentThe processing methods are also different. The following is aimed at Fragment The four ways to specify are specified in Fragment show in app The control methods are explained separately.
| fragmentUsage | Can it be monitored?Fragmentlife cycle | JiguangDynamically specify the display page interface calling method |
|---|---|---|
| Method one:add/show/hide | Unable to monitor life cycle | Fragment within onFragmentResume and onHiddenChaned callback call |
| Method two:ViewPager | Unable to monitor life cycle | Fragment within setUserVisibleHint callback call |
| Method three:replace | Can monitor the life cycle | Fragment life cycle callback within onResumeandonPause call |
| Method four:attach/detach | Can monitor the life cycle | Fragment life cycle callback within onResume and onPause call |
add/show/hideWay
1) in FragmentofonCreateView The dynamic control interface is called in the callback function and requires parameters to be passed in. @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { String classname = this.getClass().getCanonicalName(); JPushInterface.onFragmentResumed(MyApplication.gContext, classname); return inflater.inflate(R.layout.black_fragment, container, false); } 2) in Fragment of onHiddenChaned In the callback interface, call the dynamic control interface and pass in parameters as required. @Override public void onHiddenChanged(boolean hidden) { String classname = this.getClass().getCanonicalName(); if(!hidden){//contextpassapplication context JPushInterface.onFragmentResumed(MyApplication.gContext, classname); }else{//hide JPushInterface.onFragmentPaused(MyApplication.gContext, classname); } super.onHiddenChanged(hidden); }1) in FragmentofonCreateView The dynamic control interface is called in the callback function and requires parameters to be passed in. @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { String classname = this.getClass().getCanonicalName(); JPushInterface.onFragmentResumed(MyApplication.gContext, classname); return inflater.inflate(R.layout.black_fragment, container, false); } 2) in Fragment of onHiddenChaned In the callback interface, call the dynamic control interface and pass in parameters as required. @Override public void onHiddenChanged(boolean hidden) { String classname = this.getClass().getCanonicalName(); if(!hidden){//contextpassapplication context JPushInterface.onFragmentResumed(MyApplication.gContext, classname); }else{//hide JPushInterface.onFragmentPaused(MyApplication.gContext, classname); } super.onHiddenChanged(hidden); }This code block is shown in the floating windowViewPagerWay
1) in Fragment of setUserVisibleHint In the callback interface, call the dynamic control interface and pass in parameters as required. @Override public void setUserVisibleHint(boolean isVisibleToUser) { String classname = this.getClass().getCanonicalName(); if(isVisibleToUser){ //passapplication context JPushInterface.onFragmentResumed(MyApplication.gContext, classname); }else{//hide JPushInterface.onFragmentPause(MyApplication.gContext, classname); } super.setUserVisibleHint(isVisibleToUser); }1) in Fragment of setUserVisibleHint In the callback interface, call the dynamic control interface and pass in parameters as required. @Override public void setUserVisibleHint(boolean isVisibleToUser) { String classname = this.getClass().getCanonicalName(); if(isVisibleToUser){ //passapplication context JPushInterface.onFragmentResumed(MyApplication.gContext, classname); }else{//hide JPushInterface.onFragmentPause(MyApplication.gContext, classname); } super.setUserVisibleHint(isVisibleToUser); }This code block is shown in the floating windowreplace way or attach/detach Way
AddingFragmentIn the life cycle callback interface, call the dynamic page configuration interface. @Override public void onResume() {//passapplication context String classname = this.getClass().getCanonicalName(); JPushInterface.onFragmentResumed(MyApplication.gContext, classname); super.onResume(); } @Override public void onPause() { String classname = this.getClass().getCanonicalName(); JPushInterface.onFragmentPause(MyApplication.gContext, classname); super.onPause(); }AddingFragmentIn the life cycle callback interface, call the dynamic page configuration interface. @Override public void onResume() {//passapplication context String classname = this.getClass().getCanonicalName(); JPushInterface.onFragmentResumed(MyApplication.gContext, classname); super.onResume(); } @Override public void onPause() { String classname = this.getClass().getCanonicalName(); JPushInterface.onFragmentPause(MyApplication.gContext, classname); super.onPause(); }This code block is shown in the floating window
Report notification open event
Start version
- JPush Android SDK v1.6.1
Function description
- Used to report that the user's notification bar is opened, or to report events that the client needs to count, such as user-defined messages being displayed.
Interface definition
public static void reportNotificationOpened(Context context, String msgId)
Parameter description
- context: Applied ApplicationContext
- msgId: The unique ID corresponding to each message and notification pushed. ( msgId From sending messages and notifications Extra Field JPushInterface.EXTRA_MSG_ID, refer to Receive Push Messages Receiver )
code example
JPushInterface.reportNotificationOpened(context,bundle.getString(JPushInterface.EXTRA_MSG_ID));
Expand business related settings
Optional personal information settings
call this API to configure optional personal information collection
Supported versions
Recommended version:JPush Android SDK v5.3.1, need to cooperateJCore Android SDK v4.6.0and above
Interface definition
JPushInterface.setCollectControl(Context context,JPushCollectControl control);
Parameter definition
context
- application context
JPushCollectControl
- Collection control item configuration class
JPushCollectControl Control class
IMEICollection switch
public Build imei(boolean enable)
Method description
ConfigurationIMEIInformation collection switch, default istrue,false-Collection is not allowed
IMSICollection switch
public Build imsi(boolean enable)
Method description
ConfigurationIMSIInformation collection switch, default istrue,false-Collection is not allowed
MACCollection switch
public Build mac(boolean enable)
Method description
ConfigurationMACInformation collection switch, default istrue,false-Collection is not allowed
SSIDCollection switch
public Build ssid(boolean enable)
Method description
ConfigurationSSIDInformation collection switch, default istrue,false-Collection is not allowed
BSSIDCollection switch
public Build bssid(boolean enable)
Method description
ConfigurationBSSIDInformation collection switch, default istrue,false-Collection is not allowed
Base station information collection switch
public Build cell(boolean enable)
Method description
Configure the base station information collection switch, the default istrue,false-Collection is not allowed
WIFIList information collection switch
public Build wifi(boolean enable)
Method description
ConfigurationWIFIList information collection switch, default istrue,false-Collection is not allowed
完整示例:
public class MyApplication extends Application {
@Override
public void onCreate() {
JPushCollectControl.Builder builder=new JPushCollectControl.Builder();
builder.mac(false);
JPushInterface.setCollectControl(this,builder.build());
JPushInterface.init(this);
}
}
Extend business function settings
call this API To configure extended business functions
Supported versions
Recommended version:JPush Android SDK v5.3.0, need to cooperateJCore Android SDK v4.6.0and above
user segmentPush
JPushInterface.setSmartPushEnable(Context context,boolean isSmartPushEnable);
Parameter definition
context
- application context
isSmartPushEnable
- user segmentPush switch, default istrue,false-Representative closed
Geofence push
JPushInterface.setGeofenceEnable(Context context,boolean isGeoPushEnable);
Parameter definition
context
- application context
isGeoPushEnable
- Geofence push switch, default istrue,false-Representative closed
Notice
JPushInterface.setLbsEnable(Context context,boolean isGeoPushEnable) from5.4.0Version starts to be discarded
Application starts automatically
JCollectionAuth.enableAutoWakeup(Context context,boolean isAutoWakeupEnable);
Parameter definition
context
- application context
isAutoWakeupEnable
- Application auto-start switch, default istrue,false-Representative closed
link conditioner
JPushInterface.setLinkMergeEnable(Context context,boolean isLinkMergeEnable);
Parameter definition
context
- application context
isLinkMergeEnable
- Link regulator switch, default istrue,false-Representative closed
App active time statistics
JCollectionAuth.enableAppTerminate(Context context,boolean enable);
Parameter definition
context
- application context
enable
- Application active duration statistics switch, the default istrue,false-Representative closed
Notification switch API
Notification on status
Supported versions
Versions supported starting from:JPush Android SDK v3.5.0
Function description
- Check whether the notification switch of the current application is turned on
Interface definition
public static int isNotificationEnabled(Context context)
Parameter description
- context is applied ApplicationContext
- Return result: 1 means on, 0 means off, -1 means detection failed.
Jump to app notification settings page
Supported versions
Versions supported starting from:JPush Android SDK v3.5.0
Function description
- Jump to the application notification settings page of the mobile phone, and the notification switch can be turned on by the user.
Interface definition
public static void goToAppNotificationSettings(Context context)
Parameter description
- context is applied ApplicationContext
Trigger notification status check
Supported versions
Versions supported starting from:JPush Android SDK v5.9.0
Function description
- Actively trigger notification status check to detect the notification switch status of the current application and report any changes.
Interface definition
public static void triggerNotificationStateCheck(Context context)
Parameter description
- context is applied ApplicationContext
Instructions for use
- This method will actively check the notification switch status of the current application and report if there are any changes.
code example
// 触发通知状态检查,如果有变化上报
JPushInterface.triggerNotificationStateCheck(context);
Set whether to enable power saving mode
Supported versions
Versions supported starting from:JPush Android SDK v3.0.9
Function description
JPush SDK Turn power saving mode on and off. The default is off.
Implementation method
Interface definition
public static void setPowerSaveMode(Context context,boolean enable);
Parameter description
- context currently applied Activity context
- enable Do you need to turn it on or off?true To turn on,false to close
Whether to keep it after exiting the backgroundJiguanglong connection API
Supported versions
Versions supported starting from:JPush Android SDK v6.1.0 and JCore Android SDK v5.4.0 and above
Function description
Controls whether the application remains connected to the background when it enters the background.JiguangServer TCP Long connection.
- Default is to maintain a long connection (
true), consistent with historical default behavior. - Set to false: When exiting the background, the long connection will be disconnected, and the connection will be re-established after returning to the foreground. This can reduce the power consumption or network occupation caused by the long connection in the background in some scenarios (the actual effect is affected by system scheduling and manufacturer policies).
- This switch is only saved in the memory of the current process; it will be restored to default after the process ends or is cold started.
true. If your business needs a fixed strategy, please enterApplication/ Call the setting interface as early as possible before push initialization.
Set whether to maintain long connections in the background
Interface definition
public static void setKeepLongConnInBackground(Context context, boolean keep)
Parameter description
- context The context of the current application
- keep for
trueIndicates that the long connection will still be maintained after logging out; forfalseIndicates disconnection after exiting the background and reconnecting after returning to the foreground.
illustrate: JCore version lower than 540 When calling this interface, it is invalid and does not change the behavior.
Get whether to maintain a long connection in the background
Interface definition
public static boolean getKeepLongConnInBackground(Context context)
Parameter description
- context The context of the current application
Return value description
true: Currently, it is to maintain a long connection in the background; it has not been set after cold start.JCore When the version is insufficient or the reading process is abnormal, it istruefalse: It has been set to not maintain long connections in the background (requires JCore 540 and above and the settings have taken effect)
code example
JPushInterface.setKeepLongConnInBackground(context, false);
boolean keep = JPushInterface.getKeepLongConnInBackground(context);
Notification bar style customization API
Supported versions
Supported version: initially
Function description
In most cases, developers do not need to call the custom notification bar here API To customize the notification bar style, just use SDK The default one is fine.
If you want to:
- Change Notification Ringtone, vibration, appearance and disappearing behavior in
- Customize notification bar display style
- different Push notify,Notification different styles
Then please use this notification bar to customize API capabilities provided.
Tutorials and Code Examples
Please refer to the documentation:Custom notification bar style tutorial
Set the default notification bar style to build the class
public static void setDefaultPushNotificationBuilder(DefaultPushNotificationBuilder builder)
This method can be called when the user needs to customize the default notification bar style.
JPush SDK Provides 3 build classes for customizing notification bar styles:
- BasicPushNotificationBuilder
- Basic for customization Android Notification inside defaults / flags / icon and other basic styles (behavior)
- CustomPushNotificationBuilder
- inherit Basic Further allow developers to customize Notification Layout
- MultiActionsNotificationBuilder
- inherit DefaultPushNotificationBuilder Further allow developers to customize Notification Layout
If this method is not called for customization, thenJPush SDK The default notification bar style is:Android Standard notification bar prompt.
Set the notification bar style of a certain number to build a class
public static void setPushNotificationBuilder(Integer notificationBuilderId, BasicPushNotificationBuilder builder)
When developers need to specify different notification bar styles (behaviors) for different notifications, they need to call this method to set up multiple notification bar construction classes.
3.0.0 New version MultiActionsNotificationBuilder, that is, the notification bar construction class with buttons, which can be used api set up.
When setting, the developer maintains it himself notificationBuilderId This number is used when issuing notifications. builder_idAssign this number so Push SDK The notification bar construction class with the specified number set in the developer application will be called to customize the notification bar style.
Set the number of recent notifications to keep API
Supported versions
Versions supported starting from:JPush Android SDK v1.3.0
Function description
passJPush, when a lot of notifications are pushed to the client, if the user does not process them, many of them will remain there.
from JPush Android SDK v1.3.0 version start SDK Add this function to limit the number of retained notifications. The default is to keep the last 5 notifications.
Developers can call this API to be defined as different quantities.
Valid for notifications only. The so-called keeping the latest one means that if a new notification arrives, the oldest one in the previous list will be removed.
For example, set it to keep the last 5 notifications. Assume that there are already 5 items displayed in the notification bar. When the 6th item arrives, the 1st item will be removed.
Implementation method
Interface definition
public static void setLatestNotificationNumber(Context context, int maxNum)
Parameter description
- context applied ApplicationContext
- maxNum Maximum number of items displayed
Call instructions
This interface can be found in JPushInterface.init Called anywhere afterwards. Can be called multiple times.SDK Use the last value called.
code example
JPushInterface.setLatestNotificationNumber(context, 3);
CrashLog Collect and report
Supported versions
- JPush Android SDK v2.1.8 In and later versions, it is turned on by default, and additional stopCrashHandler interface.
Function description
SDK pass Thread.UncaughtExceptionHandler Capture the program crash log and report it in real time when the program crashes. If the real-time reporting fails, it will be sent to the server the next time the program starts. If you need the program crash log function, you can call this method.
closure CrashLog Report
Interface definition
public static void stopCrashHandler(Context context)
Parameter description
- Context applied Applicationcontext
turn on CrashLog Report
Interface definition
public static void initCrashHandler(Context context);
Parameter description
- Context applied Applicationcontext
Get push connection status
Supported versions
Versions supported starting from:JPush Android SDK v1.6.3
Function description
Developers can use this function to obtain the current Push The connection status of the service
When the connection status changes (connected, disconnected), a broadcast will be sent, and the developer can Receiver monitor cn.jpush.android.intent.CONNECTION Get the changed status, you can also pass API Actively obtain.
Implementation method
Function description
Get current connection status
Interface definition
public static boolean getConnectionState(Context context);
Parameter description
- context applied ApplicationContext
ACTION cn.jpush.android.intent.CONNECTION
intent parameter
JPushInterface.EXTRA_CONNECTION_CHANGE Push The value passed by the connection status change broadcast
boolean connected = bundle.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
Sample code
exist JPush Demo of MyReceiver onReceive Add the following code to the method:
else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
Log.e(TAG, "[MyReceiver]" + intent.getAction()+"connected:"+connected);
}
local notification API
Supported versions
Versions supported starting from:JPush Android SDK v1.6.4
Function description
passJPushof SDK, developers only need to simply call a few interfaces to send local notifications regularly in the application.
local notification API Does not depend on the network, can still be triggered without network conditions
Local notifications and network push notifications are independent of each other and are not subject to the upper limit of the number of recent notifications retained.
The timing time of local notification is calculated from the time of sending and is not affected by intermediate shutdown and other operations.
Add a local notification
Interface definition
public static void addLocalNotification(Context context, JPushLocalNotification notification)
Parameter description
- context is applied ApplicationContext
- notification Is a local notification object; recommended notificationId Set to a positive integer. If it is 0 or a negative number, the local notification cannot be cleared.
- Pay attention to Huawei classification, needpriorityandcategoryTo match, just setpriority,sdkwillpriorityandimportanceIn terms of conversion, the corresponding relationship is as follows:
- PRIORITY_MIN = -2 corresponds to IMPORTANCE_MIN = 1;
- PRIORITY_LOW = -1; corresponds to IMPORTANCE_LOW = 2;
- PRIORITY_DEFAULT = 0; corresponds to IMPORTANCE_DEFAULT = 3;
- PRIORITY_HIGH = 1; corresponds to IMPORTANCE_HIGH = 4;
- PRIORITY_MAX = 2; corresponds to IMPORTANCE_MAX = 5;
Call instructions
This interface can be found in JPushInterface.init Then call it anywhere
Remove specified local notification
Interface definition
public static void removeLocalNotification(Context context, long notificationId)
Parameter description
- context is applied ApplicationContext
- notificationId is the ID of the local notification to be removed, note notificationId Notifications that are 0 or negative cannot be removed
Call instructions
This interface can be found in JPushInterface.init Then call it anywhere
Remove all local notifications
Notice notificationId When it is 0 or a negative number, the notification cannot be removed.
Interface definition
public static void clearLocalNotifications(Context context)
Parameter description
- context is applied ApplicationContext
Call instructions
This interface can be found in JPushInterface.init Then call it anywhere
Local notification related settings
// 设置本地通知类别,5.2.0 版本开始支持
public void setCategory(String category)
// 设置本地通知优先级
public void setPriority(int priority)
// 设置本地通知样式,5.2.0 版本开始支持
public void setBuilderId(long)
// 设置本地通知的 title
public void setTitle(String paramString)
// 设置本地通知的 content
public void setContent(String paramString)
// 设置额外的数据信息 extras 为 json 字符串
public void setExtras(String extras)
// 设置本地通知的 ID
public void setNotificationId(long notificationId)
// 设置本地通知触发时间
public void setBroadcastTime(long broadCastTime)
public void setBroadcastTime(Date date)
public void setBroadcastTime(int year, int month, int day, int hour, int minute, int second)
Sample code
JPushLocalNotification ln = new JPushLocalNotification();
ln.setBuilderId(0);
ln.setContent("hhh");
ln.setTitle("ln");
ln.setNotificationId(11111111) ;
ln.setBroadcastTime(System.currentTimeMillis() + 1000 * 60 * 10);
//分类处理 5.2.0 版本开始支持
ln.setCategory(Notification.CATEGORY_ALARM);
ln.setPriority(Notification.PRIORITY_DEFAULT);
//PRIORITY与IMPORTANCE 相互转换关系
//PRIORITY_MIN = -2 对应 IMPORTANCE_MIN = 1;
//PRIORITY_LOW = -1; 对应 IMPORTANCE_LOW = 2;
//PRIORITY_DEFAULT = 0; 对应 IMPORTANCE_DEFAULT = 3;
//PRIORITY_HIGH = 1; 对应 IMPORTANCE_HIGH = 4;
// PRIORITY_MAX = 2; 对应 IMPORTANCE_MAX = 5;
//分类处理
Map<String , Object> map = new HashMap<String, Object>() ;
map.put("name", "jpush") ;
map.put("test", "111") ;
JSONObject json = new JSONObject(map) ;
ln.setExtras(json.toString()) ;
JPushInterface.addLocalNotification(getApplicationContext(), ln);
Geofencing API
Supported versions
Versions supported starting from:JPush Android SDK v3.1.8
Function description
JPush SDK Provides geofencing functionality, which triggers notifications or customized messages when a device enters or leaves the corresponding geographical area. Developers can use this function to SDK Provided geofencing functionality to set up.
Set geofence monitoring period
Function description
Set the geofence monitoring period, minimum 3 minutes, maximum 1 day. Defaults to 15 minutes when the distance to the geofence boundary is less than 1000 The meter cycle automatically adjusts to 3 minutes. After successful setting, the setting cycle will be used and will not be adjusted.
Interface definition
public static void setGeofenceInterval(Context context, long interval)
Parameter description
- context is applied ApplicationContext
- interval Monitoring period, unit is milliseconds.
Set the maximum number of geofences allowed to be saved
Function description
Set the maximum number of geofences allowed to be saved. After exceeding the maximum limit, if you continue to create geofences, the oldest geofences created will be deleted first. The default number is 10, the minimum allowed is 1, the maximum 100 indivual.
Interface definition
public static void setMaxGeofenceNumber(Context context, int maxNumber)
Parameter description
- context is applied ApplicationContext
- maxNumber Maximum number of geofences allowed to be saved
Remove geofence
Function description
Delete geofence with specified id
Interface definition
public static void deleteGeofence(Context context, String geofenceid)
Parameter description
- context is applied ApplicationContext
- geofenceid geofence id
corner mark API
Supported versions
Versions supported starting from:JPush Android SDK v3.3.6
Set subscript numbers
Function description
Set the corner mark number (currently only supports Huawei mobile phones)
If you need to call this interface, you also need to AndroidManifest.xml Configure Huawei-specified permissions in
<uses-permission android:name="com.huawei.android.launcher.permission.CHANGE_BADGE"/><uses-permission android:name="com.huawei.android.launcher.permission.CHANGE_BADGE"/>This code block is shown in the floating window
Interface definition
public static void setBadgeNumber(Context context, int num)
Parameter description
- context is applied ApplicationContext
- num New subscript number, if a negative number is passed in, it will be corrected to 0
Clear notification API
Supported versions
Versions supported starting from:JPush Android SDK v1.3.5
Function description
When push notifications are sent to the client, the JPush SDK Display the notification on the notification bar.
this API Provides functions to clear notifications, including: clear all JPush Displayed notifications (excluding non- JPush SDK Displayed); clear a specified notification.
Clear all notifications
Interface definition
public static void clearAllNotifications(Context context);
Parameter description
- Context context: Applied ApplicationContext
Clear notification
Interface definition
public static void clearNotificationById(Context context, int notificationId);
Parameter description
+ Context context: Applied ApplicationContext
+ int notificationId: Notification ID
此 notificationId 来源于 intent 参数 JPushInterface.EXTRA_NOTIFICATION_ID,可参考文档:接收推送消息 Receiver
Set allowed push time API
Supported versions
Starting version: Initial
Function description
By default users are allowed to push at any time. That is, anytime something is pushed, the client will receive it and display it.
Developers can call this API to set the time allowed for push.
If the message is not received within this time period,SDK The processing is: **Notifications pushed to will be thrown away. **
这是一个纯粹客户端的实现,所以与客户端时间是否准确、时区等这些,都没有关系。
而且该接口仅对通知有效,自定义消息不受影响。
Implementation method
Interface definition
public static void setPushTime(Context context, Set<Integer> weekDays, int startHour, int endHour)
Parameter description
- Context context applied ApplicationContext
- Set
days 0 means Sunday, 1 means Monday, and so on. (7-day system,Set in the collection int Range is 0 to 6) - set The value is null, you can receive notifications at any time,set of size A value of 0 means no notifications will be received at any time.
- int startHour The start time when push is allowed (24-hour clock:startHour ranges from 0 to 23)
- int endHour End time for allowed pushes (24-hour clock:endHour ranges from 0 to 23)
code example
Set<Integer> days = new HashSet<Integer>();
days.add(1);
days.add(2);
days.add(3);
days.add(4);
days.add(5);
JPushInterface.setPushTime(getApplicationContext(), days, 10, 23);
This code means that push can be made from Monday to Friday, from 10 am to 23 pm.
Set notification silent time API
Supported versions
Versions supported starting from:JPush Android SDK v1.4.0
Function description
By default, when a user receives a push notification, the client may vibrate, ring, etc. However, users hope to be in "do not disturb" mode when sleeping, having meetings, etc., which is also the concept of silent period.
Developers can call this API to set the silent period. If a message is received within this time period: there will be no ringtone or vibration.
Implementation method
Interface definition
public static void setSilenceTime(Context context, int startHour, int startMinute, int endHour, int endMinute)
Parameter description
- Context context applied ApplicationContext
- int startHour Start time of silent period - hour (24-hour clock, range: 0~23)
- int startMinute Start time of silent period - minutes (range: 0~59)
- int endHour End time of silent period - hour (24-hour clock, range: 0~23)
- int endMinute End time of silent period - minutes (range: 0~59)
code example
JPushInterface.setSilenceTime(getApplicationContext(), 22, 30, 8, 30);
This code indicates a silent period from 10:30pm to 8:30am the next morning.