English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Analysis and Implementation Method of Xiaomi Push Demo on Android Mobile Terminal

In the past few months, I have been preparing for and looking for jobs, and have made many efforts, finally with some gains, so I haven't had time to organize notes. It was only recently that I had time to organize my notes and post them online to share my learning experience.

Push
As the recent project needs to use Android message push, there are many solutions for Android push, such as C2DM, polling, SMS, MQTT protocol, XMPP protocol, and third-party platforms. After considering the project requirements, we chose Xiaomi Push for third-party platform push. Below is the implementation method of Xiaomi Push.

Preparation for implementation

If you want to use Xiaomi Push, you first need to register and apply for a developer account on the Xiaomi Developer Platform, and after1to3After the review the next day, it will be approved, and then you can apply for push services. After applying for push services for an App, obtaining AppID and AppKey, you can study and use the Demo provided by it. Below, I will mainly talk about my understanding of the Demo.

Push notifications instructions

The content of the push notification can be implemented by the backend service using the Xiaomi Push SDK, or sent through the Xiaomi Push Platform. There are two types of messages to be sent: notification messages and transparent information.

Notification messages:

These are messages that will be displayed in the Android system notification bar. The user needs to implement the response event after clicking or specify to open the App when sending.

Transparent transmission messages:

Is transparent transmission, that is, regardless of the type of business transmission, it is responsible for transmitting the required business to the destination node, while ensuring the quality of transmission, without processing the business being transmitted. It directly sends the message to the App and does not automatically display it in the notification bar.

Official Demo Instructions

The official demo simply shows us various settings of Xiaomi Push and how to implement receiving push notifications. First, the Xiaomi Push SDK is added to the Library, and then there is4Java file, as shown

The4You can ignore the Dialog, the key is the DemoMessageReceiver broadcast receiver, which receives various notifications and processes them. The DemoApplication and MainActivity are used to display the received information.

Then the interface looks like this (the demo didn't do screen adaptation, so it is like that):

A set of configurations about push notifications and a TextView to display logs. It mainly demonstrates the usage process of Xiaomi Push.

DemoMessageReceiver broadcast receiver

To implement the mobile end receiving of Xiaomi Push, the core is the most important DemoMessageReceiver BroadcastReceiver mentioned above. This BroadcastReceiver inherits from the PushMessageReceiver class in the Xiaomi SDK, and this BroadcastReceiver can override the following to5the callback method to implement the processing of push notifications.
 

@Override
  public void onReceivePassThroughMessage(Context context, MiPushMessage miPushMessage) {
    //to receive the pass-through messages sent from the server to the client, and the pass-through message triggers when received.
  }
  @Override
  public void onNotificationMessageClicked(Context context, MiPushMessage miPushMessage) {
    //to receive the notification messages sent from the server to the client, this callback method is triggered when the user manually clicks on the notification.
  }
  @Override
  public void onNotificationMessageArrived(Context context, MiPushMessage miPushMessage) {
    //to receive the notification messages sent from the server to the client, this callback method is triggered when the notification message arrives at the client. Additionally, the callback function is also triggered when the notification message arrives at the client and the app is in the foreground without popping a notification.
  }
  @Override
  public void onReceiveRegisterResult(Context context, MiPushCommandMessage miPushCommandMessage) {
    //to receive the response results after the client sends a registration command to the server
  }
  @Override
  public void onCommandResult(Context context, MiPushCommandMessage miPushCommandMessage) {
    //to receive the response results after the client sends commands to the server. Here, various command return results can be received, such as the results of registering services and setting aliases, and functions such as initializing errors and restarting can be implemented here.
  }

DemoApplication inherits from the Application class

The main functions of this Application class include setting the App's ID and KEY, and registering the push service in the onCreate method.

In this Demo, it also creates a Handler to allow the BroadcastReceiver to use it to send Toasts and to print Logs in the TextView for MainActivity.

 // user your appid the key.
  private static final String APP_ID = "1000270";
  // user your appid the key.
  private static final String APP_KEY = "670100056270";
  // This TAG can be used to retrieve the required information in adb logcat, just enter adb logcat | grep in the command line terminal.
  // com.xiaomi.mipushdemo
  public static final String TAG = "com.xiaomi.mipushdemo";
  private static DemoHandler sHandler = null;
  private static MainActivity sMainActivity = null;
  @Override
  public void onCreate() {
    super.onCreate();
    // Register the push service, and a broadcast will be sent to DemoMessageReceiver after registration is successful.
    // Registration information can be obtained from the MiPushCommandMessage object parameter in the onCommandResult method of DemoMessageReceiver.
    if (shouldInit()) {
      MiPushClient.registerPush(this, APP_ID, APP_KEY);
    }
    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);
    if (sHandler == null) {
      sHandler = new DemoHandler(getApplicationContext());
    }
  }
  //This method is to check if the process is in the foreground.
  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;
  }

MainActivity

The MainActivity in the Demo is mainly to handle the buttons on the interface, thereby telling us how to set the local push scheme, with specific settings including

  • Setting and revocation of aliases: Aliases (Alias) are user identifiers other than Regid (auto-generated) and UserAccount. They can be set and revoked through MiPushClient.setAlias() and MiPushClient.unsetAlias().
  • Setting and revocation of user accounts (UserAccount): It can be set and revoked through the MiPushClient.setUserAccount() method and the MiPushClient.unsetUserAccount() method.
  • Subscription and revocation of tags: Developers can combine their business features to tag users with different labels (Topics). When pushing messages, developers can combine the content of each message and the target user to select the corresponding tag for each message and push the message to all users who have been tagged with that tag. Subscription and cancellation can be done through MiPushClient.subscribe() and MiPushClient.unsubscribe().
  • Pause and resume push notifications, set push time: The push time setting in the Demo uses a custom Dialog class called TimeIntervalDialog to allow users to set it (which greatly increases the code volume), and it can be set through MiPushClient.setAcceptTime(). Pause and resume can be set through pausePush() and resumePush().
  •  However, the implementation of pausing and resuming at the lower level is actually calling the setting of push time to 00:00 - 00:00 and 00:00 - 23:59and that's all, and it should also be noted that not receiving push messages outside the receiving period is just a temporary measure, once the receiving period arrives, the messages will still be delivered陆续.

Configuration of AndroidManifest file

Firstly, the lowest Android version supported by Xiaomi Push is2.2Therefore, it is necessary to

<uses-sdk android:minSdkVersion="8"/>

The following permissions are required later:

  <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" />
  <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="signature" />
  <!--Here, change com.xiaomi.mipushdemo to the app's package name-->  
  <uses-permission android:name="com.xiaomi.mipushdemo.permission.MIPUSH_RECEIVE" />
  <!--Here, change com.xiaomi.mipushdemo to the app's package name-->

Then it is necessary to register a lot of BroadcastReceiver (all are statically registered because they need to run in the background for a long time, and don't forget to register DemoMessageReceiver which inherits PushMessageReceiver)3broadcast receivers and4services.

       

<service
     android:enabled="true"
     android:process=":pushservice"
     android:name="com.xiaomi.push.service.XMPushService"/>
    <service
     android:name="com.xiaomi.push.service.XMJobService"
     android:enabled="true"
     android:exported="false"
     android:permission="android.permission.BIND_JOB_SERVICE"
     android:process=":pushservice" />
    <!--Note: This service must be3.0.1Version onwards (including3.0.1Version)added-->
    <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 be2.2.5Version onwards (including2.2.5Version)added-->
    <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>
    <receiver
      android:name="com.xiaomi.mipushdemo.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>

Just change the demo's AppId and AppKey to your own (remember to match the package name and application name), and then you can receive the corresponding push.

Mobile端移植实现

After understanding this Demo, you can移植 Xiaomi Push to your own App to implement your own needs. Pay attention to the following when移植:

  1. First, think of the package name of the application, register it on the Xiaomi Push platform, and obtain AppID and AppKey.
  2. Then add the Xiaomi Push SDK to the library.
  3. Configure permissions in the AndroidManifest file (in Android6Permissions in .0 may need to be dynamically obtained), register those Services and BroadcastReceiver
  4. Remember to initialize and register the Xiaomi Push service at the beginning of the application.
  5. Finally, you can inherit a PushMessageReceiver and do as you wish inside it.
  6. Finally, I provide a simplified Demo I wrote. After understanding the above, you can refer to my simplified移植 for the sake of completeness, as the above is too comprehensive, and we can implement it according to our actual needs.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please report any violations by email to codebox.com (replace # with @), and provide relevant evidence. Once verified, this site will immediately delete the infringing content.

You May Also Like