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 IM offline push is enabled.API | Description |
Constructor (TimUiKitPushPlugin) | Instantiates a push plugin object and determines whether to use Google FCM. |
init | 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 IM server. |
requireNotificationPermission | Requests the push permission. |
setBadgeNum | Sets the unread count badge (only supported by some Android devices. For more information, see API Code Parameter Description.) |
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
.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
in App information > My apps, go to Project settings > General information to view Client secret
.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 of the Huawei channel notifications will not take effect.App package name
, App ID
, and App Secret
.flutter pub add tim_ui_kit_push_plugin
PushAppInfo
class, which needs to be passed in later.import 'package:tim_ui_kit_push_plugin/model/appInfo.dart';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 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,);
isUseGoogleFCM
field to false
.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 "/><uses-permission android:name = "com.hihonor.android.launcher.permission.CHANGE_BADGE" />
android/app/build.gradle
file and configure APPID
and App_Key
of vivo as follows:android: {defaultConfig {manifestPlaceholders = [....vivo_APPID: "vivo `APPID`"vivo_APPKEY:"vivo `APP_Key`",.....]}}
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 API_KEY that you obtained" /><meta-dataandroid:name="com.vivo.push.app_id"android:value="Enter the vivo API_ID 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/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.isUseGoogleFCM
switch is provided for you to determine whether to enable Google FCM based on the user group.import 'package:tim_ui_kit_push_plugin/tim_ui_kit_push_plugin.dart';final TimUiKitPushPlugin cPush = TimUiKitPushPlugin(isUseGoogleFCM: bool, // Whether to enable Google FCM. The default value is `true`.);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.import 'package:tim_ui_kit_push_plugin/tim_ui_kit_push_plugin.dart';final TimUiKitPushPlugin cPush = TimUiKitPushPlugin(isUseGoogleFCM: false,);final bool isUploadSuccess = await cPush.uploadToken(PushConfig.appInfo);
setBadgeNum( int badgeNum )
method in the plugin before the application switches to the inactive/paused status, so as to update the latest unread count to the desktop badge. The iOS badge is automatically managed by the IM SDK. Here, the plugin supports configuring badges of Mi (MIUI 6 to MIUI 11), Huawei, Honor, vivo, and OPPO./// coreInstance@overrideFuture<V2TimCallback> setOfflinePushStatus({required AppStatus status, int? totalCount}) {if(Platfrom.isIOS){return;}if(status == AppStatus.foreground){// Report `doForeground()` when the application is in the foregroundreturn TencentImSDKPlugin.v2TIMManager.getOfflinePushManager().doForeground();}else{// Report `doBackground()` along with the unread count when the application is in the backgroundreturn TencentImSDKPlugin.v2TIMManager.getOfflinePushManager().doBackground(unreadCount: totalCount ?? 0);}}/// Appfinal TimUiKitPushPlugin cPush = TimUiKitPushPlugin(isUseGoogleFCM: false,);@overridevoid didChangeAppLifecycleState(AppLifecycleState state) async {print("--" + state.toString());int? unreadCount = await _getTotalUnreadCount();switch (state) {case AppLifecycleState.inactive:_coreInstance.setOfflinePushStatus(status: AppStatus.background, totalCount: unreadCount);if(unreadCount != null){cPush.setBadgeNum(unreadCount);}break;case AppLifecycleState.resumed:_coreInstance.setOfflinePushStatus(status: AppStatus.foreground);break;case AppLifecycleState.paused:_coreInstance.setOfflinePushStatus(status: AppStatus.background, totalCount: unreadCount);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 IM 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.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 IM 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 WeChat.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 on the notification bar after the redirect to avoid too many IM messages.BuildContext? _cachedContext;final TimUiKitPushPlugin cPush = TimUiKitPushPlugin(isUseGoogleFCM: false,);// TUIKit onlyfinal TIMUIKitChatController _timuiKitChatController =TIMUIKitChatController();@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"] ?? "";// [TUIKit] Do not redirect if the current conversation is the target conversationfinal currentConvID = _timuiKitChatController.getCurrentConversation();if(currentConvID == convId.split("_")[1]){return;}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 of the ios/Runner/AppDelegate.swift
file in the iOS project.
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.import 'package:tim_ui_kit_push_plugin/tim_ui_kit_push_plugin.dart';final TimUiKitPushPlugin cPush = TimUiKitPushPlugin();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`.))
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.flutter 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 select New > Image Asset).
android/app/src/main/AndroidManifest.xml
file and add the following code to the main activity
of your application:<activityandroid:showWhenLocked="true"android:turnScreenOn="true">
didFinishLaunchingWithOptions
function of the ios/Runner/AppDelegate.swift
or ios/Runner/AppDelegate.m
file. For detailed directions, see the 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();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 IM login.final advancedMsgListener = V2TimAdvancedMsgListener(onRecvNewMessage: (V2TimMessage newMsg) {// Listen for the event triggered by the callback// Call the creation method in the next step here},});TencentImSDKPlugin.v2TIMManager.getMessageManager().addAdvancedMsgListener(listener: advancedMsgListener);
displayNotification
API for notification customization or displayDefaultNotificationForMessage
API for default notification generation based on the message 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
, the ext
structure will be "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 IM messages.BuildContext? _cachedContext;final TimUiKitPushPlugin cPush = TimUiKitPushPlugin(isUseGoogleFCM: false,);// TUIKit onlyfinal TIMUIKitChatController _timuiKitChatController =TIMUIKitChatController();@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"] ?? "";// [TUIKit] Do not redirect if the current conversation is the target conversationfinal currentConvID = _timuiKitChatController.getCurrentConversation();if(currentConvID == convId.split("_")[1]){return;}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?