Client SDK User Guide(AAR)更新时间: 2024-10-09 15:02:00

Mi Push Service Android Client SDK User Guide(AAR)

This document introduces the method for integrating the non-mainland China version Mi Push  Android client SDK. If you need to integrate the Chinese mainland version SDK, please refer to the Chinese mainland version Android client SDK user guide.

一、Prerequisites

You have enabled the push service and obtained the application's AppId, AppKey, and AppSecret.

二、Access Preparation

1. Download the Mi Push Android client SDK package

The non-mainland China version Mi Push Android client SDK starts from version 5.0.2 and provides AAR package access. The minimum supported Android SDK version is 19.

Download address: https://admin.xmpush.xiaomi.com/en/mipush/downpage

We recommend that you download the latest version.

2. If you have accessed Mi Push client SDK through the JAR package before, you need to completely delete the original JAR package access configuration. For details, please refer to "Mi Push Service Android Client SDK User Guide(JAR)".

三、Access Guidance

1、Adding dependencies

First, copy the AAR package of the Mi Push SDK, such as MiPush_SDK_Client_xxx.aar, to the project /libs/ directory, and then to the build.gradle of the project app module dependency:

android{ 
repositories {
flatDir {
dirs 'libs'
}
}
}
dependencies {
implementation (name: 'MiPush_SDK_Client_xxx', ext: 'aar')
}

2、Customize a BroadcastReceiver class to receive push messages

In order to receive messages, you need to customize a BroadcastReceiver that inherits from the PushMessageReceiver class for the app, and implement the onReceivePassThroughMessage, onNotificationMessageClicked, onNotificationMessageArrived, onCommandResult and onReceiveRegisterResult methods. Among whcih, onReceivePassThroughMessage is used to receive pass-through messages sent by the server, onNotificationMessageClicked is used to receive notification shade messages sent by the server (Triggered when the user taps the notification shade), and onNotificationMessageArrived is used to receive notification shade messages sent by the server (Triggered when the message arrives at the client, and can receive notification messages that the application does not display the notification when the application is in the foreground), onCommandResult is used to receive responses returned after the client sends a command message to the server, and onReceiveRegisterResult is used to receive responses returned after the client sends a register command message to the server.

Note that these methods run on the non-UI thread.

Example:

Customize BroadcastReceiver:

public class DemoMessageReceiver extends PushMessageReceiver { 

private String mRegId;

private long mResultCode = -1;

private String mReason;

private String mCommand;

private String mMessage;

private String mTopic;

private String mAlias;

private String mUserAccount;

private String mStartTime;

private String mEndTime;

@Override

public void onReceivePassThroughMessage(Context context, MiPushMessage message) {

mMessage = message.getContent();

if(!TextUtils.isEmpty(message.getTopic())) {

mTopic=message.getTopic();

} else if(!TextUtils.isEmpty(message.getAlias())) {

mAlias=message.getAlias();

} else if(!TextUtils.isEmpty(message.getUserAccount())) {

mUserAccount=message.getUserAccount();

}

}

@Override

public void onNotificationMessageClicked(Context context, MiPushMessage message) {

mMessage = message.getContent();

if(!TextUtils.isEmpty(message.getTopic())) {

mTopic=message.getTopic();

} else if(!TextUtils.isEmpty(message.getAlias())) {

mAlias=message.getAlias();

} else if(!TextUtils.isEmpty(message.getUserAccount())) {

mUserAccount=message.getUserAccount();

}

}

@Override

public void onNotificationMessageArrived(Context context, MiPushMessage message) {

mMessage = message.getContent();

if(!TextUtils.isEmpty(message.getTopic())) {

mTopic=message.getTopic();

} else if(!TextUtils.isEmpty(message.getAlias())) {

mAlias=message.getAlias();

} else if(!TextUtils.isEmpty(message.getUserAccount())) {

mUserAccount=message.getUserAccount();

}

}

@Override

public void onCommandResult(Context context, MiPushCommandMessage message) {

String command = message.getCommand();

List<String> arguments = message.getCommandArguments();

String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null);

String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null);

if (MiPushClient.COMMAND_REGISTER.equals(command)) {

if (message.getResultCode() == ErrorCode.SUCCESS) {

mRegId = cmdArg1;

String region = MiPushClient.getAppRegion(context);

}

} else if (MiPushClient.COMMAND_SET_ALIAS.equals(command)) {

if (message.getResultCode() == ErrorCode.SUCCESS) {

mAlias = cmdArg1;

}

} else if (MiPushClient.COMMAND_UNSET_ALIAS.equals(command)) {

if (message.getResultCode() == ErrorCode.SUCCESS) {

mAlias = cmdArg1;

}

} else if (MiPushClient.COMMAND_SUBSCRIBE_TOPIC.equals(command)) {

if (message.getResultCode() == ErrorCode.SUCCESS) {

mTopic = cmdArg1;

}

} else if (MiPushClient.COMMAND_UNSUBSCRIBE_TOPIC.equals(command)) {

if (message.getResultCode() == ErrorCode.SUCCESS) {

mTopic = cmdArg1;

}

} else if (MiPushClient.COMMAND_SET_ACCEPT_TIME.equals(command)) {

if (message.getResultCode() == ErrorCode.SUCCESS) {

mStartTime = cmdArg1;

mEndTime = cmdArg2;

}

}

}

@Override

public void onReceiveRegisterResult(Context context, MiPushCommandMessage message) {

String command = message.getCommand();

List<String> arguments = message.getCommandArguments();

String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null);

String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null);

if (MiPushClient.COMMAND_REGISTER.equals(command)) {

if (message.getResultCode() == ErrorCode.SUCCESS) {

mRegId = cmdArg1;

String region = MiPushClient.getAppRegion(context);

}

}

}

}

Note:Please make sure that the process where the custom BroadcastReceiver is located and the process that calls the registered push interface (MiPushClient.registerPush()) are the same process (We strongly recommend that both in the main process).

If your app uses obfuscation, you need to keep the custom BroadcastReceiver with the following code:

#Here com.xiaomi.mipushdemo.DemoMessageRreceiver is changed to the full class name defined in the app 
-keep class com.xiaomi.mipush.sdk.DemoMessageReceiver {*;}

3、Customized configuration (Optional)

In the standard AAR package configuration, the XMPushService, XMJobService and PingReceiver components run in the :pushservice process by default. If you want them to run in other processes, such as :appcustom, you can use the replace attribute of the tools namespace to achieve this:

First, declare the tools namespace in the root tag <manifest/> of the AndroidManifest.xml of your project's app module:

xmlns:tools="http://schemas.android.com/tools" 

Then, declare the modification process configuration for the XMPushService, XMJobService and PingReceiver components in the <application/>tag of the AndroidManifest.xml file of the app module of your project,:

<service 
android:name="com.xiaomi.push.service.XMJobService"
android:process=":appcustom"
tools:replace="android:process"/>
<service
android:name="com.xiaomi.push.service.XMPushService"
android:process=":appcustom"
tools:replace="android:process" />
<receiver
android:name="com.xiaomi.push.service.receivers.PingReceiver"
tools:replace="android:process"
android:process=":appcustom" />

Note:Please make sure that XMPushService, XMJobService, and PingReceiver components are running in the same process.

4、Register push service

First, set the computer area through the MiPushClient.setRegion interface. The optional computer areas are as follows:

public enum Region { 
Global,//Singapore
Europe,//Europe Frankfurt, Germany
Russia, // Moscow, Russia
India // Mumbai, India

Then call the MiPushClient.registerPush interface to register the Mi Push service.

Note:Be sure to call MiPushClient.setRegion to set the computer area before calling MiPushClient.registerPush, otherwise an IllegalArgumentException error will occur.

After successful registration, you can receive the registration result in the custom onCommandResult and onReceiveRegisterResult, where the regId is the unique identifier of the current app on the current device.

When you get the regId, please use the MiPushClient.getAppRegion(Context context) interface to get the service room location that the current device is connected to. When you send push messages to the device, you need to use the service room location;

(Note that on MIUI devices, the location of service room connected to the device obtained through the getAppRegion interface of MiPushClient may be different from the one you set through the setRegion interface. In this case, be sure to use the service room location obtained through the getAppRegion interface to send push messages. Otherwise the message cannot be delivered)

Return value of getappregion interface:

China;//If the application runs on a MIUI device in mainland China, the connected computer room area is China

Singapore;//Global

Europe;//Europe

Russia;//Russia

India;//India

To improve the push registration rate, you can initialize push in the application's onCreate.You can also initialize push elsewhere as needed. The sample code is as follows:

public class DemoApplication extends Application { 

public static final String APP_ID = "your appid";
public static final String APP_KEY = "your appkey";
public static final String TAG = "your packagename";

@Override
public void onCreate() {
...
//Initialize push service
if(isMainProcess()) {
//You must call setRegion to set the region before calling registerPush
MiPushClient.setRegion(Region.Global);
MiPushClient.registerPush(this, APP_ID, APP_KEY);
}
...
}

private boolean isMainProcess() {
ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
List<RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
String mainProcessName = getApplicationInfo().processName;
int myPid = Process.myPid();
for (RunningAppProcessInfo info : processInfos) {
if (info.pid == myPid && mainProcessName.equals(info.processName)) {
return true;
}
}
return false;
}
}

Note:Because the push service XMPushService is set to run in another process in AndroidManifest.xml, this application will be instantiated twice, so we need to initialize the main process of the application.

5、Set alias, userAccount, and subscription topic

After the registration is successful and the regId is received, you can call MiPushClient.setAlias to set the alias, MiPushClient.setUserAccount to set the userAccount, and MiPushClient.subscribe to subscribe to the topic.

The alias can be understood as the regId alias. Developers can set alias as the account of their own application account system, or the device ID.Then, when using Server SDK to send a message, you can directly specify to send to a specific alias instead of regId to avoid storing regId. 

The developer can set the same userAccount on different devices.Then use the Server SDK to send a message to the userAccount; at this point, all devices with the userAccount set can receive the message. 

The topics are used to send broadcast messages.The same app on different phones can subscribe to the same topic.By sending the topic message API, you can send messages to all clients that have subscribed to the topic at one time.For example, if you have a news app, you can customize topics such as finance, sports, technology, etc.; for users that often read about finance, you can help users subscribe to topics related to “finance”, and when an important piece of financial news comes out, you can directly push that piece of news to all users that have subscribed to that topic.

四、API Specifications

For developers, using client SDK can do 2 things: one is the client can send various requests to the server, and the other is the server can send messages to the client and respond to it. They are the corresponding access class MiPushClient and implementation class PushMesssageReceiver respectively.

1、MiPushClient access class

The MiPushClient is the access class of MiPush Client SDK on the Android platform. This class offers a series of static methods, it's unnecessary to be instantiated.

1.1. MiPushClient

public abstract class
extends Object
java.lang.Object
↳ com.xiaomi.mipush.sdk.MiPushClient

1.2 Member list

Table 4-1. MiPushClient Member List

APIFunctionScenario
registerPush(Context context, String appID, String appToken)Register for Mi Push Service. View details in section 3.4.1.When developers decide whether or not to register for push.
unregisterPush(Context context)Unregister from Mi Push Service. View details in section 3.4.2.When developers decide whether or not to turn off push.
enablePush(final Context context)Enable Mi Push service. View details in section 3.4.27.
After calling the interfaces of disablePush and enablePush, no new RegID will be generated, and the RegID will be the same as the original one.
When developers decide whether or not to turn on push.
disablePush(final Context context)Disable Mi Push service. View details in section 3.4.28.
After calling the interfaces of disablePush and enablePush, no new RegID will be generated, and the RegID will be the same as the original one.
When developers decide whether or not to disable push.
setAlias(Context context, String alias, String category)Set an alias for a specified user. View details in section 3.4.3.When developers decide to push through alias.
unsetAlias(Context context, String alias, String category)Cancel the alias of a specified user. View details in section 3.4.4.When developers need to cancel a user alias.
setUserAccount(final Context context, final String userAccount, String category)Set a userAccount for a specified user. View details in section 3.4.5.When developers decide to push through userAccount.
unsetUserAccount(final Context context, final String userAccount, String category)Cancel the userAccount of a specified user. View details in section 3.4.6.When developers need to cancel a user's userAccount.
subscribe(Context context, String topic, String category)Set a subscription topic for a user. View details in section 3.4.7.When developers send group messages to groups divided by subscriptions, according to the user's subscriptions.
unsubscribe(Context context, String topic, String category)Unsubscribe a user from a topic. View details in section 3.4.8.When a user unsubscribes from a topic.
pausePush(Context context, String category)Pause receiving messages pushed by Mi Push service. View details in section 3.4.10.Before an app resumes the Mi Push service, it won't receive any push messages.
resumePush(Context context, String category)Resume receiving messages pushed by the Mi Push service. At this point, the server will resend the push messages that were suspended during the paused period. View details in section 3.4.11.Resume receiving Mi Push service push messages.
setAcceptTime(Context context, int startHour, int startMin, int endHour, int endMin, String category)Set a time period to accept Mi Push messages, messages pushed beyond the period will be cached at server side, when the appropriate time comes the cached messages will be pushed to the app. View details in section 3.4.9.Users can control at what time they will receive push messages.
getAllAlias(Context context)By using the method, a list of aliases set by the client will be returned (if the client hasn't set any aliases, a blank list will be returned). View details in section 3.4.12.When developers need to check the aliases set.
getAllTopic(Context context)By using the method, a list of topics the client has subscribed to will be returned (if the client hasn't subscribed to any topics, a blank list will be returned). View details in section 3.4.13.When developers need to check all topics subscribed to.
getAllUserAccount(final Context context)Get all accounts set by the client. View details in section 3.4.14.When developers need to check all accounts subscribed to.
reportMessageClicked(Context context, String msgid)Report clicked messages. View details in section 3.4.15.When developers check the CTR of messages.
clearNotification(Context context, int notifyId)Clear a pop-up notification with specified notifyId of Mi Push. View details in section 3.4.16.When clearing a pop-up notification with specified notifyId of Mi Push.
clearNotification(Context context)Clear all Mi Push pop-up notifications. View details in section 3.4.17.When clearing all Mi Push pop-up notifications.
setLocalNotificationType(final Context context, int notifyType)Client sets the reminder type of the notification message. Note: Even the server has specified the message reminder type, client can override the policy. View details in section 3.4.18.When the client sets the reminder type of the notification message.
clearLocalNotificationType(final Context context)Clear the notification message reminder type set by the client. View details in section 3.4.19.Clear the notification message reminder type set by the client.
getRegId(Context context)Get the client RegID.View details in section 3.4.20.Get the client RegID.

2、ErrorCodes types

ErrorCode is the error type returned after failing to access push.

2.1. ErrorCode

public abstract class
extends Object
java.lang.Object
↳ com.xiaomi.mipush.sdk.ErrorCode

2.2 Static variable

Table 4-2. ErrorCode Static Variable

Static VariableMeaning
SUCCESSMeans the push service has been accessed
ERROR_SERVICE_UNAVAILABLEIndicates a push couldn't be connected due to network error.
ERROR_INTERNAL_ERRORError with the internal status of the push. When coming across this error message, contact the developer.
ERROR_AUTHERICATION_ERRORA push connection couldn't be authenticated.
ERROR_INVALID_PAYLOADThe format of the message sent from the client to the push channel is invalid.

3、Broadcast message receiver 

PushMesssageReceiver

PushMessageReceiver is an abstract BroadcasRreceiver class, 6 methods are declared in it: onReceivePassThroughMessage, onNotificationMessageClicked, onNotificationMessageArrived, onCommandResult, onReceiveRegisterResult, and onRequirePermissions.  It has 2 uses:

  1. To get messages pushed by the server;
  2. To get returned results of calling the MiPushClient method.

3.1 PushMesssageReceiver

public abstract class
extends Object
java.lang.Object
↳ com.xiaomi.mipush.sdk.PushMesssageReceiver

3.2 Member list

Table 4-3. PushMesssageReceiver member list

APIFunction
onReceivePassThroughMessage(Context context, MiPushMessage message)Receives the transparent message pushed by the server, the message is encapsulated in the MiPushMessage class. View details in section 3.4.21.
onNotificationMessageClicked(Context context, MiPushMessage message)Receives notification message pushed by the server, triggered after the user clicks, the message is encapsulated in the MiPushMessage class. View details in section 3.4.22.
onNotificationMessageArrived(Context context, MiPushMessage message)Receives the notification message pushed by the server, triggered when the message arrives at the client, can also receive notification messages of that don't pop up when the app is in the foreground. The message is encapsulated in the MiPushMessage class. On MIUI, the message can only be received through this method if the app is running. View details in section 3.4.23.
onCommandResult(Context context, MiPushCommandMessage message)Gets the results after sending commands to the server, the results are encapsulated in the MiPushCommandMessage class. View details in section 3.4.24.
onReceiveRegisterResult(Context context, MiPushCommandMessage message)Gets the results after sending registration commands to the server, the results are encapsulated in the MiPushCommandMessage class. View details in section 3.4.25.
onRequirePermissions(Context context, String[] permissions)This interface will be called back when the required permissions are not obtained. View details in section 3.4.26.

4、Detailed instructions for the API

4.1. public static void registerPush(Context context, String appID, String appKey)

Used to register to the Mi Push service, it is recommended to call it when the app launches.

Table 4-4. RegisterPush Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.
appIDGenerated from the developer website, it is the unique app identifier issued from the Mi Push service.
appKeyGenerated from the developer website, it corresponds to the appID, used to authenticate whether or not the appID is legal.

4.2. public static void unregisterPush(Context context)

It is used to disable the Mi Push service when the user no longer wishes to use the Mi Push service. After calling this method, the app won't be able to receive any data from Mi Push service until the registerPush is called again. Note: After calling unregisterPush, the server won't send any messages to the app.

Table 4-5. UnregisterPush Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.

4.3. public static void setAlias(Context context, String alias, String category)

Developers can set an alias for a specified user and then push messages to this alias, the effect is the same as pushing a message to a RegID.  Note: Multiple aliases can be set for 1 RegID, if the alias you are setting up already exists, it will cover up the former one.

Table 4-6. SetAlias Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.
aliasSet an alias for a specified user.
categoryExtended parameter, temporarily has no use, fill in as null.

4.4. public static void unsetAlias(Context context, String alias, String category)

Developers can cancel a certain alias of a specified user, the server then won't push messages to this alias.

Table 4-7. UnsetAlias Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.
aliasCancel an alias for a specified user.
categoryExtended parameter, temporarily has no use, fill in as null.

4.5. public static void setUserAccount(final Context context, final String userAccount, String category)

Developers can set a userAccount for a specified user.

Table 4-8. SetUserAccount Function Parameters List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.
userAccountSet a userAccount for a specified user.
categoryExtended parameter, temporarily has no use, fill in as null.

4.6. public static void unsetUserAccount(final Context context, final String userAccount, String category)

Developers can cancel a certain userAccount of a specified user, the server then won't push messages to this userAccount.

Table 4-9. UnsetUserAccount Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.
userAccountCancel a userAccount for a specified user
categoryExtended parameter, temporarily has no use, fill in as null.

4.7. public static void subscribe(Context context, String topic, String category)

Set a subscription topic for a user; developers can send message to a group of users according to different topics the user has subscribed to.

Table 4-10. Subscribe Function Parameters List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.
topicThe topic a certain user has subscribed to.
categoryExtended parameter, temporarily has no use, fill in as null.

4.8. public static void unsubscribe(Context context, String topic, String category)

Unsubscribe from a topic for a certain user.

Table 4-11. Unsubscribe Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.
topicThe topic a certain user unsubscribed from.
categoryExtended parameter, temporarily has no use, fill in as null.

4.9. public static void setAcceptTime(Context context, int startHour, int startMin, int endHour, int endMin, String category)

Set the time period to receive Mi Push service's pushes, messages that are not pushed at that time will be cached, and will be pushed again at an appropriate time.  24-hour date-time format is used here. If the start time is earlier than the end time, the time period will fall within one day; otherwise, this time period will cross over 00:00 of the day.  Note: Using aliases and topics related to a RegID will also be limited.  If the time period is set as 0:00-0:00, the push service will be paused; you can also do this by directly calling the pausePush method, the effect will the same. If the time period is set as 0:00-23:59, the push service will be resumed, i.e., messages can be received all day; you can also do this by directly calling the resumePush method, the effect will the same.

Table 4-12. SetAcceptTime Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.
startHourThe start time (hour) in the time period when receiving messages.
startMinThe start time (minute) in the time period when receiving messages.
endHourThe end time (hour) in the time period when receiving messages.
endMinThe end time (minute) in the time period when receiving messages.
categoryExtended parameter, temporarily has no use, fill in as null.

4.10. public static void pausePush(Context context, String category)

Used to temporarily pause receiving Mi Push service messages. Before the app resumes the Mi Push service, it won't receive any push messages. Note: Here messages pushed through aliases and topics related to the RegID will also be suspended.

Table 4-13. PausePush Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.
categoryExtended parameter, temporarily has no use, fill in as null.

4.11. public static void resumePush(Context context, String category)

Resume receiving Mi Push service push messages. Note: Here messages pushed through the aliases and topics related to the RegID will also be resumed; at this time the server will resend all the push messages paused before.

Table 4-14. ResumePush Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.
categoryExtended parameter, temporarily has no use, fill in as null.

4.12. public static List<String> getAllAlias(final Context context)

Get all aliases set by the client.

Table 4-15. GetAllAlias Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.

4.13. public static List<String> getAllTopic(final Context context)

Get all the topics a client is subscribed to.

Table 4-16. GetAllTopic Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.

4.14. public static List<String> getAllUserAccount(final Context context)

Get all accounts set by the client.

Table 4-17. GetAllUserAccount Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.

4.15. public static void reportMessageClicked(Context context, String msgid)

Report clicked messages.

Table 4-18. ReportMessageClicked Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.
msgidThe message ID returned after calling server API to push messages.

4.16. public static void clearNotification(Context context, int notifyId)

Clear a pop-up notification with specified notifyId of Mi Push.

Table 4-19. ClearNotification Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.
notifyIdCall the server API to set notifyId for a notification.

4.17. public static void clearNotification(Context context)

Clear all Mi Push pop-up notifications.

Table 4-20. ClearNotification Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.

4.18. public static void setLocalNotificationType(final Context context, int notifyType)

The notification message reminder type the client sets.  Note: Client settings will override even if the server side specifies the message reminder type.

Table 4-21. SetLocalNotificationType Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.
notifyTypeThe notification message reminder type.

4.19. public static void clearLocalNotificationType(final Context context)

Clear the notification message reminder type set by the client.

Table 4-22. ClearLocalNotificationType Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.

 4.20. public static String getRegId(Context context)

Get the client RegID.

Table 4-23. GetRegId Function Parameters List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.

4.21. public void onReceivePassThroughMessage(Context context, MiPushMessage message)

Receive transparent messages pushed from the server.

Table 4-24. OnReceivePassThroughMessage Function Parameter List

ParameterDescription
messageThe message pushed by the server is encapsulated in the MiPushMessage's object, information such as messageType, messageID, content, alias, topic, passThrough, isNotified, notifyType, description, title, extra and so on can be obtained from such object.
messageType indicates the message type, there are 3 types: MESSAGE_TYPE_REG, MESSAGE_TYPE_ALIAS, MESSAGE_TYPE_TOPIC. They are the static variables of MiPushMessage.
If the server has pushed a message to the alias, then the alias is not null.
If the server has pushed a message to a topic, then the topic is not null.
passThrough indicates the type of message the server side pushed.  If the value of the passThrough is 1, then it is a transparent message; if the value is 0, then it is a notification shade message.
isNotified expresses whether or not a message has been transferred to the app through the notification shade. If it is true, it means the message has been displayed on the notification shade; if it is false, it means the message was directly transferred to the app, and did not pop up any notification.
messageID is the message's ID.
content is the message's content.
notifyType is the message reminder type, such as vibration, ringtone and LED light.
description is the message's description.
title is the message's title.
extra is a map type, it includes some additional information, like the URI of the customized notification shade ringtone, click behavior on the notification shade, etc.

4.22. public void onNotificationMessageClicked(Context context, MiPushMessage message)

Receive notification messages sent by the server (triggered when the user clicks the notification).

The parameter description is the same as that for onReceivePassThroughMessage. View details in section 3.4.21.

4.23. public void onNotificationMessageArrived(Context context, MiPushMessage message)

Receive notification messages sent by the server (triggered when the message arrives to the client, and can receive notifications that don’t pop up when the app is in the foreground).

The parameter description is the same as that for onReceivePassThroughMessage. View details in section 3.4.21.

4.24. public void onCommandResult(Context context, MiPushCommandMessage message)

The results returned from the server after the client has given commands to it, such as send registration information, set alias, cancel registered alias, subscribe to a topic, unsubscribe from a topic, etc.

Table 4-25. OnCommandResult Function Parameters List

ParameterDescription
messageThe commands returned by the server are encapsulated in the MiPushCommandMessage object, information such as command, commandArguments, resultCode, reason, and so on can be obtained from such object.
Command indicates the command type.
Call MiPushClient.registerPush(), return MiPushClient.COMMAND_REGISTER
CallMiPushClient.setAlias(), return MiPushClient.COMMAND_SET_ALIAS
Call MiPushClient.unsetAlias(), return MiPushClient.COMMAND_UNSET_ALIAS
CallMiPushClient.subscribe(), return MiPushClient.COMMAND_SUBSCRIBE_TOPIC
Call MiPushClient.unsubscribe(), return MiPushClient.COMMAND_UNSUBSCIRBE_TOPIC
Call MiPushClient.setAcceptTime(), return MiPushClient.COMMAND_SET_ACCEPT_TIME
Call MiPushClient.pausePush(), return MiPushClient.COMMAND_SET_TARGETPT_TIME
Call MiPushClient.resumePush(), return MiPushClient.COMMAND_SET_ACCEPT_TIME
commandArguments indicates the command parameter. For example, when you register an app, the app will return the RegID, the unique identifier of the Mi Push service corresponding to the app's initialization this time. The alias will return the alias content, subscribing to and unsubscribing from a topic will return a topic, and calling setAcceptTime will return the time period.
resultCode indicates the result of calling the command. If it is called successfully, the ErrorCode.Sussess, i.e. 0 will be returned; otherwise an error type value will be returned.
reason indicates the reason for why a command couldn't be called. If it couldn't be called, it will return with the reason, otherwise it will return as null.

4.25.  public void onReceiveRegisterResult(Context context, MiPushCommandMessage message)

Gets the results after sending commands to the server.

The parameter description is the same as that for onCommandResult. View details in section 3.4.2.

4.26.  public void onRequirePermissions(Context context, String[] permissions)

This interface will be called back when the required permissions are not obtained.

Table 3-26. OnRequirePermissionspermissions Function Parameter List

ParameterDescription
permissionsReturn permission sets not obtained.

4.27.  public static void enablePush(final Context context) 

Enable Mi Push service.

After calling the interfaces of disablePush and enablePush, no new RegID will generate, and the RegID will be the same as the original one.

Table 4-27. EnablePush Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.

4.28.  public static void disablePush(final Context context) 

Disable Mi Push service.

After calling the interfaces of disablePush and enablePush, no new RegID will generate, and the RegID will be the same as the original one.

Table 4-28. DisablePush Function Parameter List

ParameterDescription
contextThe context of the app on the Android platform, we recommend you import the application context of current app.

五、Special Topics

1、Customize the notification icon

Currently the display rules for notification icons are as follows:

  • If there are drawable files named mipush_notification and mipush_small_notification in the app, then use the mipush_notification drawable as the notification's large icon, and the mipush_small_notification drawable as the notification's small icon.
  • If there is only one drawable file in the app, then use that drawable as the notification's icon.
  • If these 2 drawable files don't exist in the app, then use the app icon as the notification's icon. On MIUI, the notification shade message icon will use the app icon which can't be customized.

2、Processing messages

Message types: Transparent messages and notification messages. When server sends messages, refer to the server file: Guide for Mi Push Server Side SDK (Java)

2.1 Processing transparent messages

After the transparent message reaches the client, the MiPushMessage object used to encapsulate the message will be directly sent to the client through the method onReceivePassThroughMessage which inherits from class PushMessageReceiver. After the client receives a transparent message, it can customize some operations from its own defined format of transparent message.

2.2 Processing notification messages

There are custom notification messages and predefined notification messages.  If the server calls the extra(String key, String value) method of the Message.Builder class to set the Constants.EXTRA_PARAM_NOTIFY_EFFECT value, then it is a predefined notification message; otherwise it is a custom notification message (for specific details, refer to the server file Guide for Mi Push Server Side SDK (Java)). If you're pushing a message on the Mi Dev Platform, you must specify the notification message type by “Follow-up actions”. A notification will pop up on the notification shade after the message reaches the client, at this point the message has already been sent to the onNotificationMessageArrived method of the PushMessageReceiver sub-class, but the message hasn’t been sent to the client through the onNotificationMessageClicked method of the PushMessageReceiver inheritance class.When the user clicks the customized notification message, the message will be sent to the method onNotificationMessageClicked. 

Note: When the user clicks the predefined notification message, the message won't be sent to the method onNotificationMessageClicked. 

The client defines 4 kinds of different notification click behaviors:

1. Processing custom notification messages

The processing server of the custom notification message hasn’t set a Constants.EXTRA_PARAM_NOTIFY_EFFECT value indicates it is a customized notification message. After the client receives the message, it can customize some operations.  For example, if you want to launch an Activity by sending message, you need to add FLAG_ACTIVITY_NEW_TASK to the Intent.

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Codes for the transparent messages and customized notification messages are as follows:

public void onReceivePassThroughMessage(Context context, MiPushMessage message)
{
mMessage = message.getContent();
if(!TextUtils.isEmpty(message.getTopic())) {
mTopic=message.getTopic();
}
else if(!TextUtils.isEmpty(message.getAlias())) {
mAlias=message.getAlias();
}
}

public void onNotificationMessageClicked(Context context, MiPushMessage message)
{
mMessage = message.getContent();
if(!TextUtils.isEmpty(message.getTopic())) {
mTopic=message.getTopic();
}
else if(!TextUtils.isEmpty(message.getAlias())) {
mAlias=message.getAlias();
}
}

public void onNotificationMessageArrived(Context context, MiPushMessage message)
{
mMessage = message.getContent();
if(!TextUtils.isEmpty(message.getTopic())) {
mTopic=message.getTopic();
}
else if(!TextUtils.isEmpty(message.getAlias())) {
mAlias=message.getAlias();
}
}

2. Open the Launcher Activity server corresponding to current app

You need call the extra(String key, String value) method of the Message.Builder class to set the key as Constants.EXTRA_PARAM_NOTIFY_EFFECT, and the value as Constants.NOTIFY_LAUNCHER_ACTIVITY. View details in the server file: Guide for Mi Push Server Side SDK (Java).The MiPushMessage object used to encapsulated the message is sent through the Intent, the client can then call the getSerializableExtra(PushMessageHelper.KEY_MESSAGE) method of the Intent in the corresponding Activity to obtain the MiPushMessage message object.

3. Open any Activity server within current app

You need call the extra(String key, String value) method of the Message.Builder class to set the key as Constants.EXTRA_PARAM_NOTIFY_EFFECT, and the value as Constants.NOTIFY_ACTIVITY. View details in the server file: Guide for Mi Push Server Side SDK (Java).The MiPushMessage object used to encapsulated the message is sent through the Intent, the client can then call the getSerializableExtra(PushMessageHelper.KEY_MESSAGE) method of the Intent in the corresponding Activity to obtain the MiPushMessage message object.

4. Open the website

You need call the extra(String key, String value) method of the Message.Builder class to set the key as Constants.EXTRA_PARAM_NOTIFY_EFFECT and the value as Constants.NOTIFY_WEB.View details in the server file: Guide for Mi Push Server Side SDK (Java).