Flutter消息推送插件flutter_emas_push的使用

Flutter消息推送插件flutter_emas_push的使用

如何使用

build.gradle中配置推送密钥

build.gradle文件中配置阿里云的appKeyappSecret,以及其他厂商的推送密钥。

defaultConfig {
    applicationId "com.kevin.emaspush.flutter_emas_push_example" // 申请key的包名
    ...
    manifestPlaceholders = [
            emasPushAppKey   : "", // 阿里云的appKey
            emasPushAppSecret: "", // 阿里云的appSecret
            huaweiAppId      : "", // 华为的一定要配置签名文件
            miAppId          : "",
            miAppKey         : "",
            oppoAppKey       : "",
            oppoAppSecret    : "",
            vivoAppKey       : "",
            vivoAppId        : "", // 数字的要用反斜杠\\123456
            meizuAppId       : "",
            meizuAppKey      : "",
            sendId           : "", // GCM
            applicatinoId    : "", // GCM
            projectId        : "", // GCM
            apiKey           : ""  // GCM
    ]
}

build.gradle中配置签名信息(华为推送需要)

signingConfigs {
    debug {
        storeFile file('xxx') // 签名文件路径
        storePassword 'xxx' // 密码
        keyAlias 'xxx' // 别名
        keyPassword 'xxx' // 密钥密码
    }
    release {
        storeFile file('xxx') // 签名文件路径
        storePassword 'xxx' // 密码
        keyAlias 'xxx' // 别名
        keyPassword 'xxx' // 密钥密码
    }
}

AndroidManifest.xml中添加必要的配置(VIVO推送需要)

如果发现离线时无法收到推送,请检查以下配置:

<activity android:name=".PopupPushActivity" android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <!-- VIVO一定要配置applicationId -->
        <data android:host="${applicationId}" android:path="/thirdpush" android:scheme="agoo" />
    </intent-filter>
</activity>

如果点击通知时需要跳转到MainActivity,可以使用以下代码替代PopupPushActivity

PopupNotifyClick { title, summary, extMap ->
    Log.d("MainActivity", "Receive notification, title: $title, content: $summary, extraMap:$extMap")
}.onCreate(this, this.intent)

初始化推送服务

如果在manifestPlaceholders中已配置好密钥,可以直接使用registerWithMetaData方法进行初始化:

FlutterEmasPush.initPush();
// Android 8.0及以上需要设置通知渠道ID和名称
FlutterEmasPush.setNotificationChannelIdAndName("123456", "androidTest");
FlutterEmasPush.registerWithMetaData();

注册指定平台推送

支持注册华为、小米、OPPO、魅族、VIVO和GCM等推送服务:

FlutterEmasPush.registerOppo("", "");
FlutterEmasPush.registerXiaomi("", "");
FlutterEmasPush.registerHuawei();
FlutterEmasPush.registerMeizu();
FlutterEmasPush.registerGCM("", "", "", "");

绑定或解绑账号、标签和别名

绑定和解绑账号、标签和别名的操作:

FlutterEmasPush.bindAccount('testAccount');
FlutterEmasPush.unbindAccount();

FlutterEmasPush.bindTag(1, ['tags'], 'alias');
FlutterEmasPush.unbindTag(1, ['tags'], 'alias');

FlutterEmasPush.addAlias('alias');
FlutterEmasPush.removeAlias('alias');

接收在线通知

当应用处于在线状态时,可以通过监听onNotificationOpened事件接收推送通知:

_initPushMethodCallHandler() async {
  var channel = FlutterEmasPush.channel;
  channel.setMethodCallHandler((call) async {
    switch (call.method) {
      case 'onNotificationOpened':
        debugPrint('notificationOpened===========${call.arguments}');
        break;
    }
  });
}

显示日志或设置EMAS日志级别

显示日志并设置EMAS的日志级别:

FlutterEmasPush.showLog(kDebugMode);
FlutterEmasPush.showEMASLogLevel(2);

取消通知

取消所有通知或通过ID取消特定通知:

FlutterEmasPush.cancelNotification();
FlutterEmasPush.cancelNotificationById("10");

ProGuard规则配置

如果在发布带有混淆的版本时遇到崩溃问题,可以在proguard-rules.pro中添加以下规则:

-keepclasseswithmembernames class ** {
    native <methods>;
}
-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.**

# 华为通道
-keep class com.huawei.** { *; }
-dontwarn com.huawei.**

# 小米通道
-keep class com.xiaomi.** { *; }
-dontwarn com.xiaomi.**

# OPPO通道
-keep public class * extends android.app.Service

# 魅族通道
-keep class com.meizu.cloud.** { *; }
-dontwarn com.meizu.cloud.**

# VIVO通道
-keep class com.vivo.** { *; }
-dontwarn com.vivo.**

# GCM/FCM通道
-keep class com.google.firebase.** { *; }
-dontwarn com.google.firebase.**

完整示例代码

以下是一个完整的示例代码,展示了如何使用flutter_emas_push插件:

import 'dart:math';

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

import 'package:flutter/services.dart';
import 'package:flutter_emas_push/flutter_emas_push.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }

  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion =
          await FlutterEmasPush.platformVersion ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }
    if (!mounted) return;
    setState(() {
      _platformVersion = platformVersion;
    });
  }

  initPush() async {
    FlutterEmasPush.initPush();
    FlutterEmasPush.setNotificationChannelIdAndName("123456", "androidTest");
    FlutterEmasPush.registerWithMetaData();
  }

  registerOppo() async {
    FlutterEmasPush.registerOppo("", "");
  }

  bindAccount() async {
    FlutterEmasPush.bindAccount('testAccount');
  }

  unBindAccount() async {
    FlutterEmasPush.unbindAccount();
  }

  bindTag() async {
    FlutterEmasPush.bindTag(1, ['tags'], 'alias');
  }

  unbindTag() async {
    FlutterEmasPush.unbindTag(1, ['tags'], 'alias');
  }

  addAlias() async {
    FlutterEmasPush.addAlias('alias');
  }

  removeAlias() async {
    FlutterEmasPush.removeAlias('alias');
  }

  testPush() async {
    FlutterEmasPush.showLog(true);
    FlutterEmasPush.setNotificationChannelIdAndName("123456", "androidTest");
    var bool = await FlutterEmasPush.canShowNotification();
    print('hello===$bool');
    if (bool) {
      FlutterEmasPush.showNotification(
          "测试${Random().nextInt(100)}",
          "测试内容${Random().nextInt(100)}",
          "{\"_ALIYUN_NOTIFICATION_ID_\":\"542992\",\"mobileId\":\"27203753f1e1d4892143c6d8ce86867a\",\"_ALIYUN_NOTIFICATION_MSG_ID_\":\"8004229324234496\",\"id\":\"582\",\"businessType\":\"QEUBEELIVE\",\"_ALIYUN_NOTIFICATION_PRIORITY_\":\"1\"}",
          "${Random().nextInt(10000)}");
    } else {
      FlutterEmasPush.goSettingNotificationPage();
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: [
            Text('Running on: $_platformVersion\n'),
            ElevatedButton(
                onPressed: () {
                  initPush();
                },
                child: Text('initPush')),
            ElevatedButton(
                onPressed: () {
                  registerOppo();
                },
                child: Text('registerOppo')),
            ElevatedButton(
                onPressed: () {
                  testPush();
                },
                child: Text('testPush')),
            ElevatedButton(
                onPressed: () {
                  FlutterEmasPush.registerWithMetaData();
                },
                child: Text('registerWithMetaData')),
            ElevatedButton(
                onPressed: () {
                  FlutterEmasPush.cancelNotification();
                },
                child: Text('cancelNotification')),
            ElevatedButton(
                onPressed: () {
                  FlutterEmasPush.showNotification("测试指定Id", "id是10", "ext", "10");
                },
                child: Text('showSpecificNotificationById')),
            ElevatedButton(
                onPressed: () {
                  FlutterEmasPush.cancelNotificationById("10");
                },
                child: Text('cancelNotificationById')),
          ],
        ),
      ),
    );
  }
}
1 回复

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


flutter_emas_push 是一个用于在 Flutter 应用中集成阿里云移动推送(EMAS Push)的插件。通过该插件,你可以轻松地在 Flutter 应用中实现消息推送功能。以下是使用 flutter_emas_push 插件的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 flutter_emas_push 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_emas_push: ^1.0.0  # 请使用最新版本

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

2. 配置 Android 项目

android/app/build.gradle 文件中,确保你已经添加了阿里云推送的依赖:

dependencies {
    implementation 'com.aliyun.ams:alicloud-android-push:3.1.8'  // 请使用最新版本
}

android/app/src/main/AndroidManifest.xml 文件中,添加必要的权限和推送服务配置:

<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.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:name=".MyApplication"
        ...>
        
        <meta-data
            android:name="com.aliyun.push.appKey"
            android:value="your_app_key" />
        <meta-data
            android:name="com.aliyun.push.appSecret"
            android:value="your_app_secret" />

        <service
            android:name="com.aliyun.push.PushService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.aliyun.push.action.PUSH_SERVICE" />
            </intent-filter>
        </service>

        <receiver
            android:name="com.aliyun.push.NotificationReceiver"
            android:exported="false">
            <intent-filter>
                <action android:name="com.aliyun.push.action.NOTIFICATION_OPENED" />
            </intent-filter>
        </receiver>

    </application>
</manifest>

3. 配置 iOS 项目

ios/Runner/Info.plist 文件中,添加推送相关的配置:

<key>CFBundleIdentifier</key>
<string>com.example.yourapp</string>

<key>CFBundleVersion</key>
<string>1.0.0</string>

<key>CFBundleShortVersionString</key>
<string>1.0</string>

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>

4. 初始化推送服务

在 Flutter 应用的 main.dart 文件中,初始化推送服务:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化推送服务
  await FlutterEmasPush.init(
    appKey: 'your_app_key',
    appSecret: 'your_app_secret',
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter EMAS Push Demo',
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter EMAS Push Demo'),
      ),
      body: Center(
        child: Text('Hello, EMAS Push!'),
      ),
    );
  }
}

5. 处理推送消息

你可以通过监听推送消息来处理用户点击通知或接收到的消息:

FlutterEmasPush.onMessageReceived.listen((Map<String, dynamic> message) {
  print("Received message: $message");
  // 处理接收到的消息
});

FlutterEmasPush.onNotificationOpened.listen((Map<String, dynamic> message) {
  print("Notification opened: $message");
  // 处理用户点击通知
});

6. 获取设备 Token

你可以通过以下方式获取设备的推送 Token:

String deviceToken = await FlutterEmasPush.getDeviceToken();
print("Device Token: $deviceToken");
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!