### Install Dependencies with Pod Install Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/configuration.md Run `pod install --repo-update` from the `ios` directory after modifying the Podfile to install or update dependencies. ```bash pod install --repo-update ``` -------------------------------- ### Install Pods with Repo Update Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/integration-guide.md Run this command from the ios directory to install the necessary pods and update the local repository cache. ```bash cd ios pod install --repo-update cd .. ``` -------------------------------- ### Platform-Specific Setup (Android/iOS) Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/api-reference/methods-overview.md Shows conditional setup for Android and iOS platforms, including initializing third-party push, creating channels, setting badge numbers, and configuring foreground notice modes. ```dart if (Platform.isAndroid) { await push.initAndroidThirdPush(); await push.createAndroidChannel('default', 'Default', 3, 'Notifications'); await push.setAndroidBadgeNum(0); } else if (Platform.isIOS) { final token = await push.getApnsDeviceToken(); await push.setIOSForegroundNoticeMode(ForegroundNoticeMode.showAndCallback); } ``` -------------------------------- ### Initialize Aliyun Push and Setup Callbacks Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/usage-examples.md This snippet shows the complete application entry point, including initializing the Aliyun Push SDK, setting up notification callbacks, and handling platform-specific configurations for Android and iOS. It also demonstrates how to retrieve the device ID and bind/unbind user accounts. ```dart import 'dart:io'; import 'package:flutter/material.dart'; import 'package:aliyun_push/aliyun_push.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await initializeAliyunPush(); runApp(const MyApp()); } // Global push instance final _aliyunPush = AliyunPush(); Future initializeAliyunPush() async { await _aliyunPush.setLogLevel(AliyunPushLogLevel.debug); final initResult = await _aliyunPush.initPush( appKey: Platform.isIOS ? 'IOS_APP_KEY' : 'ANDROID_APP_KEY', appSecret: Platform.isIOS ? 'IOS_APP_SECRET' : 'ANDROID_APP_SECRET', ); if (initResult['code'] != kAliyunPushSuccessCode) { print('Init failed: ${initResult['errorMsg']}'); return; } if (Platform.isAndroid) { await _aliyunPush.initAndroidThirdPush(); await _aliyunPush.createAndroidChannel( 'default_channel', 'Default Notifications', 3, 'Default notification channel for the app', ); } _setupNotificationCallbacks(); print('Aliyun Push initialized'); } void _setupNotificationCallbacks() { _aliyunPush.addMessageReceiver( onNotification: _handleNotification, onMessage: _handleMessage, onNotificationOpened: _handleNotificationOpened, onNotificationRemoved: _handleNotificationRemoved, onAndroidNotificationReceivedInApp: _handleAndroidForeground, onIOSRegisterDeviceTokenSuccess: _handleIOSTokenSuccess, onIOSRegisterDeviceTokenFailed: _handleIOSTokenFailed, ); } // Callback implementations Future _handleNotification(Map message) async { print('Notification: $message'); } Future _handleMessage(Map message) async { print('Message: $message'); } Future _handleNotificationOpened(Map message) async { print('Notification opened: $message'); // Navigate to relevant screen } Future _handleNotificationRemoved(Map message) async { print('Notification removed: $message'); } Future _handleAndroidForeground(Map message) async { print('Android foreground notification: $message'); } Future _handleIOSTokenSuccess(Map message) async { print('iOS APNs token registered: $message'); } Future _handleIOSTokenFailed(Map message) async { print('iOS APNs failed: $message'); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: HomePage(), ); } } class HomePage extends StatefulWidget { @override State createState() => _HomePageState(); } class _HomePageState extends State { String _deviceId = 'Loading...'; @override void initState() { super.initState(); _loadDeviceId(); } Future _loadDeviceId() async { final deviceId = await _aliyunPush.getDeviceId(); setState(() => _deviceId = deviceId); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Aliyun Push')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('Device ID: $_deviceId'), ElevatedButton( onPressed: _bindAccount, child: const Text('Bind Account'), ), ElevatedButton( onPressed: _unbindAccount, child: const Text('Unbind Account'), ), ], ), ), ); } Future _bindAccount() async { final result = await _aliyunPush.bindAccount('user@example.com'); if (result['code'] == kAliyunPushSuccessCode) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Account bound')), ); } } Future _unbindAccount() async { final result = await _aliyunPush.unbindAccount(); if (result['code'] == kAliyunPushSuccessCode) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Account unbound')), ); } } } ``` -------------------------------- ### Complete Aliyun Push Initialization Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/configuration.md This example demonstrates the full initialization process for the Aliyun Push Flutter plugin. It includes setting the log level, configuring platform-specific credentials, initializing push services for Android and iOS, and registering message receivers. ```dart import 'package:aliyun_push/aliyun_push.dart'; import 'dart:io'; Future initializeAliyunPush() async { final aliyunPush = AliyunPush(); // Set log level for debugging await aliyunPush.setLogLevel(AliyunPushLogLevel.debug); // Platform-specific credentials String appKey = Platform.isIOS ? "YOUR_IOS_APP_KEY" : "YOUR_ANDROID_APP_KEY"; String appSecret = Platform.isIOS ? "YOUR_IOS_APP_SECRET" : "YOUR_ANDROID_APP_SECRET"; // Initialize push final result = await aliyunPush.initPush( appKey: appKey, appSecret: appSecret ); if (result['code'] != kAliyunPushSuccessCode) { print('Push init failed: ${result['errorMsg']}'); return; } // Android: Initialize vendor channels if (Platform.isAndroid) { await aliyunPush.initAndroidThirdPush(); // Create notification channel await aliyunPush.createAndroidChannel( 'default_channel', 'Default Notifications', 3, 'Standard app notifications' ); } // iOS: Register for APNs if (Platform.isIOS) { final token = await aliyunPush.getApnsDeviceToken(); print('APNs token: $token'); } // Register callbacks aliyunPush.addMessageReceiver( onNotification: (message) async { print('Notification: $message'); }, onNotificationOpened: (message) async { print('Notification opened: $message'); }, ); print('Push initialization complete'); } ``` -------------------------------- ### Example PushCallback Implementation Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/types.md An example of how to implement and use the PushCallback type for handling opened notifications. It prints notification details and can be used with addMessageReceiver. ```dart PushCallback onNotificationOpened = (message) async { print('Notification opened: $message'); var title = message['title']; var content = message['content']; // Handle notification action return null; }; _aliyunPush.addMessageReceiver( onNotificationOpened: onNotificationOpened ); ``` -------------------------------- ### Check Flutter Environment Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/example/README.md Use these commands to verify your Flutter installation and check for available devices. Ensure your environment is correctly configured before proceeding. ```sh flutter doctor# 检查环境配置 flutter devices# 查看可用设备 ``` -------------------------------- ### Troubleshoot Pod Installation Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/integration-guide.md If you encounter pod resolution issues, try cleaning the Pods directory, removing the lock file, updating the pod repo, and then reinstalling. ```bash cd ios rm -rf Pods rm Podfile.lock pod repo update pod install cd .. ``` -------------------------------- ### Run flutter pub get Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/integration-guide.md Execute this command in your terminal after updating pubspec.yaml to fetch the new dependency. ```bash flutter pub get ``` -------------------------------- ### Usage Example with Error Code Constants Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/types.md Demonstrates how to use error code constants like kAliyunPushSuccessCode and kAliyunPushFailedCode to handle the result of the initPush operation. ```dart _aliyunPush.initPush(appKey: appKey, appSecret: appSecret) .then((result) { if (result['code'] == kAliyunPushSuccessCode) { print('Init successful'); } else if (result['code'] == kAliyunPushFailedCode) { print('Init failed: ${result['errorMsg']}'); } }); ``` -------------------------------- ### API Reference: AliyunPush Class Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/MANIFEST.md Detailed documentation for the AliyunPush class, including its constructor, initialization methods, device and account management, alias management, device tag management, callback management, and platform-specific methods. Each method includes its signature, parameters, return type, error handling, platform support, and usage examples. ```APIDOC ## Constructor ### Description Initializes the AliyunPush plugin. ### Method Constructor ### Parameters None ### Response None ## initPush ### Description Initializes the push service. ### Method `Future initPush()` ### Parameters None ### Response None ### Throws PlatformException: If initialization fails. ## setLogLevel ### Description Sets the logging level for the push service. ### Method `Future setLogLevel(AliyunPushLogLevel level)` ### Parameters - **level** (AliyunPushLogLevel) - Required - The desired logging level. ### Response None ### Throws PlatformException: If setting the log level fails. ## getDeviceId ### Description Retrieves the unique device ID for push notifications. ### Method `Future getDeviceId()` ### Parameters None ### Response - **deviceId** (String) - The unique device identifier. ### Throws PlatformException: If retrieving the device ID fails. ## bindAccount ### Description Binds the current device to a user account. ### Method `Future bindAccount(String account)` ### Parameters - **account** (String) - Required - The user account identifier. ### Response None ### Throws PlatformException: If binding the account fails. ## unbindAccount ### Description Unbinds the current device from a user account. ### Method `Future unbindAccount()` ### Parameters None ### Response None ### Throws PlatformException: If unbinding the account fails. ## addAlias ### Description Adds an alias for the current device. ### Method `Future addAlias(String alias)` ### Parameters - **alias** (String) - Required - The alias to add. ### Response None ### Throws PlatformException: If adding the alias fails. ## removeAlias ### Description Removes an alias from the current device. ### Method `Future removeAlias(String alias)` ### Parameters - **alias** (String) - Required - The alias to remove. ### Response None ### Throws PlatformException: If removing the alias fails. ## listAlias ### Description Retrieves a list of all aliases associated with the current device. ### Method `Future> listAlias()` ### Parameters None ### Response - **aliases** (List) - A list of aliases. ### Throws PlatformException: If listing aliases fails. ## bindDeviceTag ### Description Binds a tag to the current device. ### Method `Future bindDeviceTag(String tag)` ### Parameters - **tag** (String) - Required - The tag to bind. ### Response None ### Throws PlatformException: If binding the tag fails. ## unbindDeviceTag ### Description Unbinds a tag from the current device. ### Method `Future unbindDeviceTag(String tag)` ### Parameters - **tag** (String) - Required - The tag to unbind. ### Response None ### Throws PlatformException: If unbinding the tag fails. ## listDeviceTags ### Description Retrieves a list of all tags associated with the current device. ### Method `Future> listDeviceTags()` ### Parameters None ### Response - **tags** (List) - A list of tags. ### Throws PlatformException: If listing tags fails. ## addMessageReceiver ### Description Adds a message receiver callback. ### Method `void addMessageReceiver(PushCallback callback)` ### Parameters - **callback** (PushCallback) - Required - The callback function to handle incoming messages. ### Response None ### Throws None ## Android-specific methods (10 methods documented) ### Description Documentation for Android-specific methods is available in the full API reference. ## iOS-specific methods (8 methods documented) ### Description Documentation for iOS-specific methods is available in the full API reference. ``` -------------------------------- ### Setup Notification Routing with Deep Linking Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/usage-examples.md Configure AliyunPush to receive opened notifications and extract routing information from custom content to navigate within the app. Requires a NavigatorState instance. ```dart class NotificationRouter { final _aliyunPush = AliyunPush(); final NavigatorState _navigator; NotificationRouter(this._navigator); void setupRouting() { _aliyunPush.addMessageReceiver( onNotificationOpened: _handleNotificationWithLink, ); } Future _handleNotificationWithLink( Map message, ) async { final route = _extractRoute(message); if (route != null) { _navigate(route); } } String? _extractRoute(Map message) { // Extract route from custom data final customContent = message['customContent'] as String?; if (customContent == null) return null; try { final json = jsonDecode(customContent) as Map; return json['route'] as String?; } catch (e) { print('Failed to parse custom content: $e'); return null; } } void _navigate(String route) { // Navigate using the extracted route if (route == '/products/list') { _navigator.pushNamed('/products'); } else if (route.startsWith('/products/')) { final productId = route.split('/').last; _navigator.pushNamed('/product', arguments: productId); } else if (route == '/promotions') { _navigator.pushNamed('/promotions'); } } } // Usage in main.dart final notificationRouter = NotificationRouter(navigatorKey.currentState!); notificationRouter.setupRouting(); ``` -------------------------------- ### Run Flutter App on iOS Simulator Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/example/README.md Guide to running your Flutter application on an iOS simulator. This involves opening the simulator and then executing the Flutter run command. ```sh # 启动iOS模拟器 open -a Simulator # 运行Flutter应用 flutter run ``` -------------------------------- ### Add Dependency to pubspec.yaml Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/integration-guide.md Add the aliyun_push plugin to your project's pubspec.yaml file and run 'flutter pub get'. ```yaml dependencies: flutter: sdk: flutter aliyun_push: ^1.2.0 ``` -------------------------------- ### Get AliyunPush Singleton Instance Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/api-reference/aliyun-push-class.md Returns the singleton instance of AliyunPush. Multiple calls to this constructor always return the same instance. ```dart factory AliyunPush() => _instance ``` -------------------------------- ### Setup iOS Push Features Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/usage-examples.md Configures iOS-specific push notification settings, including foreground handling and APNs token retrieval. Prompts the user to enable notifications if they are disabled. ```dart class iOSPushManager { final _aliyunPush = AliyunPush(); Future setupiOSFeatures() async { if (!Platform.isIOS) return; // Set foreground notification mode await _aliyunPush.setIOSForegroundNoticeMode( ForegroundNoticeMode.showAndCallback, ); // Get APNs token final token = await _aliyunPush.getApnsDeviceToken(); print('APNs Token: $token'); // Send token to server for push targeting await _sendTokenToServer(token); // Check if notifications are enabled final opened = await _aliyunPush.isIOSChannelOpened(); if (!opened) { _promptUserToEnableNotifications(); } } Future setBadgeCount(int count) async { if (!Platform.isIOS) return; final result = await _aliyunPush.setIOSBadgeNum(count); if (result['code'] == kAliyunPushSuccessCode) { print('Badge set to $count'); } } Future syncBadgeWithServer(int count) async { if (!Platform.isIOS) return; final result = await _aliyunPush.syncIOSBadgeNum(count); if (result['code'] != kAliyunPushSuccessCode) { print('Failed to sync badge: ${result['errorMsg']}'); } } Future _sendTokenToServer(String token) async { // Implement API call to send token } void _promptUserToEnableNotifications() { // Show UI prompting user to enable notifications } } ``` -------------------------------- ### Initialize and Set Up Callbacks Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/api-reference/methods-overview.md Demonstrates the typical workflow for initializing the Aliyun Push plugin, setting up message receivers, and retrieving device information. ```dart final push = AliyunPush(); // 1. Initialize await push.initPush(appKey: key, appSecret: secret); // 2. Set up callbacks push.addMessageReceiver( onNotificationOpened: (msg) async { /* ... */ }, onMessage: (msg) async { /* ... */ } ); // 3. Get device info final deviceId = await push.getDeviceId(); // 4. Set up targeting await push.bindDeviceTag(['segment', 'vip_user']); ``` -------------------------------- ### Complete Initialization Workflow Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/INDEX.md Use this workflow to initialize the Aliyun Push SDK, set up vendor channels for Android, and register notification callbacks. ```dart final push = AliyunPush(); await push.initPush(appKey: key, appSecret: secret); if (Platform.isAndroid) { await push.initAndroidThirdPush(); await push.createAndroidChannel('default', 'Default', 3, 'Notifications'); } push.addMessageReceiver( onNotification: handleNotification, onNotificationOpened: handleOpen, ); final deviceId = await push.getDeviceId(); ``` -------------------------------- ### Set iOS Foreground Notice Mode Examples Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/types.md Examples demonstrating how to set the iOS foreground notice mode using the ForegroundNoticeMode enum. This controls whether notifications are shown and callbacks are triggered. ```dart // Show notification and trigger callback when app is in foreground await _aliyunPush.setIOSForegroundNoticeMode( ForegroundNoticeMode.showAndCallback ); // Show notification only, suppress callback await _aliyunPush.setIOSForegroundNoticeMode( ForegroundNoticeMode.showOnly ); // Trigger callback only, don't show visual notification await _aliyunPush.setIOSForegroundNoticeMode( ForegroundNoticeMode.callbackOnly ); ``` -------------------------------- ### Initialization Methods Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/api-reference/methods-overview.md Methods for initializing the SDK and configuring its basic settings. ```APIDOC ## initPush() ### Description Must be called first to initialize the SDK. ### Method Method call ### Parameters None ## setLogLevel() ### Description Optional; set debugging log level. ### Method Method call ### Parameters None ## initAndroidThirdPush() ### Description Android only; initialize vendor channels. ### Method Method call ### Parameters None ``` -------------------------------- ### Get Device ID Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/INDEX.md Retrieves the unique device identifier for push notifications. Returns a Future. ```dart getDeviceId() ``` -------------------------------- ### Initialization Methods Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/README.md Methods for initializing the push service and configuring logging verbosity. ```APIDOC ## Initialization ### `initPush()` #### Description Initializes the push service. ### `setLogLevel()` #### Description Configures logging verbosity for the push service. ``` -------------------------------- ### Initialization & Core Methods Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/INDEX.md Methods for initializing the SDK, setting log levels, and registering message receivers. ```APIDOC ## initPush() ### Description Initializes the Aliyun Push SDK. ### Method `initPush()` ### Returns `Future` - A future that resolves to a map indicating the success or failure of the initialization. ### Platform Both ``` ```APIDOC ## setLogLevel() ### Description Sets the log verbosity level for the SDK. ### Method `setLogLevel()` ### Returns `Future` - A future that resolves to a map indicating the success or failure of the operation. ### Platform Both ``` ```APIDOC ## addMessageReceiver() ### Description Registers a callback function to receive push messages. ### Method `addMessageReceiver()` ### Returns `void` ### Platform Both ``` -------------------------------- ### Initialization & Core Methods Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/MANIFEST.md Methods for initializing the push service, setting the log level, and managing message receivers. ```APIDOC ## initPush() ### Description Initializes the push service. ### Method `initPush()` ### Endpoint N/A (SDK method) ### Parameters None ### Request Example ```dart await Push.initPush(); ``` ### Response N/A ``` ```APIDOC ## setLogLevel() ### Description Sets the log level for the push service. ### Method `setLogLevel(AliyunPushLogLevel level)` ### Endpoint N/A (SDK method) ### Parameters - **level** (AliyunPushLogLevel) - Required - The desired log level (none, error, warn, info, debug). ### Request Example ```dart await Push.setLogLevel(AliyunPushLogLevel.debug); ``` ### Response N/A ``` ```APIDOC ## addMessageReceiver() ### Description Adds a receiver for push messages. ### Method `addMessageReceiver(PushCallback callback)` ### Endpoint N/A (SDK method) ### Parameters - **callback** (PushCallback) - Required - A function to handle incoming messages. ### Request Example ```dart Push.addMessageReceiver((message) async { print('Received message: $message'); }); ``` ### Response N/A ``` -------------------------------- ### Get APNs Device Token Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/INDEX.md Fetches the APNs device token for iOS devices. Returns a Future. ```dart getApnsDeviceToken() ``` -------------------------------- ### Create Aliyun Push Plugin Instance Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/integration-guide.md Instantiate the AliyunPush plugin. This is typically done once in your main application or startup logic. ```dart final _aliyunPush = AliyunPush(); ``` -------------------------------- ### initPush() Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/api-reference/aliyun-push-class.md Initializes the Alibaba Cloud Push SDK with the provided app credentials. This method must be called before using other push-related functionality. ```APIDOC ## initPush() ### Description Initializes the Alibaba Cloud Push SDK with the provided app credentials. This method must be called before using other push-related functionality. ### Method `Future> initPush({ String? appKey, String? appSecret }) async` ### Parameters #### Query Parameters - **appKey** (String) - Optional - Application key from EMAS console. Platform-specific. - **appSecret** (String) - Optional - Application secret from EMAS console. Platform-specific. ### Return Type `Future>` ### Return Map Contents - `code` (String): Error code. "10000" indicates success. - `errorMsg` (String): Error message describing any initialization failure. ### Throws/Rejects - PlatformException: If the native method channel call fails ### Example ```dart String appKey = Platform.isIOS ? "YOUR_IOS_APP_KEY" : "YOUR_ANDROID_APP_KEY"; String appSecret = Platform.isIOS ? "YOUR_IOS_APP_SECRET" : "YOUR_ANDROID_APP_SECRET"; _aliyunPush.initPush(appKey: appKey, appSecret: appSecret) .then((initResult) { var code = initResult['code']; if (code == kAliyunPushSuccessCode) { print('Push initialization successful'); } else { var errorMsg = initResult['errorMsg']; print('Push initialization failed: $errorMsg'); } }); ``` ``` -------------------------------- ### Get APNs Device Token (iOS) Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/README.md Retrieves the APNs Device Token for iOS applications. This function is exclusive to iOS platforms. ```dart _aliyunPush.getApnsDeviceToken().then((token) { }); ``` -------------------------------- ### Initialize SDK Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/INDEX.md Initializes the Aliyun Push SDK. Returns a Future upon completion. ```dart initPush() ``` -------------------------------- ### Publish to pub.dev Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/AGENTS.md Perform a dry run and then publish the package to pub.dev. ```bash fvm flutter pub publish --dry-run ``` ```bash fvm flutter pub publish ``` -------------------------------- ### Initialize AliyunPush SDK Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/api-reference/aliyun-push-class.md Initializes the Alibaba Cloud Push SDK with app credentials. Must be called before other push functionalities. Handles platform-specific app keys and secrets. ```dart String appKey = Platform.isIOS ? "YOUR_IOS_APP_KEY" : "YOUR_ANDROID_APP_KEY"; String appSecret = Platform.isIOS ? "YOUR_IOS_APP_SECRET" : "YOUR_ANDROID_APP_SECRET"; _aliyunPush.initPush(appKey: appKey, appSecret: appSecret) .then((initResult) { var code = initResult['code']; if (code == kAliyunPushSuccessCode) { print('Push initialization successful'); } else { var errorMsg = initResult['errorMsg']; print('Push initialization failed: $errorMsg'); } }); ``` -------------------------------- ### Get Device ID Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/api-reference/aliyun-push-class.md Retrieves the unique device identifier assigned by the Alibaba Cloud Push service. This ID is crucial for targeting specific devices with push notifications. ```dart Future getDeviceId() async ``` ```dart _aliyunPush.getDeviceId().then((deviceId) { print('Device ID: $deviceId'); // Save for server-side push targeting }); ``` -------------------------------- ### Initialize Alibaba Cloud Push with Platform-Specific Keys Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/configuration.md Configure the plugin by providing platform-specific app keys and secrets obtained from the Alibaba Cloud EMAS console. This ensures correct initialization for either Android or iOS. ```dart import 'dart:io'; String appKey; String appSecret; if (Platform.isIOS) { appKey = "YOUR_IOS_APP_KEY"; appSecret = "YOUR_IOS_APP_SECRET"; } else { appKey = "YOUR_ANDROID_APP_KEY"; appSecret = "YOUR_ANDROID_APP_SECRET"; } final result = await _aliyunPush.initPush( appKey: appKey, appSecret: appSecret ); ``` -------------------------------- ### Import Aliyun Push Plugin and Dart IO Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/integration-guide.md Import the necessary Aliyun Push plugin and Dart IO library at the beginning of your Dart file. ```dart import 'package:aliyun_push/aliyun_push.dart'; import 'dart:io'; ``` -------------------------------- ### initPush() Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/api-reference/methods-overview.md Initializes the push service for the device. This method should be called once during application startup to establish the connection with the push service. ```APIDOC ## initPush() ### Description Initialize push service with credentials. ### Method Future ### Parameters None ### Response #### Success Response - **Map**: A map containing initialization status and details. ``` -------------------------------- ### AliyunPush Constructor Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/api-reference/aliyun-push-class.md Provides access to the singleton instance of the AliyunPush class, which manages push notification functionality. ```APIDOC ## AliyunPush() ### Description Returns the singleton instance of AliyunPush. Multiple calls to this constructor always return the same instance. ### Returns A singleton instance of `AliyunPush` ### Example ```dart final _aliyunPush = AliyunPush(); ``` ``` -------------------------------- ### Add Aliyun Push Repository Sources to Podfile Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/integration-guide.md Add these repository sources to the top of your ios/Podfile before target declarations. This ensures CocoaPods can find the Aliyun Push specs. ```ruby source 'https://github.com/aliyun/aliyun-specs.git' source 'https://github.com/CocoaPods/Specs.git' ``` -------------------------------- ### Tag and push to GitHub Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/AGENTS.md Checkout master, pull latest changes, tag the release, and push tags to both origin and GitHub. ```bash git checkout master git pull origin master git tag x.y.z git push origin x.y.z git push github master git push github x.y.z ``` -------------------------------- ### Void Methods Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/api-reference/methods-overview.md These methods do not return any value and are typically used for performing actions or setting configurations. ```APIDOC ## addMessageReceiver ### Description Registers callbacks for receiving push messages and handling notification events. ### Method `void` ### Parameters - `callbacks` (Map) - A map containing callback functions for different push events, such as `onNotificationOpened` and `onMessage`. ``` ```APIDOC ## jumpToAndroidNotificationSettings ### Description Navigates the user directly to the Android notification settings for the application. ### Method `void` ### Parameters - `id` (String?) - Optional identifier for specific notification settings. ``` -------------------------------- ### Build verification with FVM Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/AGENTS.md Ensure consistent Flutter versions using FVM and build Android and iOS applications. ```bash fvm flutter pub get cd example fvm flutter build apk --debug fvm flutter build ios --no-codesign ``` -------------------------------- ### Initialize Aliyun Push Service Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/integration-guide.md Initialize the Aliyun Push service with platform-specific app keys and secrets. This function also handles Android-specific initializations and sets up push callbacks. ```dart Future _initAliyunPush() async { // Set log level (optional, useful for debugging) await _aliyunPush.setLogLevel(AliyunPushLogLevel.debug); // Determine platform-specific credentials String appKey; String appSecret; if (Platform.isIOS) { appKey = "YOUR_IOS_APP_KEY"; // Get from EMAS console appSecret = "YOUR_IOS_APP_SECRET"; } else { appKey = "YOUR_ANDROID_APP_KEY"; // Get from EMAS console appSecret = "YOUR_ANDROID_APP_SECRET"; } // Initialize push service final initResult = await _aliyunPush.initPush( appKey: appKey, appSecret: appSecret ); if (initResult['code'] != kAliyunPushSuccessCode) { print('Push init failed: ${initResult['errorMsg']}'); return; } // Android: Initialize vendor push channels if (Platform.isAndroid) { final thirdPushResult = await _aliyunPush.initAndroidThirdPush(); if (thirdPushResult['code'] == kAliyunPushSuccessCode) { print('Android third-party push channels initialized'); } // Create default notification channel for Android 8.0+ await _aliyunPush.createAndroidChannel( 'default_channel', 'Default Notifications', 3, // IMPORTANCE_DEFAULT 'Default notification channel' ); } // iOS: Get APNs token (for debugging/logging) if (Platform.isIOS) { final token = await _aliyunPush.getApnsDeviceToken(); print('iOS APNs Token: $token'); } // Get device ID for server-side push targeting final deviceId = await _aliyunPush.getDeviceId(); print('Device ID: $deviceId'); // Set up push callbacks _setupPushCallbacks(); print('Aliyun Push initialized successfully'); } ``` -------------------------------- ### Configure Proguard Rules Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/integration-guide.md Add these rules to your android/app/proguard-rules.pro file if your app uses code obfuscation to ensure the push plugin functions correctly. ```txt -keepclasseswithmembernames class ** { native ; } -keepattributes Signature -keep class sun.misc.Unsafe { *; } -keep class com.taobao.** {*;} -keep class com.alibaba.** {*;} -keep class com.alipay.** {*;} -keep class com.ut.** {*;} -keep class com.ta.** {*;} -keep class anet.**{*;} -keep class anetwork.**{*;} -keep class org.android.spdy.**{*;} -keep class org.android.agoo.**{*;} -keep class android.os.**{*;} -keep class org.json.**{*;} -dontwarn com.taobao.** -dontwarn com.alibaba.** -dontwarn com.alipay.** -dontwarn anet.** -dontwarn org.android.spdy.** -dontwarn org.android.agoo.** -dontwarn anetwork.** -dontwarn com.ut.** -dontwarn com.ta.** ``` -------------------------------- ### Monitor Android Push Initialization Logs Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/integration-guide.md Use adb logcat to filter and view initialization messages from Aliyun Push on Android devices or emulators. ```bash adb logcat | grep -i "aliyun\|push\|mps" ``` -------------------------------- ### Initialize Android Third-Party Push Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/INDEX.md Initializes vendor-specific push channels for Android. Returns a Future. ```dart initAndroidThirdPush() ``` -------------------------------- ### Handle createAndroidChannel() Errors Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/errors.md Illustrates error handling for createAndroidChannel(), specifically checking for unsupported platforms or Android versions, and successful creation. ```dart final result = await _aliyunPush.createAndroidChannel( 'my_channel', 'My Notifications', 3, 'Description' ); if (result['code'] == kAliyunPushNotSupport) { print('Notification channels not supported on this Android version'); } else if (result['code'] == kAliyunPushSuccessCode) { print('Channel created successfully'); } ``` -------------------------------- ### Bind and Unbind User Accounts with Aliyun Push Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/usage-examples.md This snippet demonstrates how to bind a user's account to the push service upon login and unbind it upon logout. It also includes logic for updating user segments and managing device tags. ```dart class AuthService { final _aliyunPush = AliyunPush(); Future loginUser(String email, String password) async { // Your login logic here final user = await _performLogin(email, password); // Bind push account to user ID final bindResult = await _aliyunPush.bindAccount(user.id); if (bindResult['code'] != kAliyunPushSuccessCode) { print('Failed to bind push account: ${bindResult['errorMsg']}'); // Optionally handle error - push won't work but login succeeds } // Set up user segments/tags await _updateUserSegments(user); } Future logoutUser() async { // Unbind push account final unbindResult = await _aliyunPush.unbindAccount(); if (unbindResult['code'] != kAliyunPushSuccessCode) { print('Failed to unbind: ${unbindResult['errorMsg']}'); } // Clear all tags final listResult = await _aliyunPush.listDeviceTags(); final tags = (listResult['tagsList'] as String?)?.split(',') ?? []; if (tags.isNotEmpty) { await _aliyunPush.unbindDeviceTag(tags); } // Perform actual logout await _performLogout(); } Future _updateUserSegments(User user) async { final segments = _determineUserSegments(user); await _aliyunPush.bindDeviceTag(segments); } List _determineUserSegments(User user) { final segments = []; if (user.isPremium) segments.add('premium_user'); if (user.isNewUser) segments.add('new_user'); if (user.country == 'US') segments.add('us_region'); return segments; } Future _performLogin(String email, String password) async { // Implementation throw UnimplementedError(); } Future _performLogout() async { // Implementation } } ``` -------------------------------- ### Create dev branch Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/AGENTS.md Create a new development branch from master with a specific naming convention. ```bash git checkout -b dev_x.y.z master git push -u origin dev_x.y.z ``` -------------------------------- ### Method Availability by Platform Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/api-reference/methods-overview.md This section details the availability of SDK methods across different platforms (Android and iOS). ```APIDOC ## Method Availability by Platform ### Available on Both Android and iOS - initPush - setLogLevel - getDeviceId - addMessageReceiver - bindAccount - unbindAccount - addAlias - removeAlias - listAlias - bindDeviceTag - unbindDeviceTag - listDeviceTags ### Android Only - initAndroidThirdPush - bindPhoneNumber - unbindPhoneNumber - setNotificationInGroup - clearNotifications - createAndroidChannel - createAndroidChannelGroup - isAndroidNotificationEnabled - jumpToAndroidNotificationSettings - setAndroidBadgeNum ### iOS Only - setIOSBadgeNum - syncIOSBadgeNum - getApnsDeviceToken - setIOSForegroundNoticeMode - showIOSNoticeWhenForeground (deprecated) - isIOSChannelOpened ``` -------------------------------- ### Configure Vendor Push Channels in AndroidManifest.xml Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/integration-guide.md Add meta-data tags within the tag for each vendor push service you wish to support. Replace placeholders with your actual app IDs and keys. ```xml ``` -------------------------------- ### Event Callbacks Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/api-reference/methods-overview.md Method for registering handlers to receive all push-related events. ```APIDOC ## addMessageReceiver() ### Description Register handlers for all push events. ### Method Method call ### Parameters None ``` -------------------------------- ### Automatic Plugin Configuration in Podfile Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/configuration.md The Alibaba Cloud Push Flutter plugin is automatically configured in the `ios/Podfile` via its plugin specification. No manual addition of the `aliyun_push` pod is typically needed. ```ruby # This is added automatically, no manual configuration needed pod 'aliyun_push', :path => '../' ``` -------------------------------- ### Handle initPush() Errors Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/errors.md Demonstrates how to check the result of initPush() and handle specific error codes like invalid parameters or network failures. ```dart final result = await _aliyunPush.initPush( appKey: appKey, appSecret: appSecret ); if (result['code'] != kAliyunPushSuccessCode) { final errorCode = result['code']; final errorMsg = result['errorMsg']; if (errorCode == kAliyunPushParamsIllegal) { print('Invalid credentials provided'); } else if (errorCode == kAliyunPushFailedCode) { print('Network or service error: $errorMsg'); } } ``` -------------------------------- ### setLogLevel() Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/api-reference/aliyun-push-class.md Sets the logging level for the Alibaba Cloud Push SDK output, controlling the verbosity of native logs. ```APIDOC ## setLogLevel() ### Description Sets the logging level for the Alibaba Cloud Push SDK output. Controls verbosity of native logs. ### Method `Future> setLogLevel( AliyunPushLogLevel level ) async` ### Parameters #### Query Parameters - **level** (AliyunPushLogLevel) - Required - Desired log level enum value ### Return Type `Future>` ### Return Map Contents - `code` (String): Error code. "10000" indicates success. - `errorMsg` (String): Error message if setting log level fails. ### Throws/Rejects - PlatformException: If the native method channel call fails ### Example ```dart _aliyunPush.setLogLevel(AliyunPushLogLevel.debug) .then((result) { var code = result['code']; if (code == kAliyunPushSuccessCode) { print('Log level set successfully'); } else { print('Failed to set log level: ${result['errorMsg']}'); } }); ``` ``` -------------------------------- ### Create Multiple Android Notification Channels and Groups Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/usage-examples.md This snippet demonstrates how to set up default, high priority, and promotional notification channels, as well as create a channel group. It includes error handling for channel creation. ```dart class AndroidNotificationChannels { final _aliyunPush = AliyunPush(); Future setupChannels() async { if (!Platform.isAndroid) return; // Default channel await _createChannel( id: 'default', name: 'General Notifications', importance: 3, description: 'General app notifications', ); // High priority channel (sound + vibration) await _createChannel( id: 'high_priority', name: 'Important Alerts', importance: 4, description: 'Important alerts requiring immediate attention', vibration: true, light: true, lightColor: 0xFF0000FF, ); // Promotional channel (silent) await _createChannel( id: 'promotions', name: 'Promotions', importance: 2, description: 'Promotional and marketing notifications', vibration: false, ); // Create channel group await _aliyunPush.createAndroidChannelGroup( 'notification_groups', 'Notification Categories', 'Organize notifications by category', ); } Future _createChannel({ required String id, required String name, required int importance, required String description, bool? vibration, bool? light, int? lightColor, }) async { final result = await _aliyunPush.createAndroidChannel( id, name, importance, description, vibration: vibration, light: light, lightColor: lightColor, ); if (result['code'] != kAliyunPushSuccessCode) { print('Failed to create channel $id: ${result['errorMsg']}'); } } Future checkAndRequestPermissions() async { if (!Platform.isAndroid) return; final enabled = await _aliyunPush.isAndroidNotificationEnabled(); if (!enabled) { // Show dialog explaining why notifications are needed _showNotificationDialog(); } } void _showNotificationDialog() { // Show a dialog and jump to settings if user agrees _aliyunPush.jumpToAndroidNotificationSettings(); } Future setBadgeNumber(int count) async { if (!Platform.isAndroid) return; final result = await _aliyunPush.setAndroidBadgeNum(count); if (result['code'] != kAliyunPushSuccessCode) { print('Badge not supported: ${result['errorMsg']}'); } } } ``` -------------------------------- ### Run Flutter App on Android Emulator Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/example/README.md Steps to launch an Android emulator and run your Flutter application on it. This includes listing available emulators and launching a specific one. ```sh # 启动Android模拟器 #1. 查看可用Android模拟器 flutter emulators # 2. 启动Android模拟器 flutter emulators --launch Pixel_7_API_34 # 然后执行: flutter run # 或指定设备: flutter run -d ``` -------------------------------- ### Callbacks Source: https://github.com/aliyun/alibabacloud-push-flutter-plugin/blob/master/_autodocs/README.md Method for registering callbacks to receive incoming notifications. ```APIDOC ## Callbacks ### `addMessageReceiver()` #### Description Registers a callback function to receive incoming push messages and events. ```