All Products
Search
Document Center

Quick start

Last Updated: Mar 24, 2021

This topic briefly describes how to fast integrate MPS to the Android client. You can access MPS through Native AAR, mPaaS Inside, or Portal & Bundle.

The complete access process mainly includes the following 5 steps:

  1. Add pushSDK: Add the SDK dependencies.
  2. Initialize pushSDK: Establish persistent connection between the client and the mobile push gateway, and obtain the device ID.
  3. Monitor messages: Compile a service to receive messages and obtain Android device IDs (Ad-tokens) to push messages based on device ID.
  4. Report the user ID: Report the user ID to the server to bind the user and the device, and push messages based on the user dimension.
  5. Report push data: Upload the data of message arrivals, opened messages, and ignored messages to the server for statistical analysis. The results can be viewed in the mPaaS console.

Prerequisites

Add pushSDK

Add the SDK dependencies.

Native AAR mode

Follow the instructions in AAR component management to install the PUSH component in the project through Component management (AAR).

mPaaS Inside mode

Install the PUSH component in the project through Component management (AAR).

Fore more information, see Add component dependencies.

Componentized access mode

Install the PUSH component in the Portal and Bundle projects through Component management (AAR).

Fore more information, see Add component dependencies.

Initialize pushSDK

Establish persistent connection between the client and the mobile push gateway, and obtain the device ID.

The client calls the MPPush class at the mPaaS middle tier to initialize the MPS SDK:

  1. MPPush.setup(Application application);
  2. MPPush.init(Context context);

In the initialization process, pushSDK attempts to establish connection between the preconfigured address and port. If the client information for establishing connection does not carry the device identifier, the Mobile Push Gateway will deliver the device identifier (Ad-token) after the connection is successfully established.

The service configured in the App can be used to obtain the device identifier that the MPS SDK has successfully obtained. For more information, see code samples in Monitor messages.

Monitor messages

After receiving a pushed message or Ad-token, the pushSDK starts a service to process the message or Ad-token. To enable device-specific message push, compile a service to receive messages and obtain Android device identifiers (Ad-tokens).

About this task

Compile and configure a service inherited from AliPushRcvService to receive device identifiers and messages delivered by the mobile push gateway.

Procedure

  1. Compile a service. Separately compile a service for the client to receive messages and a service to obtain Ad-tokens, or compile one service for both receiving messages and obtaining Ad-tokens. The following is code sample of a service for both receiving messages and obtaining Ad-tokens:

    1. public class PushMsgService extends AliPushRcvService {
    2. private static final String TAG = "pushTag";
    3. public static final String PUSH_SERVICE_ACTION = "tt-action";
    4. //Push type, which can be customized
    5. public static final int TYPE_MSG = -1;
    6. public static final int TYPE_INNER_PUSH_INIT = -2;
    7. public static final int TYPE_THIRD_PUSH_INIT = -3;
    8. //Self-built channel push ID
    9. public static String mAdToken = "";
    10. //3rd-party channel push ID
    11. public static String mThirdToken = "";
    12. public static String mUserId = "mpaas_push_demo";
    13. public static int platformType = 0;
    14. public static boolean useDefault = false;
    15. public PushMsgService() {
    16. super();
    17. }
    18. /**
    19. * Determine whether the messages to be presented use self-built notifications
    20. * If true is returned, then all presented (non-silent) messages will be processed by mPaaS, and handleActionReceived will not be called.
    21. * If false is returned, then all messages will be passed through.
    22. */
    23. @Override
    24. protected boolean useDefaultNotification(String msgKey, String msgValue) {
    25. Intent intent = new Intent(PUSH_SERVICE_ACTION);
    26. intent.putExtra("push_type", TYPE_MSG);
    27. intent.putExtra("push_key", msgKey);
    28. intent.putExtra("push_value", msgValue);
    29. LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    30. LoggerFactory.getTraceLogger().debug(TAG, "onHandleIntent sendLocalBroadcast: " + intent.toString());
    31. return useDefault;
    32. }
    33. /**
    34. * Message process callback. For self-built messages, you need to process the pop-up notifications.
    35. * @param msgKey Message key
    36. * @param msgValue Message value
    37. * @param clicked Whether the message has been clicked
    38. * For the 3rd-party channels, if clicked = true, it means to display the notification bar
    39. * For the self-built channel, if clicked = false, it means not to dispaly the notification bar
    40. */
    41. @Override
    42. protected void handleActionReceived(String msgKey, String msgValue, boolean clicked) {
    43. if (TextUtils.isEmpty(msgValue)) {
    44. return;
    45. }
    46. BDataBean data = BDataBean.create(msgValue);
    47. if (clicked) {
    48. try {
    49. Uri uri = Uri.parse(data.getUrl());
    50. Intent actionIntent = new Intent(Intent.ACTION_VIEW);
    51. actionIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    52. actionIntent.setData(uri);
    53. actionIntent.putExtra("data", data.getParams());
    54. startActivity(actionIntent);
    55. } catch (Exception e) {
    56. Log.e(TAG, "Unable start activity due to wrong format uri", e);
    57. }
    58. } else {
    59. // show your notification and handle action
    60. NotificationHelper helper = new NotificationHelper(getApplicationContext());
    61. helper.notify("(not self-built messages)" + data.getTitle(), data.getContent());
    62. }
    63. }
    64. /**
    65. * @param adToken Push ID of self-built channel
    66. */
    67. @Override
    68. protected void handleActionId(String adToken) {
    69. PushAppInfo pushAppInfo = new PushAppInfo(getApplicationContext());
    70. pushAppInfo.setAppToken(adToken);
    71. LoggerFactory.getTraceLogger().debug(TAG, "self-built channel adToken: " + adToken);
    72. Intent intent = new Intent(PUSH_SERVICE_ACTION);
    73. intent.putExtra("push_type", TYPE_INNER_PUSH_INIT);
    74. intent.putExtra("push_token", adToken);
    75. LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    76. mAdToken = adToken;
    77. }
    78. /**
    79. * @param thirdToken Push ID of the 3rd-party channel
    80. * @param platformType Platform type of the 3rd-party channels, 5: Huawei; 4: Xiaomi; 7: OPPO; 8: VIVO
    81. */
    82. @Override
    83. protected void handleActionThirdId(String thirdToken, int platformType) {
    84. LoggerFactory.getTraceLogger().debug(TAG, "3rd-party channel adToken: " + thirdToken + "platformType: " + platformType);
    85. Intent intent = new Intent(PUSH_SERVICE_ACTION);
    86. intent.putExtra("push_type", TYPE_THIRD_PUSH_INIT);
    87. intent.putExtra("push_thirdToken", thirdToken);
    88. intent.putExtra("push_channel", platformType);
    89. LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    90. mThirdToken = thirdToken;
    91. PushMsgService.platformType = platformType;
    92. }
    93. }
  2. Configure this service in AndroidManifest.xml. In the projects based on the mPaaS framework, this service can be configured in the AndroidManifest.xml file of the portal or bundle project.
    Note: When you use wildcard characters, replace ${} in the code with the actual value.

    • ${applicationId}: Package name.
      For example, replace ${applicationId}.push.action.CHECK with com.mpaas.demo.push.action.CHECK.
    • ${appId} and ${workspaceId}: Application ID and workspace ID. Go to the mPaaS console > Code Configuration page, and download the configuration file. The .config file contains the values of both the App ID and workspace ID.
      1. <uses-permission android:name="android.permission.INTERNET" />
      2. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      3. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
      4. <uses-permission android:name="android.permission.BROADCAST_STICKY" />
      5. <uses-permission android:name="android.permission.READ_PHONE_STATE" />
      6. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
      7. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      8. <uses-permission android:name="android.permission.WRITE_SETTINGS" />
      9. <uses-permission android:name="android.permission.VIBRATE" />
      10. <uses-permission android:name="android.permission.WAKE_LOCK" />
      11. <!-- RecvMsgIntentService is the service defined in the foregoing code. -->
      12. <service android:name="com.mpaas.demo.push.PushMsgService"
      13. android:exported="false" >
      14. <intent-filter>
      15. <!-- MESSAGE_RECEIVED indicates to process the received message.-->
      16. <action android:name="${applicationId}.push.action.MESSAGE_RECEIVED" />
      17. <!-- REGISTRATION_ID indicates to process the obtained device identifier.-->
      18. <action android:name="${applicationId}.push.action.REGISTRATION_ID" />
      19. <category android:name="${applicationId}" />
      20. </intent-filter>
      21. </service>
      22. <!-- You need to configure alipush appId-->
      23. <meta-data
      24. android:name="ALIPUSH_APPID"
      25. android:value="${appId}-${workspaceId}" />
      26. <service
      27. android:name="com.alipay.pushsdk.push.NotificationService"
      28. android:enabled="true"
      29. android:exported="false"
      30. android:process=":push"
      31. android:label="NotificationService">
      32. <intent-filter>
      33. <action android:name="${applicationId}.push.action.START_PUSHSERVICE" />
      34. </intent-filter>
      35. </service>
      36. <service
      37. android:name="com.alipay.pushsdk.push.AppInfoRecvIntentService"
      38. android:exported="false"
      39. android:process=":push">
      40. </service>
      41. <receiver
      42. android:name="com.alipay.pushsdk.BroadcastActionReceiver"
      43. android:enabled="true"
      44. android:process=":push">
      45. <intent-filter android:priority="2147483647">
      46. <action android:name="android.intent.action.BOOT_COMPLETED" />
      47. <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
      48. <action android:name="android.intent.action.USER_PRESENT" />
      49. <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
      50. </intent-filter>
      51. </receiver>
      52. <receiver
      53. android:name="com.alipay.mobile.logmonitor.ClientMonitorWakeupReceiver"
      54. android:enabled="true"
      55. android:process=":push">
      56. <intent-filter>
      57. <action android:name="android.intent.action.BOOT_COMPLETED" />
      58. <action android:name="${applicationId}.push.action.CHECK" />
      59. <action android:name="${applicationId}.monitor.command" />
      60. </intent-filter>
      61. </receiver>
  3. You can create a simple push message in the console to test whether the device-based push notification can be sent successfully.
    For more information about how to create messages, see Create a message > Procedure.

Follow-up steps

  • In the 10.1.60 baseline, notification built in mPaaS is supported to cope with common message push scenarios. For more information, see Notification built in mPaaS.
  • To improve the arrival rate of messages, you can choose whether to enable third-party push channels on an Android client. For more information, see Third-party push channels.
  • The MPS SDK supports message push based on user identifiers. You can bind a user identifier and a device identifier. For more information, see Report user ID.

Report user ID

To push messages in the user dimension, upload the user identifier to the server after the user logs in. The server sends a request to the mobile push service for user and device binding. The user and the device are unbound when the user logs out.

For more information about operations on the server, see Configure the server.

Complete the following steps to report the user ID:

  1. Provide an API to facilitate user binding and unbinding. Its code sample is as follows:

    1. // For more information about the code, see the Demo.
    2. // The userId here does mustn't be a real identifier in your user system, but it must map to a single user.
    3. // Parameter userId, adtoken (received in service handleActionId)
    4. ResultPbPB resultBean = MPPush.bind(getApplicationContext(), your userId, ad-token);
    5. ResultPbPB resultBean = MPPush.unbind(getApplicationContext(), your userId, ad-token);
    6. //If you have set the userId by calling MPLogger.reportUserLogin() or MPLogger.setUserId(), you can directly use the following method (the version must be 10.1.60.9 or later, or 10.1.68.3 or later).
    7. ResultPbPB resultBean = MPPush.bind(getApplicationContext(), ad-token);
    8. ResultPbPB resultBean = MPPush.unbind(getApplicationContext(), ad-token);
  2. Choose an appropriate time for binding the API. The optional time can be:

    • A user logs into the App and a pushed Ad-token is received (this ensures the API can receive push messages for the first time upon login);
    • The App is cold started (this prevents unregistered access).

Report push data

PushSDK defines APIs that handle messages upon their arrival, open messages, and track ignored messages.

Message arrivals

After connecting to the PushSDK, you do not need to perform any operations and MPS automatically completes statistical analysis of message arrival data.

For messages pushed via different channels, MPS measures the number of arrived messages and the arrival rate in different ways.

  • Self-built channels
    For messages pushed through an MPS self-built channel, the MPS SDK automatically reports message arrival events when they arrive at the clients, and the server automatically measures the number of message arrivals and the arrival rate.
  • Third-party channels
    For messages pushed through third-party channels, the backend services of the corresponding channels return the push result data. MPS performs statistical analysis for the data to obtain the number of message arrivals and the arrival rate.

Opened messages

Call reportPushOpen to report message opening events. The server counts the number of opened messages and the open rate.

  1. public static void reportPushOpen(String pushMsgId, String pushMsgValue)

Call timing

The call timings for notification bar messages of third-party channels and custom display messages are different. The details are as follows:

  • Notification bar messages of third-party channels: After a message is opened, the MPS SDK automatically calls reportPushOpen to report related data.
  • Custom display messages: You need to enable listeners of message-opening events. When a message-opening operation is monitored, reportPushOpen is called to report related data.

Parameter description

pushMsgId and pushMsgValue can be obtained from the pushed message body, as shown in the following figure.

  • pushMsgId: the message ID corresponding to the k value in the preceding message body.
  • pushMsgValue: the message value corresponding to the bData value in the preceding message body.

Ignored messages

Call reportPushIgnored to report message-ignoring events. The server measures the number of ignored messages and the ignore rate.

  1. public static void reportPushIgnored(String pushMsgId, String pushMsgValue)

Call timing

For custom display messages, you need to enable listeners of message-ignoring events. When a message-ignoring event is monitored, reportPushIgnored is called to report related data.

Note: For messages that cannot be customized for display, MPS cannot count the number of ignored messages.

Parameter description

See Parameter description.

Code sample

Click here to download the code sample.

What to do next

After you successfully integrate MPS to your Android client, you can call the RESTful interface through the server. For more information, see Configure server > Push message.