All the code covered in this article is now open source on Github at github.com/xuexiangjys…
preface
Aurora push is the earliest third-party message push platform company in China, in the message push industry is relatively influential. I first came into contact with Aurora message push in 2016. At that time, the company needed to do message push business. However, since it had never done message push before, and it was too expensive to build a self-built message push platform, and no one could guarantee its stability, I chose the well-known Aurora message push at that time.
So why did I choose aurora push?
-
1. Free. The free version has a maximum push frequency of 600 times per minute for each Appkey, and there is no limit on the number of pushes, which is perfectly adequate for start-ups.
-
2. Easy to use and complete documentation. The documentation on the platform’s official website is very detailed, and the demo download is also very rich, which can be easily accessed with a few lines of code.
-
3. Rich functions. Compared with Xiaomi push, Huawei push, pigeon push, Youmeng push, aurora push function is the most complete. See my open source framework XPush for more details on these types of push.
-
4. High community support. Android, for example, supports not only Native integration, but also React Native, Flutter, Weex, HBuilder, Cordova and other hybrid development methods.
So is the aurora push really that good? Not really. I found some problems in using it:
-
1. The arrival rate of push is almost low. As long as the app is back in the background and either recycled by the system or killed by the user, it’s basically hard to get pushed again. This is naturally inferior to those mobile phone manufacturers push.
-
2. No free open vendor channel push integration. If you want to integrate vendor channel push, you need to pay to become a VIP.
But if you are new to the news push, I think the Aurora push is definitely the best choice for you. So follow me to learn how to use aurora push!
Quick Integration Guide
This article is based on jPush :3.5.4 and Jcore :2.2.6 version introduction, only introduces the latest recommended methods of use, those outdated usage here I do not introduce more, want to know can go to aurora push official documentation to view.
Preparations before integration
Before you can access the Aurora push, you need to obtain the app’s AppKey, which is the unique identifier of the app.
1. Create an aurora Push developer account
To create an Aurora Push developer account, please visit the official Aurora Push website: www.jiguang.cn/push
2. Create an application
After entering the Aurora console, click “Create Application” button and fill in the application name to create the application successfully. At the same time, click “Push Settings”, fill in your application package name in the Android section, and select save.
3. Obtain the AppKey of the application
In the Aurora console, click “App Info” in “App Settings” to get the app’s AppKey.
Introducing dependency libraries
Method one: JCenter automatic integration
Developers using JCenter automatic integration do not need to add JARS and SOS to their projects, jCenter automatically completes the dependencies; There is no need to add any JPush SDK-related configuration in androidmanifest.xml, jCenter will import it automatically.
1. Configure the build.gradle file for the project
Android {defaultConfig {applicationId "com.xxx.xxx" // Application package name registered on JPush platform.... NDK {// Select the.so library to add for the CPU type. abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a' //,'x86', 'x86_64', 'mips', 'mips64' } manifestPlaceholders = [ JPUSH_PKGNAME: defaultConfig.applicationId, JPUSH_APPKEY : JPUSH_CHANNEL: "default_developer",]}} dependencies {... / / introduce JPush rely on library implementation 'cn. Jiguang. SDK: JPush: 3.5.4' implementation 'cn. Jiguang. SDK: jcore: 2.2.6'}Copy the code
2. Configure the androidmanifest.xml file of the project
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.xuexiang.jpush"> <application> <! Jcommoncommonservice (); <service Android :name=".PushService" Android :enabled="true" Android: Exported ="false" android:process=":pushcore"> <intent-filter> <action android:name="cn.jiguang.user.service.action" /> </intent-filter> </service> <! - 2. All user-defined receives the message, you want to know the news here - > < receiver android: name = ". Core. Push. PushMessageReceiver "> < intent - filter > < action android:name="cn.jpush.android.intent.RECEIVE_MESSAGE" /> <category android:name="${applicationId}" /> </intent-filter> </receiver> </application> </manifest>Copy the code
Click on the automatic integration project source code
Method 2 Local manual integration
1. You first need to download the SDK, download address: docs. Jiguang. Cn/jpush/resou…
2. Decompress the SDK and copy the LIBS content in the compressed package to the liBS of the project
3. Configure the build.gradle file for the project
Android {defaultConfig {applicationId "com.xxx.xxx" // Application package name registered on JPush platform.... NDK {// Select the.so library to add for the CPU type. abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a' //,'x86', 'x86_64', 'mips', 'mips64' } manifestPlaceholders = [ JPUSH_PKGNAME: defaultConfig.applicationId, JPUSH_APPKEY : "Your Appkey ",// the value comes from the developer platform's Appkey JPUSH_CHANNEL: "Default_developer ",]} sourceSets {// set libs directory to so package loading directory main {jnilibs. srcDirs = ['libs']}}Copy the code
4. Configure the androidmanifest.xml file of the project
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.xxx.xxx">
<permission
android:name="${applicationId}.permission.JPUSH_MESSAGE"
android:protectionLevel="signature" />
<!-- Required 一些系统要求的权限,如访问网络等-->
<uses-permission android:name="${applicationId}.permission.JPUSH_MESSAGE" />
<uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- 用于开启 debug 版本的应用在6.0 系统上 层叠窗口权限 -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<!-- Optional for location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_TASKS" />
<application>
<!-- Required SDK核心功能-->
<activity
android:name="cn.jpush.android.ui.PushActivity"
android:configChanges="orientation|keyboardHidden"
android:exported="false"
android:theme="@android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="cn.jpush.android.ui.PushActivity" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="${applicationId}" />
</intent-filter>
</activity>
<!-- Required SDK 核心功能-->
<!-- 可配置android:process参数将PushService放在其他进程中 -->
<service
android:name="cn.jpush.android.service.PushService"
android:exported="false"
android:process=":pushcore">
<intent-filter>
<action android:name="cn.jpush.android.intent.REGISTER" />
<action android:name="cn.jpush.android.intent.REPORT" />
<action android:name="cn.jpush.android.intent.PushService" />
<action android:name="cn.jpush.android.intent.PUSH_TIME" />
</intent-filter>
</service>
<!-- since 3.0.9 Required SDK 核心功能-->
<provider
android:name="cn.jpush.android.service.DataProvider"
android:authorities="${applicationId}.DataProvider"
android:exported="false" />
<!-- since 1.8.0 option 可选项。用于同一设备中不同应用的JPush服务相互拉起的功能。 -->
<!-- 若不启用该功能可删除该组件,将不拉起其他应用也不能被其他应用拉起 -->
<service
android:name="cn.jpush.android.service.DaemonService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="cn.jpush.android.intent.DaemonService" />
<category android:name="${applicationId}" />
</intent-filter>
</service>
<!-- since 3.1.0 Required SDK 核心功能-->
<provider
android:name="cn.jpush.android.service.DownloadProvider"
android:authorities="${applicationId}.DownloadProvider"
android:exported="true" />
<!-- Required SDK核心功能-->
<receiver
android:name="cn.jpush.android.service.PushReceiver"
android:enabled="true"
android:exported="false">
<intent-filter android:priority="1000">
<!--Required 显示通知栏 -->
<action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED_PROXY" />
<category android:name="${applicationId}" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
<!-- Optional -->
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_REMOVED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
<!-- Required SDK核心功能-->
<receiver
android:name="cn.jpush.android.service.AlarmReceiver"
android:exported="false" />
<!--since 3.3.0 Required SDK核心功能-->
<activity
android:name="cn.jpush.android.service.JNotifyActivity"
android:exported="true"
android:taskAffinity="jpush.custom"
android:theme="@android:style/Theme.Translucent.NoTitleBar">
<intent-filter>
<action android:name="cn.jpush.android.intent.JNotifyActivity" />
<category android:name="${applicationId}" />
</intent-filter>
</activity>
<!-- *********************下面这两个是需要你自己定义的**************************** -->
<!-- since 3.3.0 Required SDK 核心功能-->
<!-- 1.这个是自定义Service,要继承极光JCommonService,可以在更多手机平台上使得推送通道保持的更稳定 -->
<service
android:name=".PushService"
android:enabled="true"
android:exported="false"
android:process=":pushcore">
<intent-filter>
<action android:name="cn.jiguang.user.service.action" />
</intent-filter>
</service>
<!-- 2.用户自定义接收消息器,所有你想要知道的消息都在这里-->
<receiver android:name=".core.push.PushMessageReceiver">
<intent-filter>
<action android:name="cn.jpush.android.intent.RECEIVE_MESSAGE" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
<meta-data
android:name="JPUSH_CHANNEL"
android:value="${JPUSH_CHANNEL}" />
<!-- 值来自开发者平台取得的AppKey-->
<meta-data
android:name="JPUSH_APPKEY"
android:value="${JPUSH_APPKEY}" />
</application>
</manifest>
Copy the code
Click on the manual integration project source code
Initialize the
1. Initialize JPush in Application
public class MyApp extends Application { @Override public void onCreate() { super.onCreate(); initJPush(); }} / * * * * initializes the aurora push/private void initJPush () {JPushInterface. SetDebugMode (BuildConfig. DEBUG); Jpushinterface.init (this); }Copy the code
2. (Optional) Apply for permission on the first page of the application.
Due to too many customized ROMs of Android phones, the notification bar permission of some mobile phones is disabled by default and users need to manually open it. If you do not enable the notification bar, even if you are connected to the push, you will not receive the push message.
/** @param activity */ public static void requestPermission(activity activity) {// Open the notification bar permission if (JPushInterface.isNotificationEnabled(activity) == 0) { new AlertDialog.Builder(activity) .setCancelable(false) .setMessage(" Notification permission not open, do you want to open?" ). SetPositiveButton (" yes ", (d, w) - > JPushInterface. GoToAppNotificationSettings (activity). SetNegativeButton (" no ", null) .show(); } / / apply for positioning, storage access JPushInterface requestPermission (activity); }Copy the code
Run the debug
After completing the above steps when, can be directly run the program, and view the logcat log, set the filter conditions to “JIGUANG,” if there is a “Register succeed” and “registrationId: XXXXXXXXXXXXXX”, is the integration success! As shown below:
Matters needing attention:
- Ensure that the AppKey is the same as the application package name.
- Make sure the network of running devices is available, otherwise you cannot connect to push.
Confuse configuration
Configure the proguard-rules.pro file for the project.
-dontoptimize -dontpreverify -dontwarn cn.jpush.** -keep class cn.jpush.** { *; } -dontwarn cn.jiguang.** -keep class cn.jiguang.** { *; } -keep class cn.jiguang.** { *; } -keep class * extends cn.jpush.android.service.JPushMessageReceiver{*; }Copy the code
Use of basic Functions
Initialize the
1. As mentioned above, push initialization advice is called in the custom Application onCreate, and push initialization only needs to be called once.
JPushInterface.init(Context context);
Copy the code
2. After push initialization, the platform returns a unique token, that is, the RegistrationID, which is obtained as follows:
JPushInterface.getRegistrationID(Context context);
Copy the code
3. The method to obtain the connection status of the current push is as follows:
JPushInterface.getConnectionState(Context context)
Copy the code
Click see push initialization demo source code
Push status control
1. Stop pushing. In some services, we need to temporarily suspend push, such as account logout, etc., we can call the following method:
JPushInterface.stopPush(Context context);
Copy the code
It should be noted that stopping push here is only a local client operation and will not be notified to the push service platform. It behaves like the device is offline, no push messages are received, and all other API calls to aurora push are invalid, except for the resumePush method that restores the push service.
2. Restore push. When the stop push method is called, the Aurora push service will work properly only when the restore push method is called. The method is as follows:
JPushInterface.resumePush(Context context);
Copy the code
3. Obtain the working status of push. To check whether the current push service is working, you can use the following methods:
JPushInterface.isPushStopped(Context context);
Copy the code
Click see push state control demo source code
Operation alias
Aliases are especially important in aurora push, and usually we use them the most. Our usual practice is that after the user logs in, the business platform will return a unique identification number generated by the platform as the alias of push, and then when the background needs to push, it will directly take this alias to inform the Aurora push service for message push.
1. Bind the alias.
JPushInterface.setAlias(Context context, int sequence, String alias);
Copy the code
2. Unbind aliases.
JPushInterface.deleteAlias(Context context, int sequence);
Copy the code
3. Obtain the binding alias.
JPushInterface.getAlias(Context context, int sequence);
Copy the code
Matters needing attention:
1. The sequence is an operation identification code, which is defined by users to identify operation types.
2. All of the above methods return void (all asynchronous operations), and the return of the method is in the custom message sink, which is derived from JPushMessageReceiver.
3. Alias operation results are called back in the onAliasOperatorResult method of JPushMessageReceiver. If you need to obtain alias operation results, you can override this method.
Click to see alias operation demo source code
Operation tag Tags
A tag is like a group. When we need to push a message to a specific group of people, we can use the tag to push.
1. Add Tags. This is an incremental request.
JPushInterface.addTags(Context context, int sequence, Set<String> tags);
Copy the code
2. Delete Tags.
JPushInterface.deleteTags(Context context, int sequence, Set<String> tags);
Copy the code
3. Get the tag Tags.
JPushInterface.getAllTags(Context context, int sequence);
Copy the code
4. Set the Tags Tags. This is a full request that overwrites the previously set label.
JPushInterface.setTags(Context context, int sequence, Set<String> tags);
Copy the code
5. Clear all labels.
JPushInterface.cleanTags(Context context, int sequence);
Copy the code
6. Query the status of the specified tag bound to the current user.
JPushInterface.checkTagBindState(Context context, int sequence, String tag);
Copy the code
Matters needing attention:
1. As in the alias method, sequence is also an operation identifier used to identify the operation type and is defined by the user.
2. All of the above methods return void (all asynchronous operations), and the return of the method is in the custom message sink, which is derived from JPushMessageReceiver.
3. The results of tag operations are called back in the onTagOperatorResult method of JPushMessageReceiver. If you need to obtain the results of tag operations, you can override this method.
4. The result of the checkTagBindState method is called back in JPushMessageReceiver’s onCheckTagOperatorResult method.
Click on the label manipulation demo source
Obtaining Operation Results
The operations include registration, alias (binding, unbinding, and obtaining), label (add, delete, obtain, set, clear, and status check), and mobile phone number setting. Because these operations provided by Aurora are asynchronous and the methods do not directly return results and provide callback interfaces, they can only be obtained by overriding the corresponding methods in JPushMessageReceiver.
All of the results can be obtained from the callback method provided by JPushMessageReceiver. However, JPushMessageReceiver can only be used as a forwarding station for messages, which is very inconvenient to use, so we can combine some event mechanism to handle these results and send them out as push events, so that we can simply subscribe to the event where we need to get the results. Here I take RxBus as an example to write simple, using my open source library RxUtil2
1. Define operation event types to identify operation types. You can use it with the sequence parameter mentioned above.
/** * @intdef ({TYPE_REGISTER, TYPE_UNREGISTER, TYPE_CONNECT_STATUS_CHANGED, TYPE_ADD_TAGS, TYPE_DEL_TAGS, TYPE_GET_TAGS, TYPE_BIND_ALIAS, TYPE_UNBIND_ALIAS, TYPE_GET_ALIAS}) @Retention(retentionPolicy.source) public @interface EventType {/** * register push */ int TYPE_REGISTER = 2000; /** * unregister */ int TYPE_UNREGISTER = 2001; /** * The connection status changed */ int TYPE_CONNECT_STATUS_CHANGED = 2002; /** */ int TYPE_BIND_ALIAS = 2010; /** * unbind alias */ int TYPE_UNBIND_ALIAS = 2011; /** * get alias */ int TYPE_GET_ALIAS = 2012; /** * Add tags [increment] */ int TYPE_ADD_TAGS = 2020; /** * delete tags */ int TYPE_DEL_TAGS = 2021; /** * get tags */ int TYPE_GET_TAGS = 2022; /** * Set tags [full] */ int TYPE_SET_TAGS = 2023; /** * Clean all tags */ int TYPE_CLEAN_TAGS = 2024; */ int TYPE_CHECK_TAG_BIND_STATE = 2025; }Copy the code
2. Define the carrier for pushing events.
The carrier only needs to define three member variables: mType (event type), mIsSuccess (success or failure), and mData (carried data). As follows:
/** * public final class PushEvent {public static final String KEY_PUSH_EVENT = "com.xuexiang.jpushsample.core.push.event.KEY_PUSH_EVENT"; /** * private int mType; */ private Boolean mIsSuccess; /** * private Object mData; public PushEvent(@EventType int type) { mType = type; } public PushEvent(@EventType int type, boolean isSuccess) { mType = type; mIsSuccess = isSuccess; } public PushEvent(@EventType int type, Object data) { mType = type; mData = data; } public int getType() { return mType; } public PushEvent setType(@EventType int type) { mType = type; return this; } public boolean isSuccess() { return mIsSuccess; } public PushEvent setSuccess(boolean success) { mIsSuccess = success; return this; } public Object getData() { return mData; } public PushEvent setData(Object data) { mData = data; return this; }}Copy the code
3. Process the event and send it.
Override the specified method in JPushMessageReceiver and send the result as one PushEvent after another.
Public class PushMessageReceiver extends JPushMessageReceiver {private static final String TAG = public class PushMessageReceiver extends JPushMessageReceiver {private static final String TAG = "JPush-Receiver"; / / = = = = = = = = = = = = = = = = = = = = = = are operating under the callback = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = / / @ Override public void onRegister (Context context, String registrationId) { Log.e(TAG, "[onRegister]:" + registrationId); RxBusUtils.get().post(KEY_PUSH_EVENT, new PushEvent(EventType.TYPE_REGISTER, true, registrationId)); } /* the connection status has changed ** @param context * @param isConnected Connected */ @override public void onConnected(context context, boolean isConnected) { Log.e(TAG, "[onConnected]:" + isConnected); RxBusUtils.get().post(KEY_PUSH_EVENT, new PushEvent(EventType.TYPE_CONNECT_STATUS_CHANGED, isConnected)); } /** * All tag related operations ** @param context * @param jPushMessage */ @override public void onTagOperatorResult(context) context, JPushMessage jPushMessage) { Log.e(TAG, "[onTagOperatorResult]:" + jPushMessage); PushEvent pushEvent = new PushEvent(jPushMessage.getSequence(), jPushMessage.getErrorCode() == 0) .setData(JPushInterface.getStringTags(jPushMessage.getTags())); RxBusUtils.get().post(KEY_PUSH_EVENT, pushEvent); } /** * All alias operation results ** @param context * @param jPushMessage */ @override public void onAliasOperatorResult(context context, JPushMessage jPushMessage) { Log.e(TAG, "[onAliasOperatorResult]:" + jPushMessage); PushEvent pushEvent = new PushEvent(jPushMessage.getSequence(), jPushMessage.getErrorCode() == 0) .setData(jPushMessage.getAlias()); RxBusUtils.get().post(KEY_PUSH_EVENT, pushEvent); } /** * Tag status check result ** @param context * @param jPushMessage */ @override public void onCheckTagOperatorResult(context context, JPushMessage jPushMessage) { Log.e(TAG, "[onCheckTagOperatorResult]:" + jPushMessage); PushEvent pushEvent = new PushEvent(jPushMessage.getSequence(), jPushMessage.getErrorCode() == 0) .setData(jPushMessage); RxBusUtils.get().post(KEY_PUSH_EVENT, pushEvent); }}Copy the code
4. Subscribe or cancel events where results are needed.
MPushEvent = rxbusutils.get ().onmainThread (key_push_process, PushEvent.class, this::handlePushEvent); } /** * handle push events, * @param pushEvent */ private void handlePushEvent(pushEvent) {String content = pushEvent.getData().toString(); switch (pushEvent.getType()) { case TYPE_BIND_ALIAS: if (pushEvent.isSuccess()) { tvAlias.setText(content); Xtoastutils.success (" alias [" + content + "] binding successful "); } else {xtoastutils.error (" alias [" + content + "] binding failed "); } break; Case TYPE_UNBIND_ALIAS: // Alias unbind break; Case TYPE_GET_ALIAS: // Get alias break; Case TYPE_ADD_TAGS: // Add the tag break; Case TYPE_DEL_TAGS: // Delete the tag break; Case TYPE_GET_TAGS: // Get the tag break; Case TYPE_SET_TAGS: // Set the tag break; Case TYPE_CLEAN_TAGS: // Clear the tag break; Case TYPE_CHECK_TAG_BIND_STATE: // Check label break; . default: break; } } @Override public void onDestroyView() { if (mPushEvent ! Rxbusutils.get ().unregister(KEY_PUSH_EVENT, mPushEvent); mPushEvent = null; } super.onDestroyView(); }Copy the code
Click see operation results to obtain the demo source code
See the source code for customizing JPushMessageReceiver
The message received
Custom message
Custom messages are also called transparent messages. As the name implies, the message is a set of parse format defined by the user. This message will not be displayed on the interface after receiving it. It carries the content as String, and the usual way is to pass a JSON. This flexible notification push is the most commonly used. However, it is important to note that this type of message is an in-application message and will not be received in a timely manner once the application is killed.
1. CustomMessage
The field name | type | Fields that |
---|---|---|
messageId | String | Message ID, which corresponds to the unique message number on the push platform |
message | String | The User-defined Message Content field is displayed on the notification push page |
extra | String | Save additional fields pushed down by the server. This is a JSON string that corresponds to the additional field in the “Optional Settings” on the push message interface. |
title | String | The title of the message (not very useful) |
2. Customize message reception
If you want to receive custom messages, simply override the onMessage method in JPushMessageReceiver. The CustomMessage CustomMessage body is called back in the onMessage method.
General notification message
Common notification messages are displayed on the notification bar of the system. However, if the content of the notification is empty, the notification will not be displayed on the notification bar.
1. Introduction to NotificationMessage
The field name | type | Fields that |
---|---|---|
messageId | String | Message ID, which corresponds to the unique message number on the push platform |
notificationId | int | Notification ID in the Notification bar, which is used to clear the Notification |
notificationTitle | String | The notification title corresponds to the Notification Title field on the notification page |
notificationContent | String | The notification content corresponds to the Notification Content field on the push notification page |
notificationExtras | String | Additional field corresponding to the additional field in Optional Settings on the push notification interface |
notificationTitle | String | The notification title corresponds to the Notification Title field on the notification page |
2. Receive ordinary notification messages
If you want to receive custom messages, simply override the onNotifyMessageArrived method in JPushMessageReceiver. The onNotifyMessageArrived method calls back the NotificationMessage body.
3. The notification message is clicked
When we do push notification development, we always have a requirement: we want users to click on a notification and automatically jump to a page of our application. This page could be an event promotion page, or a news or video page. At this point, we need to customize the action after the notification message is clicked.
So how do we customize what happens when a notification message is clicked? Simply override the onNotifyMessageOpened method in JPushMessageReceiver, read the parameters passed in, and then jump directly to the specified page using a page-routing mechanism such as ARouter.
Here ARE two different ways I can click on a notification message to jump to a particular screen:
1. Override onNotifyMessageOpened in JPushMessageReceiver.
Public class PushMessageReceiver extends JPushMessageReceiver {** ** click notification callback ** @param context * @param message Notification message */ @Override public void onNotifyMessageOpened(Context context, NotificationMessage message) { Log.e(TAG, "[onNotifyMessageOpened]:" + message); Intent Intent = parseNotificationMessage(intentUtils.getintent (context, intentUtils.getintent)) NotificationTransferActivity.class, null, true), message); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); ActivityUtils.startActivity(intent); } /** * Parse aurora notification messages: NotificationMessage */ public static Intent parseNotificationMessage(@NonNull Intent intent, Intent.putextra ("pageName", "NotificationMessage message ") {// this is just an example, for the time being, set the target page to" intent.putextra "("pageName"," NotificationMessage "); / / notice title intent. PutExtra (" title ", message. NotificationTitle); / / notice contents intent. PutExtra (" content ", message. NotificationContent); / / notice attached to expand contents intent. PutExtra (" extraMsg, "message. NotificationExtras); / / notice with key values of intent. PutExtra (" keyValue, "message. NotificationExtras); return intent; }}Copy the code
2. A combination of DeepLink technology and customisation (opening a specific page) with optional Settings in the notification bar.
(1) You first need to define Deeplink interception in androidmanifest.xml.
<! - notice the clicked after the jump page - > < activity android: name = ". The activity. The NotificationTransferActivity "> < intent - filter > < action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:host="com.xuexiang.jpush" android:path="/notification" android:scheme="jpush" /> </intent-filter> </activity>Copy the code
(2) in the container interface NotificationTransferActivity resolution passed parameters.
/** * Container page after notification click ** Deeplink format ** Jpush: / / com. Xuexiang. Jpush/notification? PageName = notice information display & title = this is a notification & content = this is the content of the notification & extraMsg = xxxxxxxxx&keyValue = {" param 1": "1111", "param2": "2222"} * */ @Router(path = "/push/notification/transfer") public class NotificationTransferActivity extends BaseActivity { @AutoWired String pageName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); XRouter.getInstance().inject(this); Uri uri = getIntent().getData(); Bundle bundle = getIntent().getExtras(); if (uri ! = null) {deeplink jump pageName = uri.getQueryParameter("pageName"); bundle = Utils.parseNotificationDeepLinkUri(uri, bundle); } if (! Stringutils. isEmpty(pageName)) {if (openPage(pageName, bundle) == null) {xtoastutils.toast (" page not found! ); finish(); }} else {xtoastutils.toast (" page not found!" ); finish(); } /** * DeepLink format: * Jpush: / / com. Xuexiang. Jpush/notification? PageName = xxxxx&title = this is a notification & content = this is the content of the notification & extraMsg = xxxxxxxxx&keyValue = {" param1 ": "1111", "param2": "2222"} * @param uri * @param bundle * @return */ public static Bundle parseNotificationDeepLinkUri(@NonNull Uri uri, Bundle bundle) { if (bundle == null) { bundle = new Bundle(); } bundle.putString("pageName", uri.getQueryParameter("pageName")); Bundle.putstring ("title", uri.getQueryParameter("title")); Bundle.putstring ("content", uri.getQueryParameter("content")); Bundle.putstring ("extraMsg", uri.getQueryParameter("extraMsg")); Bundle.putstring ("keyValue", uri.getQueryParameter("keyValue")); return bundle; }}Copy the code
Note: The openPage method above mainly uses my open source XPage. Its main function is to route the Fragment page and load a Fragment page.
(3) When sending the notification message, remember to set the link of custom (opening the specified page), as shown in the picture below:
- Link example: where
jpush://com.xuexiang.jpush/notification
Corresponding to the aboveAndroidManifest.xml
Is configured in.
Jpush: / / com. Xuexiang. Jpush/notification? PageName = xxxxx&title = this is a notification & content = this is the content of the notification & extraMsg = xxxxxxxxx&keyValue = {" param1 ": "1111", "param2": "2222"}Copy the code
- Example Settings:
Message reception processing
Similarly, both custom and notification messages are retrieved in the callback method of JPushMessageReceiver. Similarly, JPushMessageReceiver is at best a relay station for messages. If we want to be able to subscribe to incoming messages on any page, We can still use RxBus to send these messages out as we did above.
Here I give a brief implementation step:
1. Define the types of messages, in this case, custom messages and notification messages.
/** * message type */ @intdef ({TYPE_CUSTOM, TYPE_NOTIFICATION}) @retention (retentionPolicy.source) public @interface MessageType {/** * User-defined messages */ int TYPE_CUSTOM = 1000; /** * int TYPE_NOTIFICATION = 1001; }Copy the code
2. Define the carrier for pushing messages.
For the time being, just two member variables are defined: mType (message type) and mMessage (message data). As follows:
/** * public final class PushMessage {public static final String KEY_PUSH_MESSAGE = "com.xuexiang.jpushsample.core.push.event.KEY_PUSH_MESSAGE"; /** * message type */ private int mType; /** * private Object mMessage; public static PushMessage wrap(@MessageType int type, Object message) { return new PushMessage(type, message); } public PushMessage(@MessageType int type, Object message) { mType = type; mMessage = message; } public int getType() { return mType; } public PushMessage setType(int type) { mType = type; return this; } public <T> T getMessage() { return (T) mMessage; } public PushMessage setMessage(Object message) { mMessage = message; return this; } public String getMessageType() {switch (mType) {case TYPE_CUSTOM: return "custom message "; Case TYPE_NOTIFICATION: return "Normal notification message "; Default: return "unknown message "; }}}Copy the code
3. Receive and distribute messages.
Override the onMessage and onNotifyMessageArrived methods in JPushMessageReceiver and send the results as pushMessages.
Public class PushMessageReceiver extends JPushMessageReceiver {private static final String TAG = public class PushMessageReceiver extends JPushMessageReceiver {private static final String TAG = "JPush-Receiver"; @override public void onMessage(context context); CustomMessage message) { Log.e(TAG, "[onMessage]:" + message); RxBusUtils.get().post(KEY_PUSH_MESSAGE, PushMessage.wrap(MessageType.TYPE_CUSTOM, message)); } @override public void onNotifyMessageArrived(context context, NotificationMessage message) { Log.e(TAG, "[onNotifyMessageArrived]:" + message); RxBusUtils.get().post(KEY_PUSH_MESSAGE, PushMessage.wrap(MessageType.TYPE_NOTIFICATION, message)); }}Copy the code
In addition, if the business needs, we can add a filter process before sending the message, filter some duplicate and invalid messages, or merge the messages received at the same time.
4. Subscribe where you need to get your push notifications.
Rxbusutils.get ().onMainThread(KEY_PUSH_MESSAGE, pushmessage.class, this::handlePushMessage); */ private void handlePushMessage(PushMessage PushMessage) { tvType.setText(pushMessage.getMessageType()); tvMessage.setText(pushMessage.getMessage().toString()); } @override public void onDestroyView() {// Unsubscribe rxbusutils.get ().unregisterall (KEY_PUSH_MESSAGE); super.onDestroyView(); }Copy the code
At the end
Well, the above is the “Aurora push Android client guide – basic” all content, this article mainly introduces the aurora push the most commonly used and the most basic parts of the content, I believe that if you can fully grasp the above content, push is basically also a master. I’ll also dig into a few advanced uses of aurora push below, so stay tuned!
Related links
- Source code of this project
- Aurora Push Document
- XPush is a lightweight, pluggable Android notification push framework
- XPage is a very convenient fragment page framework
- RxUtil2 a useful RxJava2 tool class library
Wechat official account
More information, welcome to wechat search public number: [My Android open source journey]