MiPush Service SDK Client User Guide

MiPushServiceSDK for Client

Modify history
2013/07 Draft
2013/09/10 amended some inaccuracies, increased log methods for customer application and client.
2013/09/26 increased push usage scenarios describe some modifications and push Service and Receiver statement permissions, increased use of alias and topic scene description. Increase in notification bar icon setting method.
2014/01 modified access methods to broadcast for client
Any problems encountered, please contact us: DevPush@xiaomi.com

Directory

1 Client SDK Help

2. SDK Manual

2.1 configuration file AndroidManifest.xml

2.2 Customize a BroadcastReceiver class

2.3 Debug Log

2.4 Registe Push Service

2.5 Set the alias and subscribe topic

2.6 customize the icon on notification bar

2.7 Switching between the online and debug servers

3. API Description

3.1. MiPushClient access class

3.2. ErrorCode Error Type

3.3. PushMesssageReceiver broadcast receiver

3.4. API Details

1 Client SDK Help

Before using MiPush Service, developers need to login Mi developer site http://developer.xiaomi.com, regist an app, and get an AppId,an AppKey, and an
AppSecret. AppId and AppKey is the identity of client, which is used in the client SDK initialization; AppSecret is the server identity, which is used by the Server
SDK to send messages to the client. Then download the latest SDK archive, which includes a Server SDK, Client SDK, android DEMO.

MiPush Service currently only supports Android platform. SDK package is provided to developers in jar package, you can use MiPush Service in a small amount of code.

More information about Push Service SDK client main functional interface, please refer to Section 3 API instructions. After successful registration, the client, the server will be awarded regId, then you can subscribe to topic, set the alias (refer to 2.3) to receive push messages.  Mipush messaging currently supports two ways: through the transmission mode and the notification bar the way. After passing through the end of the phone message arrives, SDK will pass messages through broadcast subclass AndroidManifest registered PushMessageReceiver in; For notification bar message, SDK will pop up notification bar notification messages based on the information provided, after the user clicks the re-transmission subclasses of your PushMessageReceiver.

2. SDK Manual

Here’s how to configure and use MiPush Service, you can configure and use the SDK like a MiPush demo.

2.1 configuration file AndroidManifest.xml

  1. MiPush Service SDK runs on Android version 2.2 or later.

<uses-sdk android:minSdkVersion=”8″/>

  1. Push service requires permissions list below

<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” /> <uses-permission android:name=”android.permission.READ_PHONE_STATE” /> <uses-permission android:name=”android.permission.GET_TASKS” /> <uses-permission android:name=”android.permission.VIBRATE”/> <permission android:name=”com.xiaomi.mipushdemo.permission.MIPUSH_RECEIVE” android:protectionLevel=”signatureOrSystem” /> <-! Here com.xiaomi.mipushdemo into app package name ->

<uses-permission android:name=”com.xiaomi.mipushdemo.permission.MIPUSH_RECEIVE” />

<-! Here change com.xiaomi.mipushdemo into app package name ->

  1. Push service and receiver need to configure as below

<Service

android: enabled = “true”

android: process = “: pushservice”

android: name = “com.xiaomi.push.service.XMPushService” />

<Service   android: enabled = “true”

android: exported = “true”

android: name = “com.xiaomi.mipush.sdk.PushMessageHandler” />

<Service android: enabled = “true”

android: name = “com.xiaomi.mipush.sdk.MessageHandleService” />             <!– Note: This service must be in version2.2.5 or later (including version2.2.5) –>

<Receiver

android: exported = “true”

android: name = “com.xiaomi.push.service.receivers.NetworkStatusReceiver”>

<intent-filter>

<action android:name=”android.net.conn.CONNECTIVITY_CHANGE” />

<category android:name=”android.intent.category.DEFAULT” />

</ Intent-filter>

</ Receiver>

<Receiver

android: exported = “false”

android: process = “: pushservice”

android: name = “com.xiaomi.push.service.receivers.PingReceiver”>

<intent-filter>

<action android:name=”com.xiaomi.push.PING_TIMER” />

</ Intent-filter>

</ Receiver>

The XMPushService and PingReceiver are defined in the pushservice process, you can configure it to run in any process. If android: process is not definded, they will run in the application’s main process.

2.2 Customize a BroadcastReceiver class

In order to receive messages, you need to define a BroadcastReceiver class that inherits from PushMessageReceiver, and implement the functions of onCommandResult and onReceiveMessage , and then register the receiver in file AndroidManifest.xml . onCommandResult method receive a response from the server to client, onReceiveMessage method receive messages sent by the server to the client.

For 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 mStartTime;

private String mEndTime;

@ Override

public void onReceiveMessage (Context context, MiPushMessage message) {

mMessage = message.getContent ();

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

mTopic = message.getTopic ();

} Else if (! TextUtils.isEmpty (message.getAlias ​​())) {

mAlias ​​= message.getAlias ​​(); }

}

@ Override

public void onCommandResult(Context context, MiPushCommandMessage message) {

String command = message.getCommand ();

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

if (arguments! = null) {

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

Arguments.size () == 1) {

mRegId = arguments.get (0);

} Else if ((MiPushClient.COMMAND_SET_ALIAS. Equals

(command) | |                                                              MiPushClient.COMMAND_UNSET_ALIAS.equals (command)) && Arguments.size () == 1) { mAlias ​​= arguments.get (0); } Else if ((MiPushClient.COMMAND_SUBSCRIBE_TOPIC.equals (command) | | MiPushClient.COMMAND_UNSUBSCRIBE_TOPIC.equals (command)) && Arguments.size () == 1) {

mTopic = arguments.get (0);

} Else if (MiPushClient.COMMAND_SET_ACCEPT_TIME.equals (command) && Arguments.size () == 2) {

mStartTime = arguments.get (0);

mEndTime = arguments.get (1);

}

}

mResultCode = message.getResultCode ();

mReason = message.getReason ();

}

}

Registering customer BroadcastReceiver in file AndroidManifest.xml

<Receiver

android: exported = “true”

android: name = “com.xiaomi.mipushdemo.DemoMessageReceiver”>

<-! Here com.xiaomi.mipushdemo.DemoMessageRreceiver defined app into full

class name ->

<intent-filter>

<action android:name=”com.xiaomi.mipush.RECEIVE_MESSAGE” />

</ Intent-filter>

<intent-filter>

<action android:name=”com.xiaomi.mipush.ERROR” />

</ Intent-filter>

</ Receiver>

Note:

  1. onCommandResult and onReceiveMessage method runs in a non-UI thread.
  2. If your code was obfuscated, you need to keep BroadcastReceiver. Customer BroadcastReceiver inherited from PushMessageReceiver, that use the following code is not enough.

-Keep public class * extends android.content.BroadcastReceiver

You need to use the following code to keep BroadcastReceiver.

# Here com.xiaomi.mipushdemo.DemoMessageRreceiver app into full class name defined

-keep class com.xiaomi.mipush.sdk.DemoMessageReceiver {*;}

2.3 Debug Log

2.3.1 Open Logcat debug log

  1. In the customer Application’s onCreate method add the following code.

LoggerInterface newLogger = new LoggerInterface () {

@ Override

public void setTag (String tag) {

/ / Ignore

}

@ Override

public void log (String content, Throwable t) {

Log.d (TAG, content, t);

}

@ Override

public void log (String content) {

Log.d (TAG, content);

}

};

Logger.setLogger (this, newLogger);

  1. Configurate Application in the AndroidManifest.xml file, and the android: debuggable is set to true.

<Application

android: icon = “@ drawable / ic_launcher”

android: label = “@ string / app_name”

android: debuggable = “true”

android: name = “com.xiaomi.mipushdemo.DemoApplication”>

<-! Here replaced by a customer Application ->

2.3.2 Close Logcat debug log

After development, you need to close debug log, simply in AndroidManifest.xml file android: debuggable is set to false.

As follows:

<Application

android: icon = “@ drawable / ic_launcher”

android: label = “@ string / app_name”

android: debuggable = “false”

android: name = “com.xiaomi.mipushdemo.DemoApplication”>

<-! Here replaced by a customer Application ->

Note: By default, we will write log files in directory /sdcard/mipush ,even if the Logcat debug log is closed. If you need to close to write the log file (not recommended off), just call Logger.disablePushFileLog (context) .

2.4 Registe Push Service

You can initialize your Push Service by calling MiPushClient.register . After successful registration, you will receive registration results in onCommandResult method, with the regId which is the unique identify of the current app on the device. You can upload the regId to your server to send messages.

In order to increase the enrollment, you can initialize the push in onCreate method. You may also initialize the push in other places you need.

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 () {

super.onCreate ();

/ / Will switch to the online server

Constants.useOfficial ();

/ / Initialize push service

if (shouldInit ()) {

MiPushClient.registerPush (this, APP_ID,APP_KEY);

}

/ / Open Log

LoggerInterface newLogger = new LoggerInterface () {

@ Override

public void setTag (String tag) {

/ / Ignore

}

@ Override

public void log (String content, Throwable t) {

Log.d (TAG, content, t);

}

@ Override

public void log (String content) {

Log.d (TAG, content);

}

};

Logger.setLogger (this, newLogger);

}

private boolean shouldInit () {

ActivityManager am = ((ActivityManager) getSystemService (Context.ACTIVITY_SERVICE));

List <RunningAppProcessInfo> processInfos = am.getRunningAppProcesses ();

String mainProcessName = getPackageName ();

int myPid = Process.myPid ();

for (RunningAppProcessInfo info: processInfos) {

if (info.pid == myPid && mainProcessName.equals (info.processName)){

return true;

}

}

return false;

}

}

Note: Because we set the push service XMPushService runs in another process in AndroidManifest.xml, which leads to the Application be instantiated twice, so we need to initiate not in push service process.

2.5 Set the alias and subscribe topic

After successful registration and upon receiving the regId, you can call MiPushClient.setAlias ​​to set alias, call MiPushClient.subscribe to Subscribe topic.

alias is the alias of regId, developers can use the alias set for their account system account, or equipment identification. When Server SDK sends a message , it will be sent to a specific alias, rather than regId,  so that regId won’t be stored.

Topic is used for broadcast messages. You can subscribe the same topic in the same app on different phones. Sending messages by topic API, you can simultaneously send messages to all clients subscribed to the topic. For instance, you have a kind of news app, you can customize the “Finance”, “sports”, “technology” and other topics; For users who often read financial news, you can help the users to subscribe to the “Finance” topic, when a new Financial Highlights occurs when directly through thematic push this news to all users subscribed to the topic.

2.6 customize icon on notification bar

Currently notification class messages,
Icon display rules are as follows: 1) If there is simultaneously a drawable file named mipush_notification and mipush_small_notification in the app, then use the drawable mipush_notification notified as large icons, mipush_small_notification the drawable as a small icon notification. 2) If there is only one app drawable file, use the drawable icon as notification.
3) If the app does not exist in these two drawable files, use the app’s icon as an icon in the notification. In MIUI, the notification bar icon appears as a unified app’s icon, can not be customized.

2.7.Switching between the online and debug servers

In order to facilitate the development and debugging, in addition to the online server, we also provide a debug server runtime environment. In order to avoid the effects of a published app, you can develop and debug on the debug server, be sure to switch to the online server after development.You can switch servers in client as follows:

Constants.useOfficial (); / / use a online environment.

Constants.useSandbox (); / / use the debug environment.

Please perform the above method in your Application static code block. When using the debug environment, regId, alias, topic only take effect on the debug server, then the need to Server SDK also use the debug environment (see specific methods on the server side SDK User Guide).

Debug server resources is limited, be sure to switch to online server when the app released.

3. API Description

For developers, the client SDK have two functions , one is the client send various requests to the server, on the other hand is the message sent by the server to the client or respond to client requests. They are access class MiPushClient and implemente class of PushMesssageReceiver.

3.1. MiPushClient access class

MiPushClient is MiPush Client
Android platform SDK access classes. This class provides a series of static methods (static), without instantiated.

3.1.1. MiPushClient

public abstract class

extends Object

java.lang.Object

↳ com.xiaomi.mipush.sdk.MiPushClient

3.1.2 Member List

Table 1. MiPushClient list members

API FUNCTION USE SCENE
registerPush () Sign MiPush push service By the user to decide whether to open a push
unregisterPush () Close MiPush push service Push the user to decide whether to close
setAlias ​​() Set an alias for the specified user Developers decided to push through an alias
unsetAlias ​​() Cancel the specified user alias Developers need to cancel a user alias
subscribe () Subscribe a topic for a user According to user subscription ,the developer send a group of messages.
unsubscribe () Cancel a user’s subscription of topic Users cancel a subscription of topic
pausePush () Suspend to receive MiPush push messages Before restoring MiPush app push services, client does not receive any push message
resumePush () Restore service to receive MiPush push messages, then the server will push the message during the push message was suspended   again Restore service to receive MiPush push messages
setAcceptTime () Set MiPush service period, messages will be cached in the period does not push messages,cached messages will be push again in the right time . Users can control what time to receive push messages

3.2. ErrorCode Error Type

ErrorCode is the type of error returned after the failure of the push access.

3.2.1. ErrorCode

public abstract class

extends Object

java.lang.Object

↳ com.xiaomi.mipush.sdk.ErrorCode

3.2.2 Static variables

Table 2. ErrorCode static variables

STATIC VARIABLES MEANING
SUCCESS access push was successful.
ERROR_SERVICE_UNAVAILABLE Access push was failed due to network connection failure.
ERROR_INTERNAL_ERROR push internal state error, encountered such an error, please contact the developer.
ERROR_AUTHERICATION_ERROR Certification push connection fails.
ERROR_INVALID_PAYLOAD Message format is not valid.

3.3. PushMesssageReceiver broadcast receiver

PushMessageReceiver is an abstract BroadcastReceiver class , which defines two abstract methods, onCommandResult and onReceiveMessage.

It has two purposes:

  1. Get the server pushed messages
  2. Get return results by called MiPushClient

3.3.1. PushMesssageReceiver

public abstract class

extends Object

java.lang.Object

↳ com.xiaomi.mipush.sdk.PushMesssageReceiver

3.3.2 Member List

Table 3. PushMesssageReceiver member list

API FUNCTION
onReceiveMessage (Context context, MiPushMessage
message)
Receiving server push message, the message is encapsulated in class MiPushMessage. MiPushMessage references 3.4.10.
onCommandResult (Context context, MiPushCommandMessage
message)
Get the result Send of the commands to the server , the result is encapsulated in class MiPushCommandMessage. MiPushCommandMessage property reference 3.4.11.

3.4. API Details

3.4.1. Public static void registerPush (Context context, String appID, String appKey)

Regist MiPush push service, it is recommended called when app startup.

Table 4. RegisterPush function parameter list

PARAMETER LIST PARAMETER DESCRIPTION
context App context on the Android platform, the proposal passed in the current application context
appID Generated when registered on the website , It is the identification of an app with MiPush push services .
appKey Generated when registered on the website, and appID corresponds, used to verify the legality of an appID

3.4.2. Public static void unregisterPush (Context context)

Close MiPush push service, when the user wishes to no longer use MiPush push service when called after the call is successful, app will not receive any MiPush service push data until the next call registerPush().

Note: After calling unregisterPush(), the server does not send any messages to the app.

Table 5. UnregisterPush function parameter list

PARAMETER LIST PARAMETER DESCRIPTION
context App context on the Android platform, the proposal passed in the current application context

3.4.3. Public static void setAlias ​​(Context context, String alias, String category)

Developers can set an alias for the specified user, and then push the message to the alias, the effect is equivalent to RegId push messages.

Note: A RegId can be set multiple aliases, if the alias set already exists, it will overwrite the alias before.

Table 6. SetAlias ​​function parameter list

PARAMETER LIST PARAMETER DESCRIPTION
context App context on the Android platform, the proposal passed in the current application context
alias An alias for the specified user
category Extended parameters, there is no purpose, directly fill null

3.4.4. Public static void unsetAlias ​​(Context context, String alias, String category)

Developers can specify the user to cancel an alias, the alias server push messages not give up.

Table 7. UnsetAlias ​​function parameter list

PARAMETER LIST PARAMETER DESCRIPTION
context App context on the Android platform, the proposal passed in the current application context
alias An alias for the specified user
category Extended parameters, there is no purpose, directly fill null

3.4.5. Public static void subscribe (Context context, String topic, String category)

Subscribe a topic for a user; according to different topics user subscriptions, the developer send groups of messages.

Table 8. Subscribe function parameter list

PARAMETER LIST PARAMETER DESCRIPTION
context App context on the Android platform, the proposal passed in the current application context
topic A user subscribed Topic
category Extended parameters, there is no purpose, directly fill null

3.4.6. Public static void unsubscribe (Context context, String topic, String
category)

For a user to cancel a subscription topic.

Table 9. Unsubscribe function parameter list

PARAMETER LIST PARAMETER DESCRIPTION
context App context on the Android platform, the proposal passed in the current application context
topic A user unsubscribe topic
category Extended parameters, there is no purpose, directly fill null

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

Set MiPush service period, messages will be cached in the period does not push messages,cached messages will be pushagain in the right time .

Here we use 24-hour clock, if the start time is earlier than the end of time, this time period will be in a day; Otherwise, the periodwill go from today to tomorrow.

Note:
The alias that associated with the topic regId will be limited too.

If the periodis set to 0:00-0:00, which is suspended the push service, it is the same as you call pausePush() method directly.

If the periodis set to 0:00-23:59,that restoredthe push service, which is open to receive the push messages, you can also directly call resumePush() method, which is essentially the same

Table 10. SetAcceptTime function parameter list

PARAMETER LIST PARAMETER DESCRIPTION
context App context on the Android platform , the proposal passed in the current application context
startHour Start hour of the reception period
startMin Start minute of the reception period
endHour End hour of the reception period
endMin End minute of the reception period
category Extended parameters, there is no purpose, directly fill null

3.4.8. Public static void pausePush (Context context, String category)

Pause to receive MiPush push messages , before resuming MiPush push service,the clientwill not receive any push message

Note: The alias that associated with the topic regId will be suspended too.

Table 11. PausePush function parameter list

PARAMETER LIST PARAMETER DESCRIPTION
context App context on the Android platform , the proposal passed in the current application context
category Extended parameters, there is no purpose, directly fill null

3.4.9. Public static void resumePush (Context context, String category)

Restore service to receive MiPushpush messages

Note:The alias that associated with the topic regId will be restored too; then the messages suspended will be pushed again.

Table 12. ResumePush function parameter list

PARAMETER LIST PARAMETER DESCRIPTION
context App context on the Android platform , the proposal passed in the current application context
category Extended parameters, there is no purpose, directly fill null

3.4.10. Public void onReceiveMessage (Context context, MiPushMessage message)

Receiving push messages. You can choose onReceiveMessagemethod to accept messages.

Table 13. OnReceiveMessage function parameter list

PARAMETER LIST PARAMETER DESCRIPTION
message Server push messages encapsulatedin MiPushMessage object, you can get messageType , messageId, content, alias, topic, passThrough, isNotified, notifyType, description, title, extra from the object.

  1. messageType indicates the type of message is divided into three types: MESSAGE_TYPE_REG, MESSAGE_TYPE_ALIAS, MESSAGE_TYPE_TOPIC, these three are MiPushMessage static variables.
  2. If the server is to push the message alias, the alias is not null.
  3. If the server is to push the message topic, the topic content is not null.
  4. passThrough indicates the server-side push message types.
    If passThrough value of 1, it is transparently transmits the message; If passThrough value is 0, it is the notification bar message.
  5. isNotified indicates whether the message is passed through the notification bar. If true, the message in the notification bar turned out notice; If false,it means the message is passed directly to the app, with no pop-over notification.
  6. messageId is the id of the message.
  7. content is the content of the message.
  8. notifyType message is to remind the way, such as vibration, ring and flash.
  9. description is a description of the messages.
  10. title is the title of the message.
  11. extra is a map type, contains some additional information, such as customize notification bar ringtones URI, click behavior notification bar and so on.

3.4.11. Public void onCommandResult (Context context, MiPushCommandMessage message)

The resultsreturns from the serverWhen the client sends to the server registration push, set the alias, unset alias, subscribe topic,unsubscribe topicetc.

Table 14. OnCommandResult function parameter list

PARAMETER LIST PARAMETER DESCRIPTION
message The server returns the command encapsulated in MiPushCommandMessage object, you can get command, commandArguments from the object, resultCode, reason and other information.

  1. command indicates the type of command.
    • Call MiPushClient.registerPush (), returns MiPushClient.COMMAND_REGISTER
    • Call MiPushClient.setAlias ​​(), returns MiPushClient.COMMAND_SET_ALIAS
    • Call MiPushClient.unsetAlias ​​(), returns MiPushClient.COMMAND_UNSET_ALIAS
    • Call MiPushClient.subscribe (), returns MiPushClient.COMMAND_SUBSCRIBE_TOPIC
    • Call MiPushClient.unsubscribe (), returns MiPushClient.COMMAND_UNSUBSCIRBE_TOPIC
    • Call MiPushClient.setAcceptTime (), returns MiPushClient.COMMAND_SET_ACCEPT_TIME
    • Call MiPushClient.pausePush (), returns MiPushClient.COMMAND_SET_TARGETPT_TIME
    • Call MiPushClient.resumePush (), returns MiPushClient.COMMAND_SET_ACCEPT_TIME
  2. commandArguments is parameter of the command . For example:
    It will return regId when regist an app,   alias will return alias, subscribe and unsubscribe topics will return topic, setAcceptTime will return time period.
  3. resultCode said result of the call command. If successful, the return ErrorCode.Sussess that 0; otherwise it returns an error type value.
  4. reason, said the reasons for the failure. If it fails, it returns the reason for failure, otherwise returns null.