Push and Message Tip
Update time: 2021/12/03 16:49:07
Push notifications
To improve message delivery rate, CommsEase has made great efforts in keeping process alive. However, manufacturers' deep custom ROM provides more strict restrictions for the Android system in domestic environment. As a result, it is impossible to keep permanently alive for all mobile versions, for which power consumption will increase.
Therefore, CommsEase introduces manufacturer push. If the client SDK cannot connect with CommsEase server properly when users clear app process and instable network, manufacturer system level push will be used to inform users of new message.
The advantage of mobile system manufacturer push (for example, MIUI, HUAWEI, VIVO, OPPO, Meizu) is stable system-level long connection which help users receive push at any time. When push is tested, you can compile apk and install it to mobile phone that supports system push; stop processing after successful login; send messages by other accounts and view received push.
Xiaomi Push
Prerequisites
-
For auxiliary package of integration push, see description in SDK integration.
push
-
Go to Xiaomi Push notification to register account and pass certification, create app and get pushed AppID, AppKey and AppSecret.
-
Go to CommsEase console -> Certificate management -> Android push certificate to add a push certificate.
- Import Xiaomi Push SDK into the project. Current compatible version is
MiPush_SDK_Client_3_8_5
.
Integration configuration
- AndroidManifest.xml configuration
There are two manifests changed into the developer's app package name. The configured entries must not be added again.
<!--Configure permissions; entries configured are not required to be added -->
<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.VIBRATE"/>
<!--Modify the package name of developer app in the following two {Your package name} -->
<permission android:name="{Your Package name}.permission.MIPUSH_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="{Your package name}.permission.MIPUSH_RECEIVE" />
The following configurations are copied to AndroidManifest.xml, without any change.
<!--Configured service and recipient-->
<service
android:name="com.xiaomi.push.service.XMPushService"
android:enabled="true"
android:process=":mixpush"/>
<service
android:name="com.xiaomi.push.service.XMJobService"
android:enabled="true"
android:exported="false"
android:permission="android.permission.BIND_JOB_SERVICE"
android:process=":mixpush" />
<!--Note: the service must be added following the version 3.0.1 (inclusive)-->
<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: the service must be added following the version 2.2.5 (inclusive)-->
<recipient
android:exported="true"
android:name="com.xiaomi.push.service.recipients.NetworkStatusReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</recipient>
<recipient
android:exported="false"
android:process=":mixpush"
android:name="com.xiaomi.push.service.recipients.PingReceiver" >
<intent-filter>
<action android:name="com.xiaomi.push.PING_TIMER" />
</intent-filter>
</recipient>
<recipient
android:name="com.netease.nimlib.mixpush.mi.MiPushReceiver"
android:exported="true">
<intent-filter android:priority="0x7fffffff">
<action android:name="com.xiaomi.mipush.RECEIVE_MESSAGE"/>
<action android:name="com.xiaomi.mipush.MESSAGE_ARRIVED"/>
<action android:name="com.xiaomi.mipush.ERROR"/>
</intent-filter>
</recipient>
- Configure certificate information
In the SDK initialization process, certificate information related to push must be configured to SDKOptions.mixPushConfig
.
Example:
MixPushConfig config = new MixPushConfig();
// Input AppId and AppKey got from the push platform of Xiaomi
config.xmAppId = "xxxx";
config.xmAppKey = "xxxx";
// Input the Xiaomi push certificate name on CommsEase console
config.xmCertificateName = "xxxx";
...
options.mixPushConfig = config;
If code obfuscation is enabled to create an app, please add the following to proguard.cfg:
-dontwarn com.xiaomi.push.**
-keep class com.xiaomi.** {*;}
So far, Xiaomi Push access has been completed. Now, push notification can be tested on MIUI devices.
Push compatibility
If the developer's business system should also support Xiaomi Push, you should consider whether Xiaomi Push in their service system is compatible with Xiaomi Push in CommsEase messages. Besides, the following two requirements must be met, and the rest of configurations and logics are not updated.
- For Xiaomi Push, MIUI SDK requires the developer to customize
BroadcastReceiver
succeeded fromPushMessageReceiver
and register toAndroidManifest.xml
and receive push notifications. For MIUI special processing, message cannot be received if multipleBroadcastReceiver
succeeded fromPushMessageReceiver
are registered synchronously. To ensure compatibility between Xiaomi Push in the developer's business system and Xiaomi Push in CommsEase message, the developer must create a new broadcast recipient that is succeeded fromMiPushMessageReceiver
instead of originalPushMessageReceiver
.MiPushMessageReceiver
is provided by CommsEase. The push notifications are received byMiPushReceiver
. If it is the push notifications in the developer's business system, thenMiPushReceiver
will transmit message toMiPushMessageReceiver
.
/**
* The following methods operate in the non-UI thread, which corresponds to the PushMessageReceiver method of Xiaomi.
* If developers need access to Xiaomi push, the PushMessageReceiver should be changed to MiPushMessageReceiver
*/
public class MiPushMessageReceiver extends BroadcastReceiver{
@Override
public final void onReceive(Context context, Intent intent) {
}
public void onReceivePassThroughMessage(Context context, MiPushMessage message) {
}
public void onNotificationMessageClicked(Context context, MiPushMessage message) {
}
public void onNotificationMessageArrived(Context context, MiPushMessage message) {
}
public void onReceiveRegisterResult(Context context, MiPushCommandMessage message) {
}
public void onCommandResult(Context context, MiPushCommandMessage message) {
}
}
- After the broadcast recipient is changed to succeed from
MiPushMessageReceiver
, the broadcast inAndroidManifest
is configured as below. Developers only need to replace the broadcast nameMiPushMessageReceiver
with their own broadcast name. In addition, please do not configurepriority
for this receiver.
<recipient android:name="xxx.MiPushMessageReceiver">
<intent-filter>
<action android:name="com.xiaomi.mipush.RECEIVE_MESSAGE"/>
<action android:name="com.xiaomi.mipush.MESSAGE_ARRIVED"/>
<action android:name="com.xiaomi.mipush.ERROR"/>
</intent-filter>
</recipient>
Huawei push
From new version HMS package, HUAWEI Push applies to system connection solution similar to Xiaomi Push, but depends on EMUI version and HUAWEI mobile service version. Many tests indicate that EMUI4.1 and above can receive push stably when they accommodate HUAWEI mobile service version 4.0.4.301` and above simultaneously.
Prerequisites
- For auxiliary package of integration push, see description in SDK integration.
push
See Huawei Development Preparations for the following work:
-
Go to Huawei message push service to register account and pass certification, create an app and get
APP ID
andAPP SECRET
. -
Go to "CommsEase console - Certificate management - Android push certificate" to add push certificate.
-
Copy
agconnect-services.json
file to app root directory, configuremaven
storage address ofHMSSDK
, and add compiling dependencies. -
Import Huawei pushed SDK into the project. Current compatible version is `com.huawei.hms:push:4.0.4.301.
Integration configuration
First, in Application#onCreate
, following operations are completed under the main process:
public class NimApplication extends Application {
...
@Override
public void onCreate() {
...
if (NIMUtil.isMainProcess(this)) {
...
// Add the following code herein
com.huawei.hms.support.common.ActivityMgr.INST.init(this);
...
}
}
}
- AndroidManifest.xml configuration
<service
android:name="com.netease.nimlib.mixpush.hw.HWPushService"
android:exported="false">
<intent-filter>
<action android:name="com.huawei.push.action.MESSAGING_EVENT" />
</intent-filter>
</service>
- Configure certificate information
In the SDK initialization process, certificate information related to push must be configured to SDKOptions.mixPushConfig
.
MixPushConfig config = new MixPushConfig();
// Input app ID of Huawei push
config.hwAppId = "xxxx";
// Input the Huawei push certificate name on CommsEase console
config.hwCertificateName = "xxxx";
...
options.mixPushConfig = config;
If code obfuscation is enabled to create an app, you must add obfuscated configuration in proguard.cfg
to exclude HMS SDK.
-ignorewarning
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keepattributes SourceFile,LineNumberTable
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
If the developer has enabled AndResGuard, AndResGuard whitelist must be added to obfuscated configuration files.
"R.string.hms*",
"R.string.connect_server_fail_prompt_toast",
"R.string.getting_message_fail_prompt_toast",
"R.string.no_available_network_prompt_toast",
"R.string.third_app_*",
"R.string.upsdk_*",
"R.layout.hms*",
"R.layout.upsdk_*",
"R.drawable.upsdk*",
"R.color.upsdk*",
"R.dimen.upsdk*",
"R.style.upsdk*",
"R.string.agc*"
So far, Huawei push access has been completed and push notification can be tested on Huawei devices that accommodate required conditions.
Push compatibility
If the developer's business system must also access to Huawei push, then they must consider whether Huawei push in their service system is compatible with Huawei push in CommsEase message. Besides, the following two requirements must be met, and rest configurations and logics are not updated.
- For Huawei push, Huawei SDK requires developers to customize a
Service
succeeded fromHmsMessageService
and register it toAndroidManifest.xml
and receive push notifications. Developers must change their Huawei push service to succeed fromHWPushMessageService
instead of originalHmsMessageService
. Developers must independently process push notifications in their system, unlike CommsEase.
/**
* The following methods operate in the non-UI thread, which corresponds to the PushMessageReceiver method of Xiaomi.
* When developers need access to HuaWei push, HmsMessageService should be changed to HWPushMessageService, without any change to others
*/
public class HWPushMessageService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onNewToken(String token) {
MixPushPlatforms.getPushPlatform(PushType.HUA_WEI).onToken(token);
}
/**
* Pass-through message, for which users need to pop out notifications
*
* @param remoteMessage
*/
public void onMessageReceived(RemoteMessage remoteMessage) {
}
public void onMessageSent(String s) {
}
public void onDeletedMessages() {
}
public void onSendError(String var1, Exception var2) {
}
}
- After the service is changed to succeed from
HWPushMessageService
, the service inAndroidManifest
is configured as below. Developers only need to replace the service nameHWPushMessageService
with their own service name.
<service
android:name="xxx.HWPushMessageService"
android:exported="false">
<intent-filter>
<action android:name="com.netease.nimlib.mixpush.hw.action.MESSAGING_EVENT" />
</intent-filter>
</service>
VIVO push
Prerequisites
-
For auxiliary package of integration push, see the description of
push
in SDK integration. -
Go to vivo Push notification to register account and pass certification, create app and get AppID, AppKey, and AppSecret.
-
Go to "CommsEase console - Certificate management - Android push certificate" to add push certificate.
-
Import VIVO pushed SDK into the project. Current compatible version is vivo_pushsdk_v2.3.4.
Integration configuration
- AndroidManifest.xml configuration
The following configurations are copied to AndroidManifest.xml.
<!-- Configured service, activity, recipient-->
<service
android:name="com.vivo.push.sdk.service.CommandClientService"
android:exported="true"/>
<activity
android:name="com.vivo.push.sdk.LinkProxyClientActivity"
android:exported="false"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.Translucent.NoTitleBar"/>
<recipient android:name="com.netease.nimlib.mixpush.vivo.VivoPushReceiver">
<intent-filter>
<!-- Receive push notifications -->
<action android:name="com.vivo.pushclient.action.RECEIVE"/>
</intent-filter>
</recipient>
- Configure certificate information
Add configuration app_id and api_key in AndroidManifest.xml:
<meta-data
android:name="com.vivo.push.api_key"
android:value="{your vivo push app key}"/>
<meta-data
android:name="com.vivo.push.app_id"
android:value="{your vivo push app id}"/>
In the SDK initialization process, certificate information related to push must be configured to SDKOptions.mixPushConfig
.
// Input vivo push certificate name on CommsEase console
config.vivoCertificateName = "DEMO_VIVO_PUSH";
...
options.mixPushConfig = config;
If code obfuscation is enabled to create an app, please add the following to proguard.cfg
:
-dontwarn com.vivo.push.**
-keep class com.vivo.push.**{*; }
-keep class com.vivo.vms.**{*; }
-keep class com.netease.nimlib.mixpush.vivo.VivoPush* {*;}
-keep class com.netease.nimlib.mixpush.vivo.VivoPushReceiver{*;}
So far, VIVO push access has been completed and push notification can be tested on VIVO devices.
Push compatibility
- Developers need to create a new broadcast recipient and change to succeed from
VivoPushMessageReceiver
instead of originalOpenClientPushMessageReceiver
.VivoPushMessageReceiver
is provided by CommsEase.
/**
* The following methods operate in the non-UI thread, which corresponds to the OpenClientPushMessageReceiver method of VIVO SDK.
* When developers need access to Vivo push, OpenClientPushMessageReceiver should be changed to VivoPushMessageReceiver, without any change to others
*/
public class VivoPushMessageReceiver extends BroadcastReceiver {
@Override
public final void onReceive(Context context, Intent intent) {
}
public void onNotificationMessageClicked(Context context, UPSNotificationMessage upsNotificationMessage) {
}
public void onReceiveRegId(Context context, String s) {
}
}
- After the broadcast recipient is changed to succeed from
VivoPushMessageReceiver
, the broadcast inAndroidManifest
is configured as below. Developers only need to replace the broadcast nameVivoPushMessageReceiver
with their own broadcast name. In addition, please do not configurepriority
for this receiver.
<recipient android:name="xxx.VivoPushMessageReceiver">
<intent-filter>
<action android:name="com.vivo.pushclient.action.RECEIVE" />
</intent-filter>
</recipient>
Configuring message types
VIVO push notifications includes Operation message and system message, so that message type must be specified in the push process. Otherwise, push notifications will be considered as operation message processing.
The configuration point of the field is pushPayload of message body. You only need to add Map with vivoField
as key or JsonObject data. See VIVO Document for data format.
- Example
int classification = vivoClassificationCheckBox.isChecked() ? 1 : 0;
Map<String, Object> pushPayload = msg.getPushPayload();
pushPayload = pushPayload == null ? new HashMap<>() : pushPayload;
//vivoField
Map<String, Object> vivoField = new HashMap<>();
vivoField.put("classification", classification);
pushPayload.put("vivoField", vivoField);
OPPO push
Prerequisites
-
For auxiliary package of integration push, see the description of
push
in SDK integration. -
Go to OPPO PUSH Platform to register account and pass certification, create app and get AppId, AppKey, AppSecret and MasterSecret. Please distinguish AppSercet and MasterSecret.
-
Go to "CommsEase console - Certificate management - Android push certificate" to add push certificate. Note: You can view MasterSecret in
OPPO Push Operation Platform> Configuration Management> Application Configuration
. -
See OPPO PUSH SDK interface document to import OPPO pushed SDK into the project. Current compatible version is
com.heytap.msp-push-2.1.0.aar
.
Integration configuration
First, in Application#onCreate
, following operations are completed under the main process:
public class NimApplication extends Application {
...
@Override
public void onCreate() {
...
if (NIMUtil.isMainProcess(this)) {
...
// Add the following code herein
com.heytap.msp.push.HeytapPushadministrator.init(this, true);
...
}
}
}
- AndroidManifest.xml configuration
Statement of push permission:
<!-- oppo push configuration permission-->
<uses-permission android:name="com.coloros.mcs.permission.RECIEVE_MCS_MESSAGE"/>
<uses-permission android:name="com.heytap.mcs.permission.RECIEVE_MCS_MESSAGE"/>
<!--Oppo push configuration item; the following items should be configured-->
<service
android:name="com.netease.nimlib.mixpush.oppo.OppoPushService"
android:permission="com.coloros.mcs.permission.SEND_MCS_MESSAGE">
<intent-filter>
<action android:name="com.coloros.mcs.action.RECEIVE_MCS_MESSAGE"/>
</intent-filter>
</service> <!-- compatible with the version below Q-->
<service
android:name="com.netease.nimlib.mixpush.oppo.OppoAppPushService"
android:permission="com.heytap.mcs.permission.SEND_PUSH_MESSAGE">
<intent-filter>
<action android:name="com.heytap.mcs.action.RECEIVE_MCS_MESSAGE"/>
<action android:name="com.heytap.msp.push.RECEIVE_MCS_MESSAGE"/>
</intent-filter>
</service> <!--compatible with version Q-->
- Configure certificate information
In the SDK initialization process, certificate information related to push must be configured to SDKOptions.mixPushConfig
.
config.oppoAppId = "xxxx";
config.oppoAppKey = "xxxxxx";
// Notice the difference between AppSercet and MasterSecret
config.oppoAppSercet = "xxxxxxx";
// Input oppo push certificate name configured on CommsEase console
config.oppoCertificateName = "xxxx";
...
options.mixPushConfig = config;
If code obfuscation is enabled to create an app, please add the following to proguard.cfg.
-keep public class * extends android.app.Service
OPPO push does not support messages of transparent transmission.
So far, OPPO push access has been completed and push notification can be tested on OPPO devices.
Push compatibility
Similar to Xiaomi Push compatibility.
- Developers should create a new broadcast recipient and change to succeed from
OppoPushMessageService
andOppoAppPushMessageService
instead of originalPushService
andAppPushService
.OppoPushMessageService
andOppoAppPushMessageService
are provided by CommsEase.
/**
* The following methods operate in the non-UI thread, which corresponds to the PushService method of Oppo.
* When developers need access to Oppo push, PushService should be changed to OppoPushMessageService, without any change to others
*/
public class OppoPushMessageService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* Ordinary message
* @param context
* @param appMessage
*/
public void processMessage(Context context, AppMessage appMessage) {
}
/**
* oppo currently does not support messages of transparent transmission
*
* @param context
* @param sptDataMessage
*/
public void processMessage(Context context, SptDataMessage sptDataMessage) {
}
}
/**
* The following methods operate in the non-UI thread, which corresponds to the PushService method of Oppo.
* When developers need access to Oppo push, AppPushService should be changed to OppoAppPushMessageService, without any change to others
*/
public class OppoAppPushMessageService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* Ordinary message
* @param context
* @param appMessage
*/
public void processMessage(Context context, AppMessage appMessage) {
}
/**
* oppo currently does not support messages of transparent transmission
*
* @param context
* @param sptDataMessage
*/
public void processMessage(Context context, SptDataMessage sptDataMessage) {
}
}
- After the service is changed to succeed from
OppoPushMessageService
andOppoAppPushMessageService
, the service inAndroidManifest
is configured as below. Developers only need to replace the service nameOppoService
with their own service name.
<service android:name="xxx.OppoService"
android:permission="com.coloros.mcs.permission.SEND_MCS_MESSAGE">
<intent-filter>
<action android:name="com.coloros.mcs.action.RECEIVE_MCS_MESSAGE"/>
</intent-filter>
</service>
Meizu push
Prerequisites
-
For auxiliary package of integration push, see
push
of description in SDK integration. -
Go to Meizu Push notification to register account and pass certification, create app and get AppID, AppKey, and AppSecret.
-
Go to "CommsEase console - Certificate management - Android push certificate" to add push certificate.
-
Import Meizu pushed SDK into the project. Current compatible version is com.meizu.flyme.internet:push-internal:3.9.7`.
Integration configuration
- AndroidManifest.xml configuration
There are two manifests that must be changed into the developer's app package name.
<!-- Compatible with the version below Flyme5; PushSDK to which Meizu has internal access is required. Otherwise, no message will be received-->
<uses-permission android:name="com.meizu.flyme.push.permission.RECEIVE"/>
<permission
android:name="{Your package name}.permission.MESSAGE"
android:protectionLevel="signature"/>
<uses-permission android:name="{Your package name}.push.permission.MESSAGE"/>
<!--Compatible with Flyme3 configuration permission -->
<uses-permission android:name="com.meizu.c2dm.permission.RECEIVE" />
<permission
android:name="{Your package name}.permission.C2D_MESSAGE"
android:protectionLevel="signature"/>
<uses-permission android:name="{Your package name}.permission.C2D_MESSAGE"/>
The following configurations are copied to AndroidManifest.xml to replace your own package name.
<!--Meizu push configuration item-->
<recipient android:name="com.netease.nimlib.mixpush.mz.MZPushReceiver">
<intent-filter android:priority="0x7fffffff">
<!-- Receive push notifications -->
<action android:name="com.meizu.flyme.push.intent.MESSAGE" />
<!-- Receive register messages -->
<action android:name="com.meizu.flyme.push.intent.REGISTER.FEEDBACK" />
<!-- Receive unregister messages-->
<action android:name="com.meizu.flyme.push.intent.UNREGISTER.FEEDBACK"/>
<!-- Compatible with low-version Flyme3 push service configuration -->
<action android:name="com.meizu.c2dm.intent.REGISTRATION" />
<action android:name="com.meizu.c2dm.intent.RECEIVE" />
<category android:name="com.netease.nim.demo"/>
</intent-filter>
</recipient>
- Configure certificate information
In the SDK initialization process, certificate information related to push must be configured to SDKOptions.mixPushConfig
.
config.mzAppId = "xxx";
config.mzAppKey = "xxxx";
config.mzCertificateName = "xxxx";
If code obfuscation is enabled to create an app, please add the following to proguard.cfg.
-dontwarn com.meizu.cloud.**
-keep class com.meizu.cloud.** {*;}
So far, Meizu push access has been completed and push notification can be tested on Meizu devices.
Push compatibility
- Developers need to create a new broadcast recipient and change to succeed from
MeiZuPushReceiver
instead of originalMzPushMessageReceiver
.MeiZuPushReceiver
is provided by CommsEase.
/**
* The following methods operate in the non-UI thread, which corresponds to the MzPushMessageReceiver method of Meizu SDK.
* When developers need access to Meizu push, MzPushMessageReceiver should be changed to MeiZuPushReceiver, without any change to others
*/
public class MeiZuPushReceiver extends BroadcastReceiver {
@Override
public final void onReceive(Context context, Intent intent) {
}
public void onRegister(Context context, String pushId) {
}
public void onUnRegister(Context context, boolean success) {
}
public void onPushStatus(Context context, PushSwitchStatus pushSwitchStatus) {
}
public void onRegisterStatus(Context context, RegisterStatus registerStatus) {
}
public void onUnRegisterStatus(Context context, UnRegisterStatus unRegisterStatus) {
}
public void onSubTagsStatus(Context context, SubTagsStatus subTagsStatus) {
}
public void onSubAliasStatus(Context context, SubAliasStatus subAliasStatus) {
}
public void onNotificationClicked(Context context, String title, String content, String selfDefineContentString) {
}
public void onNotificationArrived(Context context, String title, String content, String selfDefineContentString) {
}
public void onNotifyMessageArrived(Context context, String message) {
}
public void onNotificationDeleted(Context context, String title, String content, String selfDefineContentString) {
}
public void onUpdateNotificationBuilder(PushNotificationBuilder pushNotificationBuilder) {
}
}
- After the broadcast recipient is changed to succeed from
MeiZuPushReceiver
, the broadcast inAndroidManifest
is configured as below. Developers only need to replace the broadcast nameMeiZuPushReceiver
with their own broadcast name. In addition, please do not configurepriority
for this receiver.
<recipient android:name="xxx.MeiZuPushReceiver">
<intent-filter>
<action android:name="com.meizu.flyme.push.intent.MESSAGE" />
<action android:name="com.meizu.flyme.push.intent.REGISTER.FEEDBACK" />
<action android:name="com.meizu.flyme.push.intent.UNREGISTER.FEEDBACK" />
</intent-filter>
</recipient>
Google push
Google Push FCM is GCM Upgrade and applicable to overseas users. FCM push can be successful only when the following two conditions are satisfied:
- The mobile phone has been installed and run Google mobile framework successfully;
- The mobile phone has been connected with overseas network which will not be walled off.
Specifically, although some domestic mobile phones meet the above two conditions and FCM push is successful, push notification bar cannot be found yet. If app is designed for domestic users, FCM integration is not required.
Prerequisites
-
For auxiliary package of integration push, see description of
push
in SDK integration. -
Go to FCM website to register account and pass certification, create app and get AppID, AppKey, and AppSecret, and add certificate fingerprint.
-
Go to "CommsEase console - Certificate management - Android push certificate" to add push certificate.
-
Copy FCM generated google-services.json to the project.
-
Import Google pushed SDK into the project. Current compatible version is as follows:
implementation 'com.google.firebase:firebase-messaging:20.1.0'
implementation 'com.google.android.gms:play-services-base:17.1.0'
implementation 'com.google.firebase:firebase-core:17.2.3'
Integration configuration
- AndroidManifest.xml configuration
The following configurations are copied to AndroidManifest.xml.
<!-- fcm -->
<service android:name="com.netease.nimlib.mixpush.fcm.FCMTokenService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
Configure icon and color for receiving FCM notification.
<!--Set the icon and color displayed upon receipt of fcm notifications-->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/change to your notification icon" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/change to your notification color" />
- Configure certificate information
In the SDK initialization process, certificate information related to push must be configured to SDKOptions.mixPushConfig
.
config.fcmCertificateName = "xxxx";
...
options.mixPushConfig = config;
If code obfuscation is enabled to create an app, please add the following to proguard.cfg.
-dontwarn com.google.**
-keep class com.google.** {*;}
So far, FCM push access has been completed and push notification can be tested.
Custom configuration
You can input data with key as fcmField
map or JsonObject data in pushPayload of CommsEase message body. Go to FCM push service to get the details.
Message alert
CommsEase SDK provides built-in message alert feature, of which scenario is different from push. Its' role is as follows in the following IM scenarios:
-
app is running in the background and SDK process is not cleared;
-
The user is chatting with A in the foreground, but receives message from others, instead of A;
-
The user is not staying on chat interface and recent session list interface.
Generally, the message alert is not required under the following scenarios:
-
The user is staying on the chat interface and receives message from current session.
-
The user is staying on the recent contact list interface, and no message alert is received (but update notification for unread count).
Enable message alert
/**
* Status bar notification on/off control. Valid only when StatusBarNotificationConfig is not null
*
* @param on son/off
*/
public static void toggleNotification(boolean on);
- Example
* Enable status bar notification
NIMClient.toggleNotification(true);
After enabling the feature, you must dynamically adjust message alert based on current page environment. In addition, you must combine with unread count related interface:
// Enter the chat interface; it is suggested to put it in onResume. This indicates that no notification is required for the messages from account.
NIMClient.getService(MsgService.class).setChattingAccount(account, sessionType);
// Enter the recent contact list interface; it is suggested to put it in onResume. This indicates that no notification is required for all messages.
NIMClient.getService(MsgService.class).setChattingAccount(MsgService.MSG_CHATTING_ACCOUNT_ALL, SessionTypeEnum.None);
// Quit the chat interface or leave the recent contact list interface; it is suggested to put it in onPause. This indicates that notification may be sent for all messages.
NIMClient.getService(MsgService.class).setChattingAccount(MsgService.MSG_CHATTING_ACCOUNT_NONE, SessionTypeEnum.None);
Recall notification message alert
/**
* Set whether message notification is required when a recalling notification is received. Valid only when StatusBarNotificationConfig is not null and the status bar notification is in open status. Open by default.
*
* @param on son/off
*/
public static void toggleRevokeMessageNotification(boolean on);
Configuring message alert
- API prototype
/**
* Update the status-bar notification settings
*
* @param config settings
*/
public static void updateStatusBarNotificationConfig(StatusBarNotificationConfig config);
- StatusBarNotificationConfig parameter
StatusBarNotificationConfig parameter | Description |
---|---|
notificationSmallIconId | Resource ID of small icon for status bar tip. If not provided, app icon will be used. |
ring | Determine to set ring tip. It is "true" by default. |
notificationSound | Sound resource for ring tip. If not provided, default notification sound will be enabled |
vibrate | Determine to set vibration alert. It is "true" by default. |
ledARGB | Color of LED indicator. We recommend to use basic colors such as green, blue and red, and avoid mixed colors. |
ledOnMs | Duration of LED ON (ms) |
ledOffMs | Duration of LED OFF (ms) |
hideContent | Hide message content. It is "false" by default |
downTimeToggle | Downtime toggle It is "close" by default. |
downTimeBegin | Downtime begin, with format HH:mm (24h system) |
downTimeEnd | Down time end, with format HH:mm (24h system) If end time is later than start time, then down time is "start time-24:00-end time". |
notificationEntrance | Activity type of response intent for notification bar tip. Null is optional. If not configured, activity of entrance intent of launcher under package will be used. |
titleOnlyShowAppName | Show app name in title of notification bar tip. It is "false" by default. When a session message is sent, session name will be displayed; when multiple sessions are sent, app name will be displayed. If it is updated to "true", despite one session or multiple sessions, only app name is displayed in title. You can set android:label under application node of AndroidManifest to configure app name. |
notificationColor | Color of message notification bar. setColor method of NotificationCompat.Builder will be applied. It will influence smallIcon in Android 5.0 and subsequent versions. |
downTimeEnableNotification | Down time; determine to show notification; "true" by default. |
notificationFoldStyle | Fold style of notification bar: All fold: NotificationFoldStyle.ALL All unfold: NotificationFoldStyle.EXPAND Fold by session: NotificationFoldStyle.CONTACT |
notificationExtraType | Click extra type delivered from online notification bar to return ArrayList<IMMessage> format: NotificationExtraTypeEnum.MESSAGE, with key as NimIntent#EXTRA_NOTIFY_CONTENT , and return String style JSONArray: NotificationExtraTypeEnum.JSON_ARR_STR, with key as NimIntent#EXTRA_NOTIFY_SESSION_CONTENT |
- Example
// Update notification configuration StatusBarNotificationConfig; for example, setting to no bell.
StatusBarNotificationConfig config = UserPreferences.getStatusConfig();
config.ring = false;
config.notificationExtraType = NotificationExtraTypeEnum.MESSAGE;
NIMClient.updateStatusBarNotificationConfig(config);
Clicking extra type shown in online notification bar
When you click notification bar of online notification, message information will be invoked for convenience of page skipping.
- Enumeration prototype
public enum NotificationExtraTypeEnum {
/**
* Callback message body list
*/
MESSAGE(0),
/**
* Call back JSONArray in the format of String. Each element contains message uuid, sessionId, sessionType and time
*/
JSON_ARR_STR(1),
;
final private int value;
NotificationExtraTypeEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
- Configuration effect
Configuration | key of Extra | Value format of Extra |
---|---|---|
MESSAGE | NimIntent#EXTRA_NOTIFY_CONTENT | ArrayList |
JSON_ARR_STR | NimIntent#EXTRA_NOTIFY_SESSION_CONTENT | String // JSONArray format. Each JSONObject contains many keys, for example, "uuid", "sessionId", "sessionType" and "time. |
Custom profile picture and name
Developers can implement UserInfoProvider
interface to process profile picture and name displayed in notification bar. The interface includes the following methods:
- getAvatarForMessageNotifier method aims to provideprofile picture for notification bar tip.
- getDisplayNameForMessageNotifier method aims to provide display name of message sender for notification bar tip.
See API document for detailed interface. For sample codes, please download IM demo source codes. See NimUserInfoProvider.java
file.
CommsEase can customizeprofile picture displayed in notification bar (for example, user profile picture, team profile picture) and provide following method under UserInfoProvider interface:
/**
* Provide the display name of message sender for the status bar in CommsEase (for example: for peer-to-peer chat, display the remark, profile name, account.; for team chat, display team profile name, remark, profile name, account.)
*
* @param account Message sender account
* @param sessionId Session ID (for peer-to-peer chat, session ID is the sender ID; for team chat, session ID is the team account)
* @param sessionType session type
* @return display name of message sender
*/
String getDisplayNameForMessageNotifier(String account, String sessionId, SessionTypeEnum sessionType);
/**
* Provideprofile picture for status bar notification in CommsEase (individual, team)
* Generally obtained from the local image cached; if no download is made or it is not available locally, please return the default localprofile picture (or the Bitmap corresponding to the defaultprofile picture resource ID)
*
* @param sessionType Session type (individual, team)
* @param sessionId User account or team ID
* @returnprofile picture bitmap
*/
Bitmap getAvatarForMessageNotifier(SessionTypeEnum sessionType, String sessionId);
To implement above required method, you must configure UserInfoProvider example in SDKOptions and type SDKOptions in SDK initialization process.
It is noted that the above Bitmap feature for returning profile picture must be configured to getAvatar from memory cache as much as possible. Otherwise, reading localprofile picture may block UI process, resulting in delayed pop-up of notification bar tip.
Configure multi-device alert strategy
When the desktop is online, SDK can set that a mobile client of same account to generate push and message alert.
The feature is provided by SettingsService
:
/**
* Set whether push is required to the mobile client when online at the desktop client (PC/WEB)
* @param isOpen Switch
* @return NoDisturbConfig
*/
InvocationFuture<java.lang.Void> updateMultiportPushConfig(boolean isOpen);
/**
* Get whether push is required to the mobile client when online at the desktop client (PC/WEB)
*/
boolean isMultiportPushOpen();
Example:
NIMClient.getService(SettingsService.class).updateMultiportPushConfig(checkState)
.setCallback(new RequestCallback<Void>() {
@Override
public void onSuccess(Void param) {
ToastHelper.showToast(SettingsActivity.this, "Setting succeeds");
}
@Override
public void onFailed(int code) {
ToastHelper.showToast(SettingsActivity.this, "Set fails,code:" + code);
adapter.notifyDataSetChanged();
}
@Override
public void onException(Throwable exception) {
}
});
In addition, you can monitor change of the entry using SettingsServiceObserver
provided invocation:
/**
* Register or cancel the event that whether push is required to the event observer when online at the desktop client (PC/WEB)
*/
void observeMultiportPushConfigNotify(Observer<java.lang.Boolean> observer,boolean register);
Global Do Not Distrub setting
Close push service
If you want to disable push and message alert, you need to close push service and message alert simultaneously.
Close push service
You can use MixPushService
provided enable
method to implement this feature. If "false", then the client cannot receive push from CommsEase system.
/**
* Enable/Disable push service
*
* @param enable true indicates enable, which SDK needs to confirm with CommsEase server; false indicates disable, which SDK also needs to notify CommsEase server.
* @return InvocationFuture - Configurable callback feature. Successful only after the interaction with server. In case of any error, specific error code will appear.
*/
public InvocationFuture<Void> enable(boolean enable);
/**
* Wether the third-party push service has been enabled
*/
boolean isEnable();
Invocation example:
NIMClient.getService(MixPushService.class).enable(enable).setCallback(new RequestCallback<Void>(){... });
Disable message alert
/**
* Status bar notification on/off control. Valid only when StatusBarNotificationConfig is not null
*
* @param on son/off
*/
public static void toggleNotification(boolean on);
Set Do Not Distrub time
Push Do Not Distrub time
You can use MixPushService
provided setPushNoDisturbConfig
method to set push down time.
/**
* Set the "Push no disturb" time in the format of HH:mm based on the 24-hour system of Beijing time. No push notifications will be sent to users during the time period
* To sync the "No disturb configuration" set by users with "push no disturb", users of the versions earlier than SDK 3.2.0 should
* call the setPushNoDisturbConfig method after monitoring the finished login sync. If developers do not use the third-party push feature of the new version, the old feature will not be affected if the method is not called.
* In addition, "push no disturb" should be set in the "No disturb settings" interface
* @param isOpen Whether to open
* @param startTime Start time format: HH:mm
* @param stopTime Stop time format: HH:mm
* @return InvocationFuture - Configurable callback feature. If successful, return the success information; if failed, return the corresponding error code.
*/
InvocationFuture<Void> setPushNoDisturbConfig(boolean isOpen, String startTime, String stopTime);
You can use MixPushService
provided getPushNoDisturbConfig()
method to get push down time.
/**
* Get the push no disturb configuration
* @return NoDisturbConfig
*/
NoDisturbConfig getPushNoDisturbConfig();
Do Not Disturb Setting
You can set this feature by configuring down time property of StatusBarNotificationConfig:
StatusBarNotificationConfig parameter | Description |
---|---|
downTimeToggle | Downtime toggle It is "close" by default. |
downTimeBegin | Downtime begin, with format HH:mm (24h system) |
downTimeEnd | Down time end, with format HH:mm (24h system) If end time is later than start time, then down time is "start time-24:00-end time". |
Example:
config.downTimeToggle = true;
config.downTimeBegin = startTime;
config.downTimeEnd = endTime;
config.downTimeEnableNotification = enableNotification;
NIMClient.updateStatusBarNotificationConfig(config);
Messaging Configuration
Push notifications and new message alert
If you need to specify a certain message without push and message alert, you can configure this feature using CustomMessageConfig.enablePush
and set to false
, then the message will not trigger a push. See Configure message property settings.
Set prefix of push content
If you need to specify prefix for a certain push notification, current display name of message sender will be used by default. You can configure using CustomMessageConfig.enablePushNick
. See Configure message property settings.
Push title setting
- If you have configured
"pushTitle":"Title content"
usingIMMessage.setPushPayload(Map pushPayload)
, then the content is displayed like this (in priority). - If there is no such configuration, then title of peer-to-peer push notification will be user profile name, and title of team push notification will be team name.
- If user display name is not set, then title of peer-to-peer push notification will be "new message".
Notification bar text
Push content
You can configure push text using IMMessage.setPushContent(String pushContent)
method. If push text is not configured, then CommsEase built-in text will be used.
- Customize default push text
If the developer configures "Hide Preview Text" (see the following for the configuration method), then default push text will be "You've got a new message". At this time, the developer can customize push text (for example, based on system language). Notes: You need to apply to the business consultant for this feature.
Log in to CommsEase Console-> Application->Certificate Management->Custom Push Copy
. At most 100 user-defined texts can be configured. Each user-defined text is marked with one user-defined type.
User-defined push text will not take effect until the client is configured with "Hide Preview Text"
/**
* Set whether to show no detail for push
*
* @param showNoDetail whether to show no detail, true indicates showing no detail
* @return InvocationFuture - Configurable callback feature. If successful, return the success information; if failed, return the corresponding error code.
*/
InvocationFuture<Void> setPushShowNoDetail(boolean showNoDetail);
- Example
NIMClient.getService(MixPushService.class).setPushShowNoDetail(showNoDetail).setCallback(new RequestCallbackWrapper<Void>() {
@Override
public void onResult(int code, Void result, Throwable exception) {
if (code == ResponseCode.RES_SUCCESS) {
// Set config.hideContent, or set at initialization
StatusBarNotificationConfig config = UserPreferences.getStatusConfig();
config.hideContent = showNoDetail;
UserPreferences.setStatusConfig(config);
NIMClient.updateStatusBarNotificationConfig(config);
} else {
...
}
}
});
If the push content is hidden, the push will be sent as per configured text. The corresponding parameter is SDKOptions.customPushContentType
.
Message alert text
The text of Android SDK notification bar tip displays the content in the following priority:
-
If the sender has configured push text when sending message, then push text will be displayed in message alert.
-
SDK will invoke
SDKOptions.messageNotifierCustomization
interface when receiving messages, and the developer can customize tip text in the invocation. -
Android SDK provides NimStrings type for the developer to customize the text of new notification bar tip and corresponding multi-language support. For detailed application mode, see IM
Demo> NIMInitadministrator.java> updateLocale method> NimStrings configured
related field. Please callNIMClient.updateStrings(NimStrings strings)
method to update text configuration. The detailed text strings are defined inres > values > strings > strings.xml
(Demo has been configured with Chinese and English examples).
Forced push for team messages
When sending a message, the user can force to push team message by configuring IMMessage.setMemberPushOption(MemberPushOption pushOption)
field. That is, the recipient can still push current message even when shielding current session (for example, mute).
- Parameters
MemberPushOption interface
Return | MemberPushOption interface | Description |
---|---|---|
List |
getForcePushList() | Return force pushed account list |
String | getForcePushContent() | Return force pushed text |
boolean | isForcePush() | Return force push need |
void | setForcePush(boolean forcePush) | Set force push. For accounts in forcePushList, false is "non-force push"; true is "force push". Default value is "true". For users in forcePushList, the push text is forcePushContent; for users not in forcePushList, the push text is pushContent; for accounts in forcePushList, if isForcePush is "true", push text will not contain sender's nick, but forcePushContent; if ForcePush is "false", the push text contains sender's nick (temporary), i.e. fromNick: forcePushContent. |
void | setForcePushList(List |
Set force push list. If null, it will be pushed to all members of the session by force; if not null, maximum limit of accounts is 100. |
void | setForcePushContent(String forcePushContent) | Force push text (extensible to push text different from ordinary push), with current length limit 500. |
- Example
// The account is an example. Please register.
String account = "testAccount";
// Push message only for team chat
SessionTypeEnum sessionType = SessionTypeEnum.Team;
String text = "Specified push notifications";
// Create a text message
IMMessage textMessage = MessageBuilder.createTextMessage(account, sessionType, text);
// Configure push to specified members
MemberPushOption memberPushOption = new MemberPushOption();
// Enable force push
memberPushOption.setForcePush(true);
// Set push content
memberPushOption.setForcePushContent(textMessage.getContent());
List<String> pushList = new ArrayList<>();
pushList.add("account1");
pushList.add("account2");
// Set specified push list
memberPushOption.setForcePushList(pushList);
textMessage.setMemberPushOption(memberPushOption);
// Send to the other party
NIMClient.getService(MsgService.class).sendMessage(textMessage, false);
Redirection from clicking the notification bar
When receiving push and notification bar tip, the user can click notification bar. If the user hopes to join specified chat page, the user must skip to corresponding chat interface.
Redirection from the notification bar
Huawei push
Before sending messages, you must input data with key as hwField
map or JsonObject data in pushPayload of CommsEase message body, for example, sender's account or team chat ID and type (one-to-one chat or team chat). These information will be transferred to push recipient. For the method of filling in data parameter, see HUAWEI open platform: HTTPS downlink message.
- Example
Intent hwIntent = new Intent(Intent.ACTION_VIEW);
String intentStr = String.format(
"pushscheme://com.huawei.codelabpush/deeplink?sessionID=%s&sessionType=%s",
sessionId, // Sender account or team chat id
sessionType // Type (one-to-one chat or team chat)
);
hwIntent.setData(Uri.parse(intentStr));
hwIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
String intentUri = hwIntent.toUri(Intent.URI_INTENT_SCHEME);
//Click event content
JSONObject clickAction = new JSONObject();
//Content notified
JSONObject notification = new JSONObject();
try {
clickAction.putOpt("type", 1)
.putOpt("intent", intentUri);
notification.putOpt("click_action", clickAction);
pushPayload.put("hwField", notification);
} catch (JSONException e) {
e.printStackTrace();
}
When the recipient receives HUAWEI push, see HUAWEI open platform: click notification message for processing mode.
OPPO push
Before sending messages, you must input data with key as oppoField
map or JsonObject data in pushPayload of CommsEase message body, for example, sender's account or team chat ID and type (one-to-one chat or team chat). These information will be transferred to push recipient. For data parameter, see OPPO open platform: notification bar message.
// oppoField
Map<String, Object> oppoField = new HashMap<>();
Editable oppoChannelId = oppoChannelIdET.getText();
oppoField.put("click_action_type", 1);
oppoField.put("click_action_activity", "com.oppo.codelabpush.intent.action.test");
// oppoField.put("click_action_type", 4);
// oppoField.put("click_action_activity", "com.netease.nim.demo.main.activity.MixPushActivity");
JSONObject obj = new JSONObject();
try {
obj.putOpt("sessionID", sessionType == SessionTypeEnum.peer-to-peer ? TestCache.getAccount() : msg.getSessionId());
obj.putOpt("sessionType", sessionType.getValue());
} catch (JSONException e) {
e.printStackTrace();
}
oppoField.put("action_parameters", obj.toString());
pushPayload.put("oppoField", oppoField);
When the recipient receives OPPO push, see OPPO open platform: notification bar message for processing mode.
Google Push
After clicking Google push notification bar, you can enable app entry Activity and pass through Intent carrying data. SDK provides interface to determine that FCM Intent is integrated at CommsEase side.
MixPushService
provides two interfaces to process FCM payload:
/**
* Whether Activity is enabled by clicking fcm notification
*
* @param intent activity intent
* @return Judge result
*/
boolean isFCMIntent(Intent intent);
/**
* Resolve payload character string from FCM
*
* @param intent activity intent
* @return
*/
String parseFCMPayload(Intent intent);
In IM Demo, you can determine if (NIMClient.getService(MixPushService.class).isFCMIntent(intent))
under onIntent of WelcomeActivity.java. See Demo for detailed codes.
Other vendors
For push, when creating message object, the sender must insert information (for example, account, team ID, session type) that can indicate session identification in IMMessage.setPushPayload(Map pushPayload)
to analyze playload received by receiving client.
The invocation of click event in push notification bar is provided by MixPushMessageHandler
:
public interface MixPushMessageHandler {
/**
* Push the callback method after click on the notification bar
*
* @param context
* @param custom pushPayload {@link com.netease.nimlib.sdk.msg.model.IMMessage} set by users in payload IMessage
* @return true indicates that developers handle the events clicked on the status bar, which SDK will no longer handle; false indicates skip after click by default as provided by SDK
*/
boolean onNotificationClicked(Context context, Map<String, String> payload);
}
Developers must register MixPushMessageHandler
in the main process under Application#oncreate
. Demo example:
if (NIMUtil.isMainProcess(this)) {
// Register custom push notifications handler (this is optional)
NIMPushClient.registerMixPushMessageHandler(new DemoMixPushMessageHandler());
}
Notification bar redirection
You can configure Activity of response Intent in notification bar tip using StatusBarNotificationConfig.notificationEntrance
parameter, and update configuration of notification bar tip using NIMClient.updateStatusBarNotificationConfig(StatusBarNotificationConfig config)
.
For IM Demo, there are logics as below:
- Invoke
NIMClient.init(...,..., NimSDKOptionConfig.getSDKOptions(this))
inNimApplication.java
; - Invoke
initStatusBarNotificationConfig(options)
ingetSDKOptions(Context context)
underNimSDKOptionConfig.java
; - Configure
StatusBarNotificationConfig config = loadStatusBarNotificationConfig()
ininitStatusBarNotificationConfig(SDKOptions options)
; - Configure
config.notificationEntrance = WelcomeActivity.class
inloadStatusBarNotificationConfig()
; - Determine
parseNotifyIntent(intent)
invocation byif (intent.hasExtra(NimIntent.EXTRA_NOTIFY_CONTENT))
inonIntent
underWelcomeActivity.java
. See Demo for detailed codes.
[Notes] For meaning of EXTRA_NOTIFY_CONTENT
, see EXTRA_NOTIFY_CONTENT.