logout
API is called to log out proactively or you are forced to log out due to multi-device login, you cannot receive offline push messages even though offline push of the Chat service is enabled.API | Description |
Constructor (TimUiKitPushPlugin) | Instantiates a push plugin object and determines whether to use Google FCM. |
init | Initialize the plugin. Binds the callback for the notification click event and passes in vendor channel information. |
uploadToken | Automatically gets and uploads the device token and certificate ID to the Chat server. |
clearToken | Clears the push token of the current device on the server side to block notifications. |
requireNotificationPermission | Requests the push permission. |
setBadgeNum | Sets the unread count badge. For iOS devices, disable the badge setting feature of the Chat SDK first. For more information, see here. |
clearAllNotification | Clears all the notifications of the current application from the notification bar. |
getDevicePushConfig | Gets the push information of the current vendor, including model, certification ID, and token. |
getDevicePushToken | Gets the push token of the current vendor. |
getOtherPushType | Gets the vendor information. |
getBuzId | Gets the current vendor's certificate ID registered in the Tencent Cloud console. |
createNotificationChannel | Creates a notification channel for an Android model. For more information, see Create and manage notification channels. |
clearAllNotification | Clears all the notifications of the current application from the notification bar. |
displayNotification | Manually creates a message notification on the client. |
displayDefaultNotificationForMessage | Automatically creates a message notification for a V2TimMessage object on the client according to the default rules. |
AppId
, AppKey
, AppSecret
, and MasterSecret
values.tuikit
.ChannelID
. A private channel is recommended to avoid exceeding the daily push limit.com.tencent.flutter.tim_ui_kit_push_plugin.pushActivity.OPPOMessageActivity
.APP ID
, APP key
, and App secret
.tencent_im_push://${your package name}/message?#Intent;scheme=tencent_im_push;launchFlags=0x4000000;end
.SecretKey
information on the page that appears after you choose App information > My apps, choose Project settings > General information to view the Client Secret
information.keystore.jks
key file to get its SHA-256 value and enter it on the HUAWEI Push platform.keystore
signature, so that the SHA-256 value of the final build is consistent with the former value. The code is as follows:zipalign -v -p 4 built apk.apk packaged apk_aligned.apkapksigner sign --ks keystore.jks --ks-pass pass: Your keystore password --out Final signature Completed apk.apk Packaged apk_aligned.apk
agconnect-services.json
of your Huawei application to the android/app
directory.Activity
class of the Android application entry, for example, com.tencent.flutter.tuikit
in the demo; otherwise, the badge settings for Huawei channel notifications will not take effect.
Set Response after Click to Open application.App package name
, App ID
, and App Secret
.tencent_im_push://${your package name}/honorMessage?#Intent;scheme=tencent_im_push;launchFlags=0x4000000;end
.Edition | Package | Support for Google FCM | Native Channel Support for Chinese Device Vendors | Description |
Chinese mainland edition | No | Yes | Offline push for Android devices is implemented only through the native channels of the vendors. | |
International edition | Yes | Yes | The Google FCM channel is preferred whenever possible. Native channels of the vendors are also supported. |
// Chinese mainland editionflutter pub add tencent_chat_push_for_china// International editionflutter pub add tim_ui_kit_push_plugin
lib/utils/push
folder and the call methods.PushAppInfo
class, which needs to be passed in later.static final PushAppInfo appInfo = PushAppInfo(hw_buz_id: , // Huawei certificate IDmi_app_id: , // Mi `APPID`mi_app_key: , // Mi `APPKey`mi_buz_id: , // Mi certificate IDmz_app_id: , // Meizu `APPID`mz_app_key: , // Meizu `APPKey`mz_buz_id: , // Meizu certificate IDvivo_buz_id: , // vivo certificate IDoppo_app_key: , // OPPO `APPKey`oppo_app_secret: , // OPPO `APP Secret`oppo_buz_id: , // OPPO certificate IDoppo_app_id: , // OPPO `APPID`google_buz_id: , // Google FCM certificate IDapple_buz_id: , // Apple certificate IDhonor_buz_id: , // Honor certificate ID);
android/app/src/main/AndroidManifest.xml
file and add the usesCleartextTraffic
field to application
.<applicationandroid:usesCleartextTraffic="true" // Add this line><!-- possibly other elements --></application>
pubspec.yaml
file, add the firebase_core
dependency, and use v1.12.0.dependencies:firebase_core: 1.12.0
flutter pub get
to complete installation.// Install the Firebase CLInpm install -g firebase-toolscurl -sL https://firebase.tools | bashdart pub global activate flutterfire_cli// Generate a configuration fileflutterfire configure
main()
method.WidgetsFlutterBinding.ensureInitialized();await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform,);
android/build.gradle
file.buildscript {repositories {google()jcenter()maven {url 'https://developer.huawei.com/repo/'} // Add Huawei Maven repository address}dependencies {// Other `classpath` configurationsclasspath 'com.huawei.agconnect:agcp:1.3.1.300' // Add the Gradle plugin dependencies of Huawei Push}// Set release signing and passwords in the same build configuration filesigningConfigs {release {storeFile file('<keystore_file>')storePassword '<keystore_password>'keyAlias '<key_alias>'keyPassword '<key_password>'}}buildTypes {// The debug mode also requires compilation with a certificate; otherwise, Huawei fingerprint verification may fail.debug {signingConfig signingConfigs.release}release {signingConfig signingConfigs.release}}}
android/build.gradle
file, and add the Huawei dependency repository address under repositories in allprojects:allprojects {repositories {google()jcenter()maven {url 'https://developer.huawei.com/repo/'} // Add Huawei Maven repository address}}
agconnect-services.json
of your Huawei application to the android/app
directory.android/app/build.gradle
file and add the following configuration:// Other Gradle plugins of applicationapply plugin: 'com.huawei.agconnect' // HMS Push SDK Gradle pluginandroid {// Application configuration content}
android/app/src/main/AndroidManifest.xml
file and add the following uses-permission
information:<uses-permission android:name = "com.huawei.android.launcher.permission.CHANGE_BADGE "/>
android/app/build.gradle
file and configure AppID
and AppKey
of vivo as follows:android: {defaultConfig {manifestPlaceholders = [....vivo_APPID: "Enter the vivo AppID that you obtained"vivo_APPKEY: "Enter the vivo AppKey that you obtained".....]}}
android/app/src/main/AndroidManifest.xml
file and add meta-data
to <application>
as follows:<meta-dataandroid:name="com.vivo.push.api_key"android:value="Enter the vivo AppKey that you obtained" /><meta-dataandroid:name="com.vivo.push.app_id"android:value="Enter the vivo AppID that you obtained" /></application>
android/app/src/main/AndroidManifest.xml
file and add the following uses-permission
information:<uses-permission android:name="com.vivo.notification.permission.BADGE_ICON" />
android/app/src/main/AndroidManifest.xml
file and add meta-data
to <application></application>
as follows:<meta-dataandroid:name="com.hihonor.push.app_id"android:value="Enter the HONOR AppID that you obtained" /></application>
android/app/build.gradle
file and add the following code:repositories {maven { url 'https://developer.hihonor.com/repo/' } // Add}
android/app/src/main/AndroidManifest.xml
file and add the following uses-permission
information:<uses-permission android:name = "com.hihonor.android.launcher.permission.CHANGE_BADGE" />
android/app/build.gradle
file and add the package name to defaultConfig
.defaultConfig {applicationId "${Enter your package name}"...}
android/app/src/main/AndroidManifest.xml
file and configure permissions for each vendor.<!--Mi Start--><permissionandroid:name="${Enter your package name}.permission.MIPUSH_RECEIVE"android:protectionLevel="signature" /><uses-permission android:name="${Enter your package name}.permission.MIPUSH_RECEIVE" /><!--Mi End--><!--OPPO Start--><uses-permission android:name="com.coloros.mcs.permission.RECIEVE_MCS_MESSAGE" /><uses-permission android:name="com.heytap.mcs.permission.RECIEVE_MCS_MESSAGE" /><!--OPPO End--><!--Meizu Start--><!-- It is optional and used for compatibility with Flyme OS 5 and push services on earlier versions.--><uses-permission android:name="android.permission.READ_PHONE_STATE" /><!-- Permission configuration for compatibility with Flyme OS 5--><uses-permission android:name="com.meizu.flyme.push.permission.RECEIVE" /><permission android:name="${Enter your package name}.push.permission.MESSAGE"android:protectionLevel="signature"/><uses-permission android:name="${Enter your package name}.push.permission.MESSAGE" /><!-- Permission configuration for compatibility with Flyme OS 3--><uses-permission android:name="com.meizu.c2dm.permission.RECEIVE" /><permission android:name="${Enter your package name}.permission.C2D_MESSAGE" android:protectionLevel="signature"/><uses-permission android:name="${Enter your package name}.permission.C2D_MESSAGE"/><!--Meizu End-->
init
method of the plugin to initialize the vendor channels and request the notification permissions from the vendors. final TimUiKitPushPlugin cPush = TimUiKitPushPlugin(isUseGoogleFCM: bool, // Whether to enable Google FCM. The default value is `true`. This parameter is unavailable in the Chinese mainland edition.);await cPush.init(pushClickAction: pushClickAction, // Callback for the event upon notification click, which is as detailed in step 6.appInfo: PushConfig.appInfo, // Pass in the `appInfo` in step 1);
createNotificationChannel
method to create message channels for some vendors, such as OPPO and Mi.cPush.createNotificationChannel(channelId: "new_message",channelName: "message push",channelDescription: "push new messages");
requireNotificationPermission
method.cPush.requireNotificationPermission();
appInfo
and reports the token.final TimUiKitPushPlugin cPush = TimUiKitPushPlugin(isUseGoogleFCM: true, // This parameter is unavailable in the Chinese mainland edition.);Future.delayed(const Duration(seconds: 5), () async {final bool isUploadSuccess =await ChannelPush.uploadToken(PushConfig.appInfo);print("Push token upload result: $isUploadSuccess");});
setBadgeNum(int badgeNum )
method in the plugin before the application switches to the inactive/paused state, so as to update the latest unread count to the desktop badge. The plugin supports configuring badges for Mi (MIUI 6 to MIUI 11), Huawei, HONOR, vivo, and OPPO devices./// App@overridevoid didChangeAppLifecycleState(AppLifecycleState state) async {print("--" + state.toString());int? unreadCount = await _getTotalUnreadCount();switch (state) {case AppLifecycleState.inactive:TencentImSDKPlugin.v2TIMManager.getOfflinePushManager().doBackground(unreadCount: unreadCount ?? 0);if(unreadCount != null){cPush.setBadgeNum(unreadCount);}break;case AppLifecycleState.resumed:TencentImSDKPlugin.v2TIMManager.getOfflinePushManager().doForeground();break;case AppLifecycleState.paused:TencentImSDKPlugin.v2TIMManager.getOfflinePushManager().doBackground(unreadCount: unreadCount ?? 0);if(unreadCount != null){cPush.setBadgeNum(unreadCount);}break;}}
OfflinePushInfo offlinePushInfo
field when sending a message.OfflinePushInfo({this.title = '', // Push notification title. When this string is left empty, the Chat backend will automatically replace it with the sender nickname or, if the sender nickname is unavailable, the sender ID. Therefore, we recommend you leave it empty unless you have special needs, which delivers the same experience as Weixin.this.desc = '', // Push the second linethis.disablePush = false,this.ext = '', // Extra information in the push, which can be obtained after the redirect upon notification click. We recommend you pass in the JSON string containing conversation information, so that the receiver can be redirected to the corresponding chat. For more information, see the following TUIKit instance code.this.androidOPPOChannelID = '', // OPPO channel ID});
notificationTitle
/notificationOPPOChannelID
/notificationBody
/notificationExt
/notificationIOSSound
in TIMUIKitChatConfig
of the TIMUIKitChat
component as follows:TIMUIKitChat(config: TIMUIKitChatConfig(notificationTitle: "",// Push notification title. When this string is left empty, the Chat backend will automatically replace it with the sender nickname or, if the sender nickname is unavailable, the sender ID. Therefore, we recommend you leave it empty unless you have special needs.notificationOPPOChannelID: "", // OPPO channel ID configured for message pushnotificationBody: (V2TimMessage message, String convID, ConvType convType) {return "the second line of the push you customize based on the given parameters";},notificationExt: (V2TimMessage message, String convID, ConvType convType) {// The `ext` field you customize based on the given parameters. We recommend you pass in the conversation ID in JSON format as follows:String createJSON(String convID){return "{\\"conversationID\\": \\"$convID\\"}";}String ext = (convType == ConvType.c2c? createJSON("c2c_${message.sender}"): createJSON("group_$convID"));return ext;}))
pushClickAction
in step 3.Map
containing the push body and ext
information.conversationID
is passed in for ext
when OfflinePushInfo
is created in the previous step, the receiver will be directly redirected to the corresponding chat.clearAllNotification()
method to clear other notifications in the application on the notification bar after the redirect, to avoid too many Chat messages.BuildContext? _cachedContext;final TimUiKitPushPlugin cPush = TimUiKitPushPlugin(isUseGoogleFCM: true, // This parameter is unavailable in the Chinese mainland edition.);@overridevoid initState() {super.initState();_cachedContext = context;}void handleClickNotification(Map<String, dynamic> msg) async {String ext = msg['ext'] ?? "";Map<String, dynamic> extMsp = jsonDecode(ext);String convId = extMsp["conversationID"] ?? "";// We recommend you determine whether the current page is the conversation to be redirected to.// If yes, we recommend you stop the redirect to avoid entering the same page.final targetConversationRes = await TencentImSDKPlugin.v2TIMManager.getConversationManager().getConversation(conversationID: convId);V2TimConversation? targetConversation = targetConversationRes.data;if(targetConversation != null){cPush.clearAllNotification();Navigator.push(_cachedContext ?? context,MaterialPageRoute(builder: (context) => Chat(selectedConversation: targetConversation,),));}}
offlinePushInfo
field as instructed in step 6.offlinePush
object in the third parameter of the call
method as follows:final user = await sdkInstance.getLoginUser();final myId = user.data;OfflinePushInfo offlinePush = OfflinePushInfo(title: "",desc: "make an audio call to you",ext: "{\\"conversationID\\": \\"c2c_$myId\\"}",disablePush: false,ignoreIOSBadge: false,androidOPPOChannelID: PushConfig.OPPOChannelID);_calling?.call(widget.selectedConversation.userID!, CallingScenes.Audio, offlinePush);
Push Notification
capability in the top-left corner.
flutter pub get
to install the plugin, enter the iOS directory, and run pod install
to install the dependency library.didFinishLaunchingWithOptions
method in the ios/Runner/AppDelegate.swift
file of the iOS project. For more information, see DEMO.
Objective-C:if (@available(iOS 10.0, *)) {[UNUserNotificationCenter currentNotificationCenter].delegate = (id<UNUserNotificationCenterDelegate>) self;}
if #available(iOS 10.0, *) {UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate}
info.plist
.<key>flutter_apns.disable_firebase_core</key><false/>
init
method of the plugin to initialize vendor channels and request the vendor notification permission. We recommend you call the method upon application start.final TimUiKitPushPlugin cPush = TimUiKitPushPlugin(isUseGoogleFCM: true, // This parameter is unavailable in the Chinese mainland edition.);cPush.init(pushClickAction: pushClickAction, // Callback for the event upon notification click, which is as detailed in step 6.appInfo: PushConfig.appInfo, // Pass in the `appInfo` in step 1);
OfflinePushInfo offlinePushInfo
field when sending a message.OfflinePushInfo({// Other configurationsthis.iOSSound = "", // iOS offline push sound settings. `iOSSound = kIOSOfflinePushNoSound` indicates not to play back the system sound when a message is received; `iOSSound = kIOSOfflinePushDefaultSound` indicates to play back the system sound when a message is received. To customize `iOSSound`, you need to link the audio file to the Xcode project and pass in the filename (with the extension) to `iOSSound`.this.ignoreIOSBadge = false,});
notificationTitle
/notificationOPPOChannelID
/notificationBody
/notificationExt
/notificationIOSSound
in TIMUIKitChatConfig
of the TIMUIKitChat
component as follows:TIMUIKitChat(config: TIMUIKitChatConfig(// Other configurationsnotificationIOSSound: "", // iOS offline push sound settings. `iOSSound = kIOSOfflinePushNoSound` indicates not to play back the system sound when a message is received; `iOSSound = kIOSOfflinePushDefaultSound` indicates to play back the system sound when a message is received. To customize `iOSSound`, you need to link the audio file to the Xcode project and pass in the filename (with the extension) to `iOSSound`.))
setBadgeNum
method. Sample code:TencentImSDKPlugin.v2TIMManager.callExperimentalAPI(api: 'disableBadgeNumber',param: true);
From_Account
to an independent admin account and pass through the offline push information so that you can trigger message push on clients.ext
field of OfflinePushInfo
is the same as that in Step 6. We recommend that you set this field to content in the JSON format that can be directed to after you tap the notification and that can be parsed on clients.{"From_Account": "Admin", // We recommend that you set the value to an admin account."MsgRandom": 3674128,"MsgLifeTime": 120,"MsgBody": [{"MsgType": "TIMTextElem","MsgContent": {"Text": "Push Test"}}],"OfflinePushInfo": {"PushFlag": 0,"Title": "Title of the message to push","Desc": "Content to push offline","Ext": "The content to be passed through. The value must be in the JSON format. You can get the content through click callback or custom operations such as tap-to-redirect.","AndroidInfo": { // Push configuration on Android devices."Sound": "android.mp3"},"ApnsInfo": { // Push configuration on iOS devices."Sound": "apns.mp3","BadgeMode": 1, // If this field is left as default or is set to `0`, the message is counted. If this field is set to `1`, the message is not counted, that is, the badge counter in the upper-right corner does not increase."Title":"apns title", // APNs title"SubTitle":"apns subtitle", // APNs subtitle"Image":"www.image.com" // Image URL}}}
regId
(or device token) of the test device (vivo phone).ext
is conversationID
. If you need other fields when processing the callback for notification click (see step 6), you can modify the JavaScript code.
npm install axios
, npm install js-md5
, and then node testvivo
, and the push result will be displayed in the last row of the log.
desc
field of offlinePushInfo
when calling sendMessage
, after which desc
will be displayed by default during the push.ext
field be in JSON format.displayNotification
for notification customization and displayDefaultNotificationForMessage
for default notification generation based on the message. You can select one as needed.// Chinese mainland editionflutter pub add tencent_chat_push_for_china// International editionflutter pub add tim_ui_kit_push_plugin
@mipmap/ic_launcher
exists as your application icon. The complete path is android/app/src/main/res/mipmap/ic_launcher.png
.
mipmap
directory and choosing New > Image Asset.
didFinishLaunchingWithOptions
in the ios/Runner/AppDelegate.swift
or ios/Runner/AppDelegate.m
file. For more information, see DEMO.if (@available(iOS 10.0, *)) {[UNUserNotificationCenter currentNotificationCenter].delegate = (id<UNUserNotificationCenterDelegate>) self;}
if #available(iOS 10.0, *) {UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate}
cPush
plugin for subsequent calls.final TimUiKitPushPlugin cPush = TimUiKitPushPlugin(isUseGoogleFCM: true, // This parameter is unavailable in the Chinese mainland edition.);cPush.init(// Bind the function for the redirect upon notification click, which is as detailed belowpushClickAction: onClickNotification,);
V2TimAdvancedMsgListener
V2TimAdvancedMsgListener
, skip this section; otherwise, mount the listener after you log in to the Chat service.final advancedMsgListener = V2TimAdvancedMsgListener(onRecvNewMessage: (V2TimMessage newMsg) {// Listen for the event triggered by the callback// Call the API for triggering local message notification mentioned in the next step},});TencentImSDKPlugin.v2TIMManager.getMessageManager().addAdvancedMsgListener(listener: advancedMsgListener);
displayNotification
API for notification customization or displayDefaultNotificationForMessage
API for default notification generation based on messages, as needed.channelID
and channelName
for both of the APIs. If no Android push channels are created, you need to create one by using the createNotificationChannel
API of the plugin.cPush.createNotificationChannel(channelId: "new_message",channelName: "message push",channelDescription: "push new messages");
displayNotification
title
, body
, and ext
for the redirect. You can parse the V2TimMessage
as needed to generated them.displayDefaultNotificationForMessage
code for the ext
generation rule.cPush.displayNotification(channelID: "new_message",channelName: "message push",title: "",body: "",ext: "");
displayDefaultNotificationForMessage
V2TimMessage
.V2TimMessage
object.cPush.displayDefaultNotificationForMessage(message: message, channelID: "new_message", channelName: "message push");
ext
. It reads and redirects the receiver to the corresponding conversation.displayDefaultNotificationForMessage
in the previous step or use the ext
generation function identical to the default in displayNotification
, ext
will be in the structure of "conversationID": "corresponding conversation"
.pushClickAction
.Map
containing the push body and ext
information.clearAllNotification()
method to clear other notifications on the notification bar after the redirect to avoid too many Chat messages.BuildContext? _cachedContext;final TimUiKitPushPlugin cPush = TimUiKitPushPlugin(isUseGoogleFCM: true, // This parameter is unavailable in the Chinese mainland edition.);@overridevoid initState() {super.initState();_cachedContext = context;}void onClickNotification(Map<String, dynamic> msg) async {String ext = msg['ext'] ?? "";Map<String, dynamic> extMsp = jsonDecode(ext);String convId = extMsp["conversationID"] ?? "";// Do not redirect if the current conversation is the target conversation// We recommend you check the current page opened by the user.final targetConversationRes = await TencentImSDKPlugin.v2TIMManager.getConversationManager().getConversation(conversationID: convId);V2TimConversation? targetConversation = targetConversationRes.data;if(targetConversation != null){cPush.clearAllNotification();Navigator.push(_cachedContext ?? context,MaterialPageRoute(builder: (context) => Chat(selectedConversation: targetConversation,),));}}
ext
structure, you need to implement the redirect function on your own.onRecvNewMessage
.
Was this page helpful?