Mi Push Service Android Client SDK User Guide(JAR)
一、ntroduction
Android client SDK is the developer toolkit provided for Android developers to access Mi Push service. The third party app only needs to add a small amount of codes to adapt to the Mi Push service.
1、Preparation
1.1. Sign in to Mi Dev Platform, register the app and apply for the AppID, AppKey as well as AppSecret.
Before using the Mi Push service, developers must first go to Mi Dev Platform (http://global.developer.mi.com/) to register the app and apply for the AppID, AppKey and AppSecret (View details in Mi Push Service Activation Guide). The AppID and AppKey represent the client's identity, used when the client SDK initializes; the AppSecret is authenticated for sending message at server side.
1.2. Download the compressed package of Android client SDK
Address: https://admin.xmpush.xiaomi.com/en/mipush/downpage/
The client SDK and Android demo are included in the compressed package.
Notice:
Due to the "notification trampoline" restrictions of Android 12, for apps in which targetSdkVersion ≧ 31, we recommend updating the SDK version to 4.8.6 or above. Otherwise, it won't switch to the target page normally after you tap a notification.
2、SDK instructions
The Android SDK is provided in a JAR library. For the main function interfaces of the Mi Push service client SDK, please refer to the section "3. API Specifications".
After the client has been registered successfully, a RegID will be received from the server, then developers can receive push messages by subscribing to topics and setting aliases.
Mi Push currently supports two kinds of messages: the transparent messages and notification messages.
- After a transparent message reaches a phone, the SDK will send the message to the method onReceivePassThroughMessage of the PushMessageReceiver subclass declared in the AndroidManifest by the system broadcast.
- For a notification message, the SDK will display a pop-up notification according to the information set in the message.
- If the notification message arrives when the app is running, it will go to the onNotificationMessageArrived method of the PushMessageReceiver subclass.
- For the customized notification message (refers to 4.2.2 Processing notification messages), after the user clicks on it, it will be sent to the onNotificationMessageClicked method of your PushMessageReceiver subclass.
二、SDK Access Guide
Here we introduce how to configure and use Mi Push, you can also refer to the demo in the SDK.
1、Configure AndroidManifest.xml file
The earliest Android version that Mi Push SDK supports is 2.3.
Permissions required by Mi Push are as follows (should be configured in AndroidManifest.xml):
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<permission android:name="Your app package name
.permission.MIPUSH_RECEIVE" android:protectionLevel="signature" />
<uses-permission android:name="Your app package name
.permission.MIPUSH_RECEIVE" />
Note: Please use your app package name as the prefix, in order to avoid conflicts between permission.MIPUSH_RECEIVE permission statement and other apps' statements.
If targetSdkVersion ≧ 31 is applied, and the accessed version of Mi Push Service Android Client SDK is 4.8.6 or above, the following configuration is required:
<activity
android:name="com.xiaomi.mipush.sdk.NotificationClickedActivity"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:launchMode="singleInstance"
android:exported="true"
android:enabled="true">
</activity>
Mi Push Service must configure service and receiver in AndroidManifest.xml:
<service
android:name="com.xiaomi.push.service.XMPushService"
android:enabled="true"
android:process=":pushservice" />
<!--Note: This service must be added to the version 3.0.1 or later (including version 3.0.1)-->
<service
android:name="com.xiaomi.push.service.XMJobService"
android:enabled="true"
android:exported="false"
android:permission="android.permission.BIND_JOB_SERVICE"
android:process=":pushservice" />
<service
android:name="com.xiaomi.mipush.sdk.PushMessageHandler"
android:enabled="true"
android:exported="true" />
<!--Note: This service must be added to version 2.2.5 or later (including version 2.2.5)-->
<service
android:name="com.xiaomi.mipush.sdk.MessageHandleService"
android:enabled="true" />
<receiver
android:name="com.xiaomi.push.service.receivers.PingReceiver"
android:exported="false"
android:process=":pushservice">
<intent-filter>
<action android:name="com.xiaomi.push.PING_TIMER" />
</intent-filter>
</receiver>
Note:
- Here the XMPushService, PingReceiver and XMJobService have been declared in the pushservice process, you can also declare them in other processes; to avoid burdening the main process, do not declare them in the main process;
- PushMessageHandler and MessageHandleService should be declared in the main process, and kept in the same process as the calling of MiPushClient.registerPush initializing push service.
2、Implement a BroadcastReceiver class
In order to receive messages, you must implement a BroadcastReceiver inherited from PushMessageReceiver and reload the method you need to monitor. Except onNotificationMessageClicked method, these methods will be implemented only when your app is running.
- Receive registration results whether it's successful or failed: onReceiveRegisterResult()
- Receive the Command result, such as settings of alias, topic, account, etc.: onCommandResult()
- When received transparent messages: onReceivePassThroughMessage()
- When received notification messages, callback: onNotificationMessageArrived()
- When the customized notification message is clicked, callback: onNotificationMessageClicked(). The UI (User Interface) of your app needs to be called in this method.
- The result code is defined by: com.xiaomi.mipush.sdk.ErrorCode. Among the codes, ErrorCode.SUCCESS means messages received successfully.
Note: The method described above runs in non-main thread.
Here is an example for you:
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;
//Process transparent messages
@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();
}
}
//Process the clicks of customized notification messages
@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();
}
}
//Notification messages reach the device
@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();
}
}
//command result processing
@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;
}
} 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;
}
}
}
//Receive registration result
@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;
}
}
}
}
Declare the customized BroadcastReceiver in AndroidManifest.xml file.
<!--Change xxx.DemoMessageRreceiver to the full class name defined in your app-->
<receiver android:name="xxx.DemoMessageReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.xiaomi.mipush.RECEIVE_MESSAGE" />
</intent-filter>
<intent-filter>
<action android:name="com.xiaomi.mipush.MESSAGE_ARRIVED" />
</intent-filter>
<intent-filter>
<action android:name="com.xiaomi.mipush.ERROR" />
</intent-filter>
</receiver>
Note:
- BroadcastReceiver must be stated in AndroidManifest.xml, otherwise the push messages won't be received or being displayed on the notification shade;
- android:exported must be declared as true, otherwise it will affect the process of message receiving and clicks.
3、Obfuscate Proguard configuration
Add the following data to the configuration file:
#Change xxx.DemoMessageRreceiver to the full class name defined in your app
-keep class xxx.DemoMessageReceiver {*;}
#SDK has been obfuscated and compressed to avoid class not found error due to re-obfuscation.
-keep class com.xiaomi.**
#If the compiling Android version you are using is 23, you can prevent getting a false warning which makes it impossible to compile.
-dontwarn com.xiaomi.push.**
-keep class com.xiaomi.mipush.sdk.MiPushMessage {*;}-keep class com.xiaomi.mipush.sdk.MiPushCommandMessage {*;}
-keep class com.xiaomi.mipush.sdk.PushMessageReceiver {*;}
-keep class com.xiaomi.mipush.sdk.MessageHandleService {*;}
-keep class com.xiaomi.push.service.XMJobService {*;}
-keep class com.xiaomi.push.service.XMPushService {*;}
-keep class com.xiaomi.mipush.sdk.PushMessageHandler {*;}
-keep class com.xiaomi.push.service.receivers.NetworkStatusReceiver {*;}
-keep class com.xiaomi.push.service.receivers.PingReceiver {*;}
-keep class com.xiaomi.mipush.sdk.NotificationClickedActivity {*;}
4、Register for Mi Push service (Initialization)
Initialize the Mi Push service by calling com.xiaomi.mipush.sdk.MiPushClient.registerPush.
You can receive the registration results in the implemented methods onReceiveRegisterResult and onCommandResult.
After registering successfully, a RegID (the only identification of current app on the device) will be returned. Report the RegID to your own server to send messages through it.
To increase the push registration rate, you can initialize the push on the method onCreate of your own app. You can also initialize pushes in other places according to your requirements. Note: Make sure you initialize pushes in the main process, and avoid multiple processes.
The codes are as follows:
public class DemoApplication extends Application {
public static final String APP_ID = "your appid";
public static final String APP_KEY = "your appkey";
@Override
public void onCreate() {
super.onCreate();
//Initialize push service in the main process
if(isMainProcess()) {
MiPushClient.registerPush(this, APP_ID, APP_KEY);
}
//Enable Log in case of errors
LoggerInterface newLogger = new LoggerInterface() {
private static String TAG = "XMPush";
@Override
public void setTag(String tag) {
}
@Override
public void log(String content, Throwable t) {
android.util.Log.d(TAG, content, t);
}
@Override
public void log(String content) {
android.util.Log.d(TAG, content);
}
};
Logger.setLogger(this, newLogger);
}
//Judge if it's in the main process
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:
Since the push service XMPushService has been set as running in another process in the AndroidManifest.xml, which will cause this app to be instantiated twice, therefore we need to initialize in the app's main process.
5、Set alias, userAccount and subscribe topic
After registering successfully, you can use the push service in the following ways according to your needs:
- Set alias: MiPushClient.setAlias. Process the setting result in the callback of onCommandResult;
- Subscribe topic: MiPushClient.subscribe. Process the subscription result in the callback of onCommandResult;
- Set account: MiPushClient.setUserAccount. Process the setting result in the callback of onCommandResult;
All methods above can be canceled by:
- Cancel alias setting: MiPushClient.unsetAlias. Process the result in the callback of onCommandResult;
- Cancel topic subscription: MiPushClient.unsubscribe. Process the result in the callback of onCommandResult.
- Cancel account setting: MiPushClient.unsetUserAccount. Process the result in the callback of onCommandResult;
If the settings have been successfully implemented, the results will be saved locally, the query method is as follows:
- Check RegID: MiPushClient.getRegId, return RegID;
- Check alias: MiPushClient.getAllAlias, return all successfully set aliases;
- Check topic: MiPushClient.getAllTopic, return all successfully subscribed topics;
- Check account: MiPushClient.getAllUserAccount, return all successfully set accounts;
三、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 3-1. MiPushClient Member List
API | Function | Scenario |
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 3-2. ErrorCode Static Variable
Static Variable | Meaning |
SUCCESS | Means the push service has been accessed |
ERROR_SERVICE_UNAVAILABLE | Indicates a push couldn't be connected due to network error. |
ERROR_INTERNAL_ERROR | Error with the internal status of the push. When coming across this error message, contact the developer. |
ERROR_AUTHERICATION_ERROR | A push connection couldn't be authenticated. |
ERROR_INVALID_PAYLOAD | The 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:
- To get messages pushed by the server;
- 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 3-3. PushMesssageReceiver member list
API | Function |
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 3-4. RegisterPush Function Parameter List
Parameter | Description |
context | The context of the app on the Android platform, we recommend you import the application context of current app. |
appID | Generated from the developer website, it is the unique app identifier issued from the Mi Push service. |
appKey | Generated 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 3-5. UnregisterPush Function Parameter List
Parameter | Description |
context | The 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 3-6. SetAlias Function Parameter List
Parameter | Description |
context | The context of the app on the Android platform, we recommend you import the application context of current app. |
alias | Set an alias for a specified user. |
category | Extended 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 3-7. UnsetAlias Function Parameter List
Parameter | Description |
context | The context of the app on the Android platform, we recommend you import the application context of current app. |
alias | Cancel an alias for a specified user. |
category | Extended 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 3-8. SetUserAccount Function Parameters List
Parameter | Description |
context | The context of the app on the Android platform, we recommend you import the application context of current app. |
userAccount | Set a userAccount for a specified user. |
category | Extended parameter, temporarily has no use, fill in as null. |
4.6. public static void unsetUserAccount(final Context context, final String userAccount, String category)
Develoers can cancel a certain userAccount of a specified user, the server then won't push messages to this userAccount.
Table 3-9. UnsetUserAccount Function Parameter List
Parameter | Description |
context | The context of the app on the Android platform, we recommend you import the application context of current app. |
userAccount | Cancel a userAccount for a specified user |
category | Extended 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 3-10. Subscribe Function Parameters List
Parameter | Description |
context | The context of the app on the Android platform, we recommend you import the application context of current app. |
topic | The topic a certain user has subscribed to. |
category | Extended 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 3-11. Unsubscribe Function Parameter List
Parameter | Description |
context | The context of the app on the Android platform, we recommend you import the application context of current app. |
topic | The topic a certain user unsubscribed from. |
category | Extended 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 3-12. SetAcceptTime Function Parameter List
Parameter | Description |
context | The context of the app on the Android platform, we recommend you import the application context of current app. |
startHour | The start time (hour) in the time period when receiving messages. |
startMin | The start time (minute) in the time period when receiving messages. |
endHour | The end time (hour) in the time period when receiving messages. |
endMin | The end time (minute) in the time period when receiving messages. |
category | Extended 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 3-13. PausePush Function Parameter List
Parameter | Description |
context | The context of the app on the Android platform, we recommend you import the application context of current app. |
category | Extended 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 3-14. ResumePush Function Parameter List
Parameter | Description |
context | The context of the app on the Android platform, we recommend you import the application context of current app. |
category | Extended 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 3-15. GetAllAlias Function Parameter List
Parameter | Description |
context | The 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 3-16. GetAllTopic Function Parameter List
Parameter | Description |
context | The 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 3-17. GetAllUserAccount Function Parameter List
Parameter | Description |
context | The 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 3-18. ReportMessageClicked Function Parameter List
Parameter | Description |
context | The context of the app on the Android platform, we recommend you import the application context of current app. |
msgid | The 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 3-19. ClearNotification Function Parameter List
Parameter | Description |
context | The context of the app on the Android platform, we recommend you import the application context of current app. |
notifyId | Call 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 3-20. ClearNotification Function Parameter List
Parameter | Description |
context | The 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 3-21. SetLocalNotificationType Function Parameter List
Parameter | Description |
context | The context of the app on the Android platform, we recommend you import the application context of current app. |
notifyType | The notification message reminder type. |
4.19. public static void clearLocalNotificationType(final Context context)
Clear the notification message reminder type set by the client.
Table 3-22. ClearLocalNotificationType Function Parameter List
Parameter | Description |
context | The 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 3-23. GetRegId Function Parameters List
Parameter | Description |
context | The 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 3-24. OnReceivePassThroughMessage Function Parameter List
Parameter | Description |
message | The 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 3-25. OnCommandResult Function Parameters List
Parameter | Description |
message | The 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
Parameter | Description |
permissions | Return 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 3-27. EnablePush Function Parameter List
Parameter | Description |
context | The 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 3-28. DisablePush Function Parameter List
Parameter | Description |
context | The 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).