Flutter推送服务插件umeng_push_sdk的使用

Flutter推送服务插件umeng_push_sdk的使用

集成

在工程 pubspec.yaml 中加入依赖项:

dependencies:
  umeng_push_sdk: ^2.3.0

配置

Android/android/app/build.gradle 中添加下列代码:

android {
    defaultConfig {
        applicationId "您的应用包名"

        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a'
        }

        manifestPlaceholders = [
            UMENG_APPKEY: '您申请的appkey',
            UMENG_MESSAGE_SECRET: '您申请的message secret',
            UMENG_CHANNEL: '您的应用发布渠道',

            HUAWEI_APP_ID: '您申请的华为通道appid',

            HONOR_APP_ID: '您申请的荣耀通道appid',

            XIAOMI_APP_ID: '您申请的小米通道appid',
            XIAOMI_APP_KEY: '您申请的小米通道appkey',

            OPPO_APP_KEY: '您申请的OPPO通道appkey',
            OPPO_APP_SECRET: '您申请的OPPO通道app secret',

            VIVO_APP_ID: '您申请的VIVO通道appid',
            VIVO_APP_KEY: '您申请的VIVO通道appkey',

            MEIZU_APP_ID: '您申请的魅族通道appid',
            MEIZU_APP_KEY: '您申请的魅族通道appkey',
        ]
    }
}

厂商消息下发时,Activity路径传入:com.umeng.message.UmengOfflineMessageActivity

iOS 证书配置请参考文档:https://developer.umeng.com/docs/67966/detail/66748

AppDelegate.m中需要进行的配置:

  1. didFinishLaunchingWithOptions 方法中设置消息代理。
  2. 处理 willPresentNotification 方法回调。
  3. 处理 didReceiveNotificationResponse 方法回调。
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [GeneratedPluginRegistrant registerWithRegistry:self];
    [UNUserNotificationCenter currentNotificationCenter].delegate=self;
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {

    NSDictionary * userInfo = notification.request.content.userInfo;

    [UmengPushSdkPlugin didReceiveUMessage:userInfo];
    if ([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [UMessage setAutoAlert:NO];
        // 应用处于前台时 的远程推送接收
        // 必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
    } else {
        // 应用处于前台时 的本地推送接收
    }

    // 控制推送消息是否直接在前台显示
   completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler {
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    // 应用后台或者关闭时收到消息,回调flutter层onNotificationOpen方法
    [UmengPushSdkPlugin didOpenUMessage:userInfo];

    if ([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        // 应用处于后台时 的远程推送接收
        // 必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
    } else {
        // 应用处于后台时 的本地推送接收
    }
}
@endimplementation

使用

import 'package:umeng_common_sdk/umeng_common_sdk.dart';
import 'package:umeng_push_sdk/umeng_push_sdk.dart';

import 'helper.dart';

void main() => runApp(MyApp());

class _PushState extends State<Push> with AutomaticKeepAliveClientMixin {
  TextEditingController controller = TextEditingController();

  late Map<String, VoidCallback?> methods;

  int badgeNumber = 0;

  void registerPush() {
    UmengPushSdk.setLogEnable(true);
    UmengCommonSdk.initCommon(
        "5b960fb5a40fa3332e000082",
        "5f69a20ba246501b677d0923",
        "AppStore",
        "de1a922ad7c8a23d3adcf5daac38c3f");
    UmengPushSdk.register("5f69a20ba2446501b677d0923", "AppStore");
  }

  [@override](/user/override)
  void initState() {
    super.initState();
    methods = {
      // 模拟同意隐私政策
      'agree': () async { UmengHelper.agree().then((value) =&gt; registerPush()); },
      // 注册
      'register': () async { registerPush(); },
      // 获取DeviceToken
      'getDeviceToken': () async { String? deviceToken = await UmengPushSdk.getRegisteredId(); if (deviceToken != null) { controller.text += deviceToken + "\n"; } },
      // 添加别名
      'addAlias': () async { controller.text += (await UmengPushSdk.addAlias("myAlias", "SINA_WEIBO")).toString() + "\n"; },
      // 移除别名
      'removeAlias': () async { controller.text += (await UmengPushSdk.removeAlias("myAlias", "SINA_WEIBO")).toString() + "\n"; },
      // 绑定别名
      'setAlias': () async { controller.text += (await UmengPushSdk.setAlias("myAlias", "SINA_WEIBO")).toString(), },
      // 添加标签
      'addTags': () async { controller.text += (await UmengPushSdk.addTags(["myTag1", "myTag2", "myTag3"])).toString() + "\n"; },
      // 移除标签
      'removeTags': () async { controller.text += (await UmengPushSdk.removeTags(["myTag1", "myTag2", "myTag3"])).toString() + "\n"; },
      // 获取已设置的标签
      'getAllTags': () async { controller.text += (await UmengPushSdk.getTags()).toString() + "\n"; },
      // 打开推送功能
      'openPush': () async { UmengPushSdk.setPushEnable(true); },
      // 关闭推送功能
      'closePush': () async { UmengPushSdk.setPushEnable(false); },
      // 清空日志
      'clear': () { controller.text = ""; },
    };

    // 设置deviceToken回调
    UmengPushSdk.setTokenCallback((deviceToken) { print("$_TAG deviceToken:$deviceToken"); controller.text += deviceToken + "\n"; });

    // 设置自定义消息回调
    UmengPushSdk.setMessageCallback((msg) { print("$_TAG receive custom:$msg"); controller.text += msg + "\n"; });

    // 设置通知消息回调
    UmengPushSdk.setNotificationCallback((receive) { print("$_TAG receive:$receive"); controller.text += "receive:$receive\n"; }, (open) { print("$_TAG open:$open"); controller.text += "open:$open\n"; });

    UmengHelper.isAgreed().then((value) { if (value!) { registerPush(); } });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        appBar: AppBar(
          title: Text('PushSample'),
        ),
        body: Center(
          child: Column(
            children: [
              TextField(
                maxLines: 5,
                controller: controller,
              ),
              Expanded(
                  child: Wrap(
                runSpacing: 10,
                spacing: 10,
                children: methods.keys.map((e) { return ElevatedButton(child: Text(e), onPressed: methods[e]); }).toList(),
              )),
            ],
          ),
        ));
  }

  [@override](/user/override)
  bool get wantKeepAlive => true;
}

class Push extends StatefulWidget {
  [@override](/user/override)
  State&lt;StatefulWidget&gt; createState() {
    return _PushState();
  }
}

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() =&gt; _MyAppState();
}

class _MyAppState extends State&lt;MyApp&gt; {
  var _pageController = PageController();

  final _bodyList = [
    Push(),
  ];

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: PageView(
          controller: _pageController,
          children: _bodyList,
          onPageChanged: pageControllerTap,
          physics: NeverScrollableScrollPhysics(),
        ),
      ),
    );
  }

  void pageControllerTap(int index) {
    setState(() {});
  }

  void onTap(int index) {
    _pageController.jumpToPage(index);
  }
}

更多关于Flutter推送服务插件umeng_push_sdk的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter推送服务插件umeng_push_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中集成和使用Umeng Push SDK(umeng_push_sdk)的示例代码案例。这个示例将展示如何配置插件、初始化推送服务以及处理推送消息。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加umeng_push_sdk依赖:

dependencies:
  flutter:
    sdk: flutter
  umeng_push_sdk: ^最新版本号 # 请替换为实际的最新版本号

然后运行flutter pub get来获取依赖。

2. 配置Android项目

2.1 在android/app/src/main/AndroidManifest.xml中添加权限和Umeng Push相关的配置:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <!-- 其他配置 -->

    <!-- 添加权限 -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.VIBRATE"/>

    <!-- Umeng Push Service -->
    <service
        android:name="com.umeng.message.reg.Service"
        android:exported="true">
        <intent-filter>
            <action android:name="com.umeng.message.intent.action.REGISTER" />
        </intent-filter>
    </service>
    <service
        android:name="com.umeng.message.reg.DeviceInfoReportService"
        android:exported="true"/>
    <receiver android:name="com.umeng.message.PushBroadcastReceiver" android:exported="true">
        <intent-filter>
            <action android:name="com.umeng.message.client.action.CLICK"/>
            <action android:name="com.umeng.message.client.action.DISMISS"/>
            <action android:name="com.umeng.message.client.action.DOWNLOAD_PROGRESS"/>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        </intent-filter>
    </receiver>
    <receiver android:name="com.umeng.message.UmengNotificationClickedReceiver" android:exported="true">
        <intent-filter>
            <action android:name="com.umeng.message.action.NOTIFICATION_CLICKED" />
        </intent-filter>
    </receiver>

    <!-- 其他配置 -->

</manifest>

2.2 在android/app/build.gradle中添加Umeng的key配置:

android {
    // ...
    defaultConfig {
        // ...
        manifestPlaceholders = [
                UMENG_APPKEY: "你的Umeng App Key", // 替换为你的Umeng App Key
                UMENG_CHANNEL: "your_channel"      // 替换为你的渠道标识
        ]
    }
}

3. 配置iOS项目

3.1 在ios/Runner/Info.plist中添加Umeng Push所需的配置:

<key>UMENG_APPKEY</key>
<string>你的Umeng App Key</string> <!-- 替换为你的Umeng App Key -->
<key>UMENG_CHANNEL</key>
<string>your_channel</string> <!-- 替换为你的渠道标识 -->

3.2 确保你的iOS项目已经配置了推送通知权限,在ios/Runner/AppDelegate.swiftAppDelegate.m中添加必要的代码(这里以Swift为例):

import UIKit
import UserNotifications
import flutter_umeng_push // 导入Umeng Push插件的iOS模块

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)
        
        // 注册推送通知
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if let error = error {
                print("推送通知注册失败: \(error.localizedDescription)")
            } else if granted {
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            }
        }
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    
    // 处理收到的远程通知
    override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        UMengPushAgent.default().handleRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)
    }
    
    // 处理前台收到的远程通知
    override func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound])
    }
}

4. 初始化Umeng Push并在Flutter中使用

在你的Flutter项目的main.dart文件中初始化Umeng Push并处理推送消息:

import 'package:flutter/material.dart';
import 'package:umeng_push_sdk/umeng_push_sdk.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    // 初始化Umeng Push
    UmengPush.init(
      androidKey: "你的Umeng App Key", // 仅在Android上需要
      iosKey: "你的Umeng App Key", // 仅在iOS上需要(如果与Android相同,可以省略)
      channel: "your_channel",
    );

    // 监听推送消息
    UmengPush.onMessageReceived.listen((message) {
      print("收到推送消息: $message");
      // 在这里处理收到的推送消息
    });

    // 监听推送点击事件
    UmengPush.onNotificationClicked.listen((notification) {
      print("点击了推送通知: $notification");
      // 在这里处理点击事件,例如导航到特定页面
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Umeng Push Demo'),
        ),
        body: Center(
          child: Text('等待推送消息...'),
        ),
      ),
    );
  }
}

以上代码展示了如何在Flutter项目中集成和使用Umeng Push SDK。请确保你已经正确配置了Umeng后台以及你的应用权限。

回到顶部