Android SDK Advanced Tutorial

Using Tutorials of Aliases and Labels

Why do I need aliases and labels?

When pushing a message, you must specify the object to be pushed: All, an individual, or a group of people.

It’s all very well done. Just use “mass” for an application. Both the Portal and the API support sending messages to the specified appKey.

Assigning to a specific person, or a specific group of people, is relatively complicated. Because for JPush, a person is a registration ID and this registration ID has nothing to do with the developer App, or there is no meaning to the developer App.

If you want to push a message to a specific user that is meaningful to the developer app, you need to: bind the JPush registered user to the developer App user.

There are two basic ideas for this binding::

  • Save the binding relationship to the JPush server
  • Save the binding relationship to the developer application server

For the former, what we have to say here: the function of aliases and labels. This mechanism is easy to use and works for most developers.

The latter is another set of RegistrationID mechanisms provided by JPush. For developers, this set of mechanism needs an application server to maintain the binding relationship and it does not apply to ordinary developers. Android SDK 1.6.0 version begins to support the mechanism.

How to use

Working methods of alias ​​and tag mechanism are:

  • The client developer app calls the setAlias ​​or setTags API to set the relationship
  • JPush SDK saves the relationship settings to JPush Server
  • When pushing messages on the server side, specify to push to aliases or labels previously set

For the Alias ​​and Tags interfaces supported by the SDK, please refer to the corresponding document: Aliases and Tags API

There are several points to make special notes in the use process::

  • The legacy tag and alias setting interfaces provided in version 1.5.0 are no longer maintained. It is recommended that developers use the new tag and alias interfaces provided by version 3.0.7.
    • If 6002 (timeout) or 6014 (busy service) is returned in the result of the callback, it is recommended to retry. For the definition of the specific error code, please refer to the definition of the error code..
  • When pushing on the Portal or pushing an API call to an alias or tag, an error may be reported: There is no push target user. The error indicates that there is no user binding relationship for the alias or tag you pushed on JPush Server, so there is no push target. The developer need to check if the developer app has correctly called the alias and tags APIs, and if the network is not good at the time of the call, thereby the JPush SDK failed to save successfully.

Use an alias

Used to push messages to a specific user. Aliases can be considered approximately as nicknames in user accounts.

Use labels

Used to push messages to a group of people.

The tag is similar to tagging an article in a blog, that is, classifying a resource.

Dynamic tag

The APIs provided by JPush for setting labels are on the client’s side. How do developers do dynamic grouping on their own server side? For example, an enterprise OA system often needs to change departmental personnel groups. The following is a rough idea:

  • Design a custom message format (business protocol). After the app parses, you can call the JPush SDK setAliasAndTags API to reset the label (grouping)
    • Example: {“action”:”resetTags”, “newTags”:[“dep_level_1”:”Company A”, “dep_level_2”:”Technology Department”, “dep_level_3”:”Android Development Team”, “address”:” Shenzhen”, “lang”:”zh”]}
  • To dynamically set the group, push this custom message to the specified user
    • Use the alias mechanism to push to the specified user.
  • The client app calls the JPush SDK API to set a new label

Exception Handling of Aliases and Tag Settings

Due to the unstable network connection, there is a certain probability that the JPush SDK will fail to set aliases and tags. If App developers properly handle the setup failures, the impact of occasional failures to normal use of the application is limited.

The following uses the Android SDK as an example. For more details, see example.

The basic idea:

  • When the setting is successful, write the status to the SharePreference and do not need to set later
  • If encounters a 6002 timeout, please retry a little later.
  1. // 这是来自 JPush Example 的设置别名的 Activity 里的代码,更详细的示例请参考JPush Example。一般 App 的设置的调用入口,在任何方便的地方调用都可以。
  2. private void handleAction(int sequence,TagAliasBean tagAliasBean) {
  3. if(tagAliasBean == null){
  4. Log.w(TAG,"tagAliasBean was null");
  5. return;
  6. }
  7. if(tagAliasBean.isAliasAction){
  8. switch (tagAliasBean.action){
  9. case ACTION_GET:
  10. JPushInterface.getAlias(getApplicationContext(),sequence);
  11. break;
  12. case ACTION_DELETE:
  13. JPushInterface.deleteAlias(getApplicationContext(),sequence);
  14. break;
  15. case ACTION_SET:
  16. JPushInterface.setAlias(getApplicationContext(),sequence,tagAliasBean.alias);
  17. break;
  18. default:
  19. Log.w(TAG,"unsupport alias action type");
  20. return;
  21. }
  22. }else {
  23. //tag operation
  24. }
  25. }

Tutorial of Custom Notification Bar Style

About custom notification bar styles

When the JPush notification is pushed to the client, the default settings of the mobile phone are used to display the notification bar, including ringtones, vibrations, and the like.

If the developer wants to achieve the following results, he need to use the “Customize Notification Bar Style” function:

  • The notification bar style uses different settings than the default, for example you want to control:
    • Ringing, shaking
    • Icon
    • Replace the default notification bar style

Push message specifies the notification bar style number

The notification bar style is only represented by a number (number) when it is pushed down on the server side.

The style number of the push notification should be set on the client side with a custom notification bar style.

If the style number on the notification does not exist in the client side, please use the default style of the notification bar.


When you do not use a custom notification bar style, this number defaults to 0. To use a custom notification bar style, the number should be greater than 0 and less than 1000.

When sending a notification on the portal, the bottom “optional” section expands and the developer can specify the style number of the notification that is currently being pushed. As shown below:

Android SDK Advanced Tutorial - 图1

Client setting notification bar style

The custom notification bar style is set on the client. Please refer to the Notification Bar Style Customization API to see the supported features.

Design of custom notification bar style

  • There is a PushNotificationBuilder concept. Developers use the setPushNotificationBuilder method to specify a number for some type of PushNotificationBuilder.
  • setPushNotificationBuilder can be called anywhere after JPushInterface.init() . It can be triggered to call by the logic of developer apps, or it can be called at initialization time.
  • Only need to set once, JPush SDK will remember this setting. The next time a push notification is received, the PushNotificationBuilder is found and executed based on the number specified in the notification.

API - setDefaultPushNotificationBuilder sets Default

This API changes the default notification bar style with the number 0.

API - setPushNotificationBuilder Specify Number

This API is a developer-assigned number and sets up a custom PushNotificationBuilder.

Example - Basic PushNotificationBuilder

Customize notification styles such as sound, vibration, and flash.

  1. BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(MainActivity.this);
  2. builder.statusBarDrawable = R.drawable.jpush_notification_icon;
  3. builder.notificationFlags = Notification.FLAG_AUTO_CANCEL
  4. | Notification.FLAG_SHOW_LIGHTS; //设置为自动消失和呼吸灯闪烁
  5. builder.notificationDefaults = Notification.DEFAULT_SOUND
  6. | Notification.DEFAULT_VIBRATE
  7. | Notification.DEFAULT_LIGHTS; // 设置为铃声、震动、呼吸灯闪烁都要
  8. JPushInterface.setPushNotificationBuilder(1, builder);

Customize notification styles with buttons (3.0.0 and later versions of sdk only support this style, and this style does not display properly on some models that differ from the Android native system).

  1. MultiActionsNotificationBuilder builder = new MultiActionsNotificationBuilder(PushSetActivity.this);
  2. //添加按钮,参数(按钮图片、按钮文字、扩展数据)
  3. builder.addJPushAction(R.drawable.jpush_ic_richpush_actionbar_back, "first", "my_extra1");
  4. builder.addJPushAction(R.drawable.jpush_ic_richpush_actionbar_back, "second", "my_extra2");
  5. builder.addJPushAction(R.drawable.jpush_ic_richpush_actionbar_back, "third", "my_extra3");
  6. JPushInterface.setPushNotificationBuilder(2, builder);

Example - Advanced Custom PushNotificationBuilder

Based on the underlying PushNotificationBuilder, the Layout of the Notification can be further customized.

Customer_notitfication_layout as an example here can be found under /res/layout/ of our example project. You can use your own layout.


CustomPushNotificationBuilder builder = new CustomPushNotificationBuilder(MainActivity.this, R.layout.customer_notitfication_layout, R.id.icon, R.id.title, R.id.text); // 指定定制的 Notification Layout builder.statusBarDrawable = R.drawable.your_notification_icon; // 指定最顶层状态栏小图标 builder.layoutIconDrawable = R.drawable.your_2_notification_icon; // 指定下拉状态栏时显示的通知图标 JPushInterface.setPushNotificationBuilder(2, builder); #### Notification bar style definition does not meet the requirements? The functionality of the custom notification bar style provided above is limited. For example: Android SDK 4.0 and later Notification supports the specified Style, and there is no JPush SDK could support this complex notification style definition. Or you want to customize the complex notification style, but are reluctant to use the advanced customization features of custom notification bar described above. It is recommended not to use the notification function provided by JPush but to use the custom message function. That is, after the custom message is pushed to the client, the App retrieves the entire content of the custom message, and then the App itself writes a code to display the notification. Please refer to the document: Notifications vs. Custom Messages. Notification vs Custom Messages JPush includes two types of push notifications and custom messages. This article describes their differences and suggested application scenarios. ### The difference between the two - functional perspective #### Notice Notification refers to a notification message that will appear on the notification bar (status bar) of the mobile phone. This is the basic function of Android/iOS. The notification is mainly used to prompt the user. A notice can be a plain text simply filled in. Application plus notifications help increase the activity of the application. #### Custom message The custom message is not a notification. By default, the SDK will not be displayed on the notification bar. JPush is only responsible for the transparent transmission to the SDK. Its content and presentation form are completely defined by the developers themselves. Custom messages are mainly used for the application’s internal business logic and special display requirements. ### The difference between the two - developer use perspective #### Notice In simple scenarios, the user can write no code, and the SDK is responsible for the default display of the effect and the main interface for opening the application when the default user clicks. The JPush Android SDK provides APIs for developers to customize the effect of notification bar. Please refer to: Customize Notification Bar Style Tutorials. It also provides Receiver to allow you to customize the behaviors when receiving a notification and when the user clicks notification. #### Custom message The SDK will not display custom messages to the notification bar. So when debugging, you need to go to the log to see the custom message pushed by the server. The received message of custom message must be processed by the Receiver written by developers.

Note:

When the custom message content msg_content is empty, the SDK does not broadcast the message, so that the app cannot receive the pushed message. Thereby, it is recommended to add content when using custom message push.

Use notice

Please refer to the following sample code.

  1. public class MyReceiver extends BroadcastReceiver {
  2. private static final String TAG = "MyReceiver";
  3. private NotificationManager nm;
  4. @Override
  5. public void onReceive(Context context, Intent intent) {
  6. if (null == nm) {
  7. nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  8. }
  9. Bundle bundle = intent.getExtras();
  10. Logger.d(TAG, "onReceive - " + intent.getAction() + ", extras: " + AndroidUtil.printBundle(bundle));
  11. if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
  12. Logger.d(TAG, "JPush用户注册成功");
  13. } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
  14. Logger.d(TAG, "接受到推送下来的自定义消息");
  15. } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
  16. Logger.d(TAG, "接受到推送下来的通知");
  17. receivingNotification(context,bundle);
  18. } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
  19. Logger.d(TAG, "用户点击打开了通知");
  20. openNotification(context,bundle);
  21. } else {
  22. Logger.d(TAG, "Unhandled intent - " + intent.getAction());
  23. }
  24. }
  25. private void receivingNotification(Context context, Bundle bundle){
  26. String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
  27. Logger.d(TAG, " title : " + title);
  28. String message = bundle.getString(JPushInterface.EXTRA_ALERT);
  29. Logger.d(TAG, "message : " + message);
  30. String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
  31. Logger.d(TAG, "extras : " + extras);
  32. }
  33. private void openNotification(Context context, Bundle bundle){
  34. String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
  35. String myValue = "";
  36. try {
  37. JSONObject extrasJson = new JSONObject(extras);
  38. myValue = extrasJson.optString("myKey");
  39. } catch (Exception e) {
  40. Logger.w(TAG, "Unexpected: extras is not a valid json", e);
  41. return;
  42. }
  43. if (TYPE_THIS.equals(myValue)) {
  44. Intent mIntent = new Intent(context, ThisActivity.class);
  45. mIntent.putExtras(bundle);
  46. mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  47. context.startActivity(mIntent);
  48. } else if (TYPE_ANOTHER.equals(myValue)){
  49. Intent mIntent = new Intent(context, AnotherActivity.class);
  50. mIntent.putExtras(bundle);
  51. mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  52. context.startActivity(mIntent);
  53. }
  54. }
  55. }

Use custom messages

To use custom messages, you must write code in the client app to receive the broadcast of the JPush SDK, to obtain the pushed message content. For details, please refer to the document: Receiver.

The following code is from chat.

  1. public class TalkReceiver extends BroadcastReceiver {
  2. private static final String TAG = "TalkReceiver";
  3. private NotificationManager nm;
  4. @Override
  5. public void onReceive(Context context, Intent intent) {
  6. if (null == nm) {
  7. nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  8. }
  9. Bundle bundle = intent.getExtras();
  10. Logger.d(TAG, "onReceive - " + intent.getAction() + ", extras: " + AndroidUtil.printBundle(bundle));
  11. if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
  12. Logger.d(TAG, "JPush用户注册成功");
  13. } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
  14. Logger.d(TAG, "接受到推送下来的自定义消息");
  15. // Push Talk messages are push down by custom message format
  16. processCustomMessage(context, bundle);
  17. } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
  18. Logger.d(TAG, "接受到推送下来的通知");
  19. receivingNotification(context,bundle);
  20. } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
  21. Logger.d(TAG, "用户点击打开了通知");
  22. openNotification(context,bundle);
  23. } else {
  24. Logger.d(TAG, "Unhandled intent - " + intent.getAction());
  25. }
  26. }
  27. private void processCustomMessage(Context context, Bundle bundle) {
  28. String title = bundle.getString(JPushInterface.EXTRA_TITLE);
  29. String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
  30. if (StringUtils.isEmpty(title)) {
  31. Logger.w(TAG, "Unexpected: empty title (friend). Give up");
  32. return;
  33. }
  34. boolean needIncreaseUnread = true;
  35. if (title.equalsIgnoreCase(Config.myName)) {
  36. Logger.d(TAG, "Message from myself. Give up");
  37. needIncreaseUnread = false;
  38. if (!Config.IS_TEST_MODE) {
  39. return;
  40. }
  41. }
  42. String channel = null;
  43. String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
  44. try {
  45. JSONObject extrasJson = new JSONObject(extras);
  46. channel = extrasJson.optString(Constants.KEY_CHANNEL);
  47. } catch (Exception e) {
  48. Logger.w(TAG, "Unexpected: extras is not a valid json", e);
  49. }
  50. // Send message to UI (Webview) only when UI is up
  51. if (!Config.isBackground) {
  52. Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
  53. msgIntent.putExtra(Constants.KEY_MESSAGE, message);
  54. msgIntent.putExtra(Constants.KEY_TITLE, title);
  55. if (null != channel) {
  56. msgIntent.putExtra(Constants.KEY_CHANNEL, channel);
  57. }
  58. JSONObject all = new JSONObject();
  59. try {
  60. all.put(Constants.KEY_TITLE, title);
  61. all.put(Constants.KEY_MESSAGE, message);
  62. all.put(Constants.KEY_EXTRAS, new JSONObject(extras));
  63. } catch (JSONException e) {
  64. }
  65. msgIntent.putExtra("all", all.toString());
  66. context.sendBroadcast(msgIntent);
  67. }
  68. String chatting = title;
  69. if (!StringUtils.isEmpty(channel)) {
  70. chatting = channel;
  71. }
  72. String currentChatting = MyPreferenceManager.getString(Constants.PREF_CURRENT_CHATTING, null);
  73. if (chatting.equalsIgnoreCase(currentChatting)) {
  74. Logger.d(TAG, "Is now chatting with - " + chatting + ". Dont show notificaiton.");
  75. needIncreaseUnread = false;
  76. if (!Config.IS_TEST_MODE) {
  77. return;
  78. }
  79. }
  80. if (needIncreaseUnread) {
  81. unreadMessage(title, channel);
  82. }
  83. NotificationHelper.showMessageNotification(context, nm, title, message, channel);
  84. }
  85. // When received message, increase unread number for Recent Chat
  86. private void unreadMessage(final String friend, final String channel) {
  87. new Thread() {
  88. public void run() {
  89. String chattingFriend = null;
  90. if (StringUtils.isEmpty(channel)) {
  91. chattingFriend = friend;
  92. }
  93. Map<String, String> params = new HashMap<String, String>();
  94. params.put("udid", Config.udid);
  95. params.put("friend", chattingFriend);
  96. params.put("channel_name", channel);
  97. try {
  98. HttpHelper.post(Constants.PATH_UNREAD, params);
  99. } catch (Exception e) {
  100. Logger.e(TAG, "Call pushtalk api to report unread error", e);
  101. }
  102. }
  103. }.start();
  104. }
  105. }
  • 19000
  • 3000-3020
  • 7000-7020
  • 8000-8020