Fast integration of imsdk and Huawei offline push

ppchao 2021-01-14 14:45:52
fast integration imsdk huawei offline


One 、 brief introduction

Instant messaging IM End users need to be able to get the latest news at any time , However, due to the limited performance and power of mobile devices , When App In the background , In order to avoid excessive resource consumption caused by maintaining a long connection , Instant messaging IM It is recommended that you use the system level push channels provided by various manufacturers for message notification , The system level push channel has more stable system level connection than the third party push channel , You can accept push messages at any time , And the consumption of resources is greatly reduced .

This paper mainly introduces : stay tuikit How to quickly run through Huawei offline push , Realize the following function points , By the way , In the integration process , Easy to step on pits

1、 Back in the background / Killing process , Receiving offline messages

2、 Offline message transmission ext Field

3、 Click on the notification bar , Open the application interface

4、app Corner mark count refresh

Two 、 Official website integration

All the integration processes , stay IM Official website It has been introduced , Careful students refer to the official website process , You can run through the code .

This article starts directly from tuikit demo Starting with , Fast running, integrated running, Huawei offline push .

preparation :

1、 download tuikit demo;

2、 Apply for Huawei offline push account ;

3、 Reference resources IM Official website , complete im Some simple configuration of the console ;

4、 After the configuration of each id, Replace the tuikit demo In the middle

5、 Get it done

The offline push effect is shown in the figure below

3、 ... and 、 Integrated operations

1、 download tuikit demo, And run it

tuikit The necessary libraries for Huawei offline push have been integrated , We just need to replace tuikit Several configuration parameters in , It's going to work .

Several configuration parameters that need to be replaced , The following will point out one by one .

If you are already familiar with tuikit, It needs to be self integrated , You can refer to Huawei Official website integration documents

2、 Apply for Huawei offline push account

Here's the picture , Apply for a good account , download agconnect-services.json file , Replace the tuikit demo In the middle

If the package name you applied for is not com.tencent.qcloud.tim.tuikit, It's my own app Package name , You can modify demo The package name appliationId.

Huawei offline push account , Some projects require enterprise qualification , By Huawei , It's going to take a couple of working days , Remember to apply in advance .

3、im Some simple configuration of the console

Here's the picture , Put Huawei developers on the console , Applied offline push account information , Fill in IM Console , Will generate a buzid certificate .

take buzid、appid fill demo in

4、 The account configuration parameters will be pushed offline , write in demo in

The above configuration has been live , altogether 3 spot , Replace agconnect-services.json file 、 write in buzid、 write in appid.

5、 Get it done

To run , Must use release package , Signed the document sha256 Fingerprint Certificate , To be configured with Huawei console sha256 The certificate is consistent . If it's not consistent , The code runs to the time when Huawei offline push is registered , Will be submitted to the 6003 error .

HmsInstanceId.getInstance(MainActivity.this).getToken(appId, "HCM");

Four 、 Offline push principle

Here's the picture ,“ The sender ” Send a message to “ The receiving party ”, Message delivery process .

1、 Here's the news IM Server side ,IM The server will judge the receiver userid Online status of ;

2、 If the recipient is login Login status 、 And it's applied to the front desk , This background flag state is Online, The message is sent directly to the receiving end imsdk. This is online news .

3、 If the recipient is login Login status 、 But the app goes back to the background 、 The process is still alive , This background marker is also Online, The message will be sent to the receiver at the same time imsdk、 Send it to Huawei offline push background , Huawei offline push background , I'll push this message to my phone again .

4、 If the recipient is login Login status , But the app goes back to the background 、 The process was killed , This background marker is PushOnline, The message will not be sent to the receiver imsdk 了 , It will only be sent to Huawei offline push background , Huawei offline push the message back to the background , Pop up the system notification bar . This is the offline message .

5、 If the recipient has logout It's logged out , This background marker is Offline, The message won't go down , It will be in the roaming server , The receiver is within the validity period ,login Logged in , Then pull the roaming interface to get these messages .

The first 2 Point and point 3 spot , Background tags are also Online state , The push strategy is different , This is to receive imsdk terminal api The trigger : When the terminal goes back , Called doBackground Interface , The backstage will push online messages at the same time , Also push offline messages .

//APP This interface can be called when the application is detected to be out of the background , Can be used as the initial unread number of desktop application corner .
// from 5.0.1 Version start , If offline push is configured , You will receive a notification message from the manufacturer's offline push channel .
V2TIMManager.getOfflinePushManager().doBackground(param)

5、 ... and 、 Offline push , transparent transmission ext Field

Be careful :

Due to the compatibility problem of Huawei push , The content can only be transmitted in part EUI10+ Received on your device .

step 1: The sender sets custom content

Before sending messages, set the notification bar custom content of each message .

Here is Android A simple example , You can also refer to TUIKit in ChatManagerKit.java Class sendMessage() The corresponding logic in the method :

OfflineMessageContainerBean containerBean = new OfflineMessageContainerBean();
OfflineMessageBean entity = new OfflineMessageBean();
entity.content = message.getExtra().toString();
entity.sender = message.getFromUser();
entity.nickname = TUIKitConfigs.getConfigs().getGeneralConfig().getUserNickname();
entity.faceUrl = TUIKitConfigs.getConfigs().getGeneralConfig().getUserFaceUrl();
containerBean.entity = entity;
V2TIMOfflinePushInfo v2TIMOfflinePushInfo = new V2TIMOfflinePushInfo();
v2TIMOfflinePushInfo.setExt(new Gson().toJson(containerBean).getBytes());
V2TIMManager.getMessageManager().sendMessage(v2TIMMessage, userID, null,
V2TIMMessage.V2TIM_PRIORITY_DEFAULT, false, v2TIMOfflinePushInfo, V2TIMSendCallback)

step 2: The receiver gets the custom content

  • if Add Certificate Set when 【 After clicking the notification 】 The operation of is 【 Open application 】 or 【 Open the specified interface in the application 】, When you click on the message in the notification bar , The client can be in the corresponding Activity Get custom content from , You can refer to OfflineMessageDispatcher.java Class parseOfflineMessage(Intent intent) Method realization .
Bundle bundle = getIntent().getExtras();
String value = bundle.getString("ext");
Log.i(TAG, "push custom data ext: " + ext);
// Output push custom data ext:
{
"entity":{
"action":1,
"chatType":1,
"content":" This is a custom ext Message for field ",
"faceUrl":"",
"nickname":"",
"sendTime":0,
"sender":"chaoli01",
"version":1
}
}

6、 ... and 、 Click action in the notification bar

Reference resources IM Official website configuration

Here's an example , Demo Click to open the application interface :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.tencent.qcloud.tim.demo">
......
<activity
android:name="com.tencent.qcloud.tim.demo.chat.ChatActivity"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize|stateHidden">
<!-- Huawei offline push opens the in app page -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<data
android:host="com.tencent.qcloud.tim"
android:path="/detail"
android:scheme="pushscheme" />
</intent-filter>
</activity>
......
</manifest>

7、 ... and 、app Corner marker refresh

  • The mobile phone system controls the corner marker

Manufacturers push offline messages to mobile phones , The mobile phone system will trigger the refresh notification bar 、app Corner marker , Open it in the mobile phone system settings / Turn off the corner marker function , That's all right. .

An offline message , Corresponding to a notice bar message , Corresponding to a corner number +1

  • Code control corner

Let's see Huawei pushes documents offline , Description of terminal code control corner .

When you click on the notification bar message , Evoke application , Can be in app The corner marker is controlled by code , The main problem is to eliminate the corner mark ,tuikit demo There are listening messages read and reported in , Call Huawei after reading successfully api, eliminate app Corner marker , The code is as follows :

public class DemoApplication extends Application {
@Override
public void onCreate() {
DemoLog.i(TAG, "onCreate:DemoApplication");
super.onCreate();
registerActivityLifecycleCallbacks(new StatisticActivityLifecycleCallback());
}
class StatisticActivityLifecycleCallback implements ActivityLifecycleCallbacks {
private int foregroundActivities = 0;
private boolean isChangingConfiguration;
private IMEventListener mIMEventListener = new IMEventListener() {
@Override
public void onNewMessage(V2TIMMessage msg) {
String version = TIMManager.getInstance().getVersion();
int i = Integer.parseInt(version.substring(0,1));
//imsdk 5.0 Version above , When app Call when you step back doBackground,im The background will push online messages and offline messages at the same time .
// When sdk Version greater than or equal to 5.0 when , By default, the user-defined notification bar of the online message will not be triggered when the user exits the background .
if(i<4){
MessageNotification notification = MessageNotification.getInstance();
notification.notify(msg);
}
}
};
private ConversationManagerKit.MessageUnreadWatcher mUnreadWatcher = new ConversationManagerKit.MessageUnreadWatcher() {
@Override
public void updateUnread(int count) {
// Huawei pushes corner markers offline
HUAWEIHmsMessageService.updateBadge(DemoApplication.this, count);
}
};
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
DemoLog.i(TAG, "onActivityCreated bundle: " + bundle);
}
@Override
public void onActivityStarted(Activity activity) {
foregroundActivities++;
if (foregroundActivities == 1 && !isChangingConfiguration) {
// The application cuts to the front desk
DemoLog.i(TAG, "application enter foreground");
V2TIMManager.getOfflinePushManager().doForeground(new V2TIMCallback() {
@Override
public void onError(int code, String desc) {
DemoLog.e(TAG, "doForeground err = " + code + ", desc = " + desc);
}
@Override
public void onSuccess() {
DemoLog.i(TAG, "doForeground success");
}
});
TUIKit.removeIMEventListener(mIMEventListener);
ConversationManagerKit.getInstance().removeUnreadWatcher(mUnreadWatcher);
MessageNotification.getInstance().cancelTimeout();
}
isChangingConfiguration = false;
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
foregroundActivities--;
if (foregroundActivities == 0) {
// The application cuts to the background
DemoLog.i(TAG, "application enter background");
int unReadCount = ConversationManagerKit.getInstance().getUnreadTotal();
V2TIMManager.getOfflinePushManager().doBackground(unReadCount, new V2TIMCallback() {
@Override
public void onError(int code, String desc) {
DemoLog.e(TAG, "doBackground err = " + code + ", desc = " + desc);
}
@Override
public void onSuccess() {
DemoLog.i(TAG, "doBackground success");
}
});
// The app goes back to the background , Messages are converted into system notifications
TUIKit.addIMEventListener(mIMEventListener);
ConversationManagerKit.getInstance().addUnreadWatcher(mUnreadWatcher);
}
isChangingConfiguration = activity.isChangingConfigurations();
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
}
public class HUAWEIHmsMessageService extends HmsMessageService {
public static void updateBadge(final Context context, final int number) {
if (!BrandUtil.isBrandHuawei()) {
return;
}
DemoLog.i(TAG, "huawei badge = " + number);
try {
Bundle extra = new Bundle();
extra.putString("package", "com.tencent.qcloud.tim.tuikit");
extra.putString("class", "com.tencent.qcloud.tim.demo.SplashActivity");
extra.putInt("badgenumber", number);
context.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, extra);
} catch (Exception e) {
DemoLog.w(TAG, "huawei badge exception: " + e.getLocalizedMessage());
}
}
}

The refresh effect of corner marker is as follows :

8、 ... and 、 summary & common problem :

1、tuikit Huawei offline push has been integrated , Refer to above 3 Step configuration , It can run quickly, Huawei push .

2、 Register Huawei offline push account , Need enterprise qualification , It's going to take a couple of working days to approve , Please apply in advance .

3、 Huawei offline push , It's necessary to release package , Signed the document sha256 Fingerprint Certificate , To add to Huawei console .

4、 The fingerprint certificate is wrong , Run to application token when , Will report a mistake 6003

5、imsdk stay 5.0 Version above , Back to background call doBackground Interface ,im The backstage will push online consumption to app Inside imsdk, Push offline messages to manufacturers , The manufacturer pushes the offline message to the mobile phone system .tuikit The current version monitors the state of the background before the application ActivityLifecycleCallbacks, Please pay attention to the modification sdk Version judgment logic , Avoid getting back online at the same time 、 offline message .

6、 Due to the compatibility problem of Huawei push , Customize ext Field , Only in part EUI10+ Received on your device

7、 Process killed , Manufacturers push offline messages , Pop up notification bar behavior 、 Notification bar style 、 shock 、 Prompt tone 、 Corner mark increased , It's all system behavior , The control switch is in the mobile phone system settings .

8、imsdk4.8 Version above , It supports refreshing corner marks , This is im Console configuration , To configure app The first page activity The full name of .

9、 Some Huawei models , Offline message received after killing process 15+, If you increase the corner mark, you will see less occasionally 1 individual , I'm not sure . If online development encounters , It is recommended to consult Huawei offline push support personnel .

10、 The number of corners is set 0:tuikit The current logic is , Listening message read , Call Huawei to refresh the corner marker api, Set the corner number to 0. At present, the logic of reporting has been read is : When the latest message is reported as read , So all the news before this one , All set to read .

11、 Click action in the notification bar : Start the application 、 Open the web page 、 Jump to the application interface , Only need im Just modify the configuration of the console , It will take a few minutes .

12、 Configure to open the application interface , Refer to the document and configure it correctly . If it's debugging tuikit, Be careful tuikit The default is to start the app , Two code changes are required :①、DemoApplication It's on by default SplashActivity Sliding interface ,②、ChatActivity It's a default judgment intent.getExtras, If it's empty, jump to SplashActivity Sliding interface , Can be in EUI10+ Debug on your device , Enable to receive custom ext Field , Can open normally and stay in ChatActivity Interface .

13、 Writing date :2021/1/13 Japan , Some of the above functions are upgraded , Updates will be synchronized .

Original statement , This article is authorized by the author + Community publication , Unauthorized , Shall not be reproduced .

If there is any infringement , Please contact the yunjia_community@tencent.com Delete .

版权声明
本文为[ppchao]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210113183725303p.html

  1. Redis basic command
  2. Summary of MySQL articles
  3. 2、 Create k8s cluster in 5 seconds
  4. data自定义属性在jQuery中的用法
  5. Linux常见解压缩
  6. Detailed explanation of HBase basic principle
  7. 1、 Why and how to learn k8s
  8. Java advanced (29) -- HashMap set
  9. java中大文件上传
  10. Weblogic 2017-3248 analysis of Java Security
  11. Kubernetes official java client 8: fluent style
  12. Explain the function of thread pool and how to use it in Java
  13. Programming software tutorial video Encyclopedia: C + + / Java / Python / assembly / easy language (with tutorial)
  14. Description of dependency problem after javacv is updated to 1.5. X and how to reduce the size of dependency package
  15. Java reflection & dynamic agent
  16. Building Apache 2.4 + php7 + mysql8 in centos7 environment
  17. Summary of Java multithreading (1)
  18. Oracle AWR report generation
  19. Four magic functions of mybatis, don't step on the pit!
  20. A 16-year-old high school student successfully transplanted Linux to iPhone and posted a detailed guide
  21. Centos7 one click installation of JDK1.8 shell script
  22. Mounting of file system in Linux (centos7)
  23. How does serverless deal with the resource supply demand of k8s in the offline scenario
  24. Detailed explanation of HBase basic principle
  25. Spring security oauth2.0 authentication and authorization 4: distributed system authentication and authorization
  26. Redis performance Part 5 redis buffer
  27. JavaScript this keyword
  28. Summary of Java multithreading (3)
  29. Sentry(v20.12.1) K8S 云原生架构探索, SENTRY FOR JAVASCRIPT 手动捕获事件基本用法
  30. Sentry(v20.12.1) K8S 云原生架构探索, SENTRY FOR JAVASCRIPT 手动捕获事件基本用法
  31. (10) Spring from the beginning to the end
  32. Summary of Java multithreading (2)
  33. Spring source notes! From the introduction to the source code, let you really understand the source code
  34. A stormy sunny day
  35. Zookeeper (curator), the implementation of distributed lock
  36. Show the sky! Tencent T4's core Java Dictionary (framework + principle + Notes + map)
  37. Spring boot project, how to gracefully replace the blank value in the interface parameter with null value?
  38. Spring boot project, how to gracefully replace the blank value in the interface parameter with null value?
  39. docker+mysql集群+读写分离+mycat管理+垂直分库+负载均衡
  40. docker+mysql集群+读写分离+mycat管理+垂直分库+负载均衡
  41. To what extent can I go out to work?
  42. Java 使用拦截器无限转发/重定向无限循环/重定向次数过多报错(StackOverflowError) 解决方案
  43. Implementation of rocketmq message sending based on JMeter
  44. How to choose the ticket grabbing app in the Spring Festival? We have measured
  45. Implementation of rocketmq message sending based on JMeter
  46. My programmer's Road: self study java
  47. My programmer's Road: self study java
  48. All in one, one article talks about the use of virtual machine VirtualBox and Linux
  49. All in one, one article talks about the use of virtual machine VirtualBox and Linux
  50. Java 使用拦截器无限转发/重定向无限循环/重定向次数过多报错(StackOverflowError) 解决方案
  51. [Java training project] Java ID number recognition system
  52. How does serverless deal with the resource supply demand of k8s in the offline scenario
  53. Detailed explanation of HBase basic principle
  54. Explain the function of thread pool and how to use it in Java
  55. Kubernetes official java client 8: fluent style
  56. 010_MySQL
  57. Vibrant special purchases for the Spring Festival tiktok section, hundreds of good things to make the year more rich flavor.
  58. 010_MySQL
  59. Of the 4 million docker images, 51% have high-risk vulnerabilities
  60. Rocketmq CPP client visual studio 2019 compilation