Flutter消息推送插件izooto_plugin的使用

Flutter消息推送插件izooto_plugin的使用

1. 简介

iZooto 提供了移动应用的消息推送服务。通过 izooto_plugin 插件,您可以轻松地在基于 Flutter 框架构建的 Android 和 iOS 应用中实现消息推送功能。

2. 安装与快速开始

2.1 添加依赖

要将 iZooto Flutter SDK 添加到您的项目中,请编辑项目的 pubspec.yaml 文件:

dependencies:
  izooto_plugin: ^2.5.6
2.2 安装 SDK

运行以下命令以安装 SDK:

flutter packages get
2.3 导入 SDK

在 Dart 代码中使用以下导入语句:

import 'package:izooto_plugin/iZooto_flutter.dart';

3. SDK 方法

请参考 iZooto Flutter SDK 参考文档 获取可用的回调和方法。

4. 支持

如果您在设置过程中遇到问题,请访问 iZooto 官方网站 或发送邮件至 support@izooto.com 获取帮助。

5. 示例项目

我们提供了一个示例项目,位于此仓库的 /example 文件夹中,您可以参考该示例项目来了解如何使用 iZooto Flutter SDK。

6. 支持的平台

  • 测试并验证了从 Android 5.0 (API level 21) 到 Android 13 (API level 33)。
  • 测试并验证了从 iOS 12 到 iOS 15+。

7. 完整示例 Demo

以下是一个完整的示例项目,展示了如何使用 iZooto Flutter SDK 实现消息推送功能。

import 'dart:collection';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:izooto_plugin/iZooto_flutter.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Home(title: 'HomePage'),
      routes: {
        'pageTwo': (context) => PageTwo(title: 'Page Two'),
      },
    );
  }
}

class Home extends StatefulWidget {
  final String title;
  Home({required this.title});

  [@override](/user/override)
  _HomeState createState() => new _HomeState();
}

class _HomeState extends State<Home> {
  static const platform = const MethodChannel("iZooto-flutter");

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: const Center(
        child: Text(
          'HomePage',
          style: TextStyle(color: Colors.green, fontSize: 20),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        autofocus: true,
        focusElevation: 5,
        child: const Icon(Icons.notifications),
        onPressed: () {
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => const SecondRoute()));
          // iZooto.navigateToSettings();
          iZooto.setSubscription(false);
          print("Unsuscribe false");
        },
      ),
    );
  }

  void initMethod() async {
    // 初始化 Android
    iZooto.androidInit(false);
    // 请求推送通知权限
    iZooto.promptForPushNotifications();
    
    // OneTap 方法调用
    iZooto.requestOneTapActivity();
    iZooto.shared.oneTapResponse((response) {
      print('DATA -> ' + response.toString());
      // 解析 JSON 字符串
      Map<String, dynamic> jsonString = jsonDecode(response.toString());
      // 获取值
      String email = jsonString['email'];
      String firstName = jsonString['firstName'];
      String lastName = jsonString['lastName'];
      // 打印值
      print('Email: $email');
      print('First Name: $firstName');
      print('Last Name: $lastName');
    });

    // 同步用户详细信息
    iZooto.syncUserDetailsEmail("abc1@gmail.com", "Test1", "Demo1");

    if (Platform.isIOS) {
      // 初始化 iOS
      iZooto.iOSInit(
        appId: "6d6292461db5888f4c10172c0767541a40e2175c", // 替换为您的 iOS App ID
      );
    }

    // 监听接收到的通知
    iZooto.shared.onNotificationReceived((payload) {
      print('PayLoad >>  $payload');
    });

    // 监听打开的通知
    iZooto.shared.onNotificationOpened((data) {
      print('Data >>  $data');
      Navigator.push(context,
          MaterialPageRoute(builder: (context) => const SecondRoute()));
    });

    // 监听 WebView URL
    iZooto.shared.onWebView((landingUrl) {
      print('Landing URL >>  $landingUrl');
      Navigator.push(context,
          MaterialPageRoute(builder: (context) => const SecondRoute()));
    });

    // 监听设备令牌
    iZooto.shared.onTokenReceived((token) {
      print('Token >>  $token ');
    });

    try {
      // iOS 深链接处理(应用被杀死状态)
      String value = await platform.invokeMethod("OpenNotification");
      if (value != null) {
        print('iZooto Killed state ios data : $value ');
        Navigator.push(context, MaterialPageRoute(builder: (context) => const SecondRoute()));
      }
    } catch (e) {}
  }
}

Future<dynamic> onPush(String name, Map<String, dynamic> payload) {
  return Future.value(true);
}

// class PageTwo extends StatefulWidget {
//   final String title;
//   PageTwo({required this.title});
//   [@override](/user/override)
//   _PageTwoState createState() => new _PageTwoState();
// }

// class _PageTwoState extends State<PageTwo> {
//   [@override](/user/override)
//   Widget build(BuildContext context) {
//     return Scaffold(
//       appBar: AppBar(
//         title: Text(widget.title),
//       ),
//       body: Center(
//         child: Text('Page Two'),
//       ),
//       floatingActionButton: FloatingActionButton(
//         autofocus: true,
//         focusElevation: 5,
//         child: const Icon(Icons.notifications),
//         onPressed: () {
//           // iZooto.setNewsHub();
//         },
//       ),
//     );
//   }
// }

class SecondRoute extends StatelessWidget {
  const SecondRoute();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Second Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            iZooto.setSubscription(true);
            Navigator.pop(context);
            print("Subscribe True");
          },
          child: const Text('Go back!'),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是一个关于如何在Flutter项目中使用izooto_plugin进行消息推送的示例代码。izooto_plugin允许你向Flutter应用用户发送推送通知。请注意,这只是一个基础示例,实际项目中可能需要根据具体需求进行调整和扩展。

首先,确保你已经在pubspec.yaml文件中添加了izooto_plugin依赖:

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

然后,运行flutter pub get来安装依赖。

接下来,你需要配置AndroidManifest.xmlInfo.plist文件以启用推送服务。这里只展示Android的配置,iOS的配置类似,需要按照izooto的官方文档进行设置。

AndroidManifest.xml

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

    <!-- 其他配置 -->

    <application
        android:label="yourapp"
        android:icon="@mipmap/ic_launcher">
        
        <!-- 添加izooto接收器 -->
        <receiver android:name="com.izooto.android.sdk.IZootoGCMReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.example.yourapp" />
            </intent-filter>
        </receiver>

        <!-- 其他配置 -->
        
    </application>

    <!-- 添加权限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <permission android:name="com.example.yourapp.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="com.example.yourapp.permission.C2D_MESSAGE" />

</manifest>

在Flutter代码中,你可以按照以下步骤初始化并使用izooto_plugin

main.dart

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

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

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

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _initializeIzooto();
  }

  Future<void> _initializeIzooto() async {
    // 替换为你的App Key和App Secret
    String appKey = "你的AppKey";
    String appSecret = "你的AppSecret";

    try {
      await IzootoPlugin.initialize(appKey: appKey, appSecret: appSecret);
      print("Izooto initialized successfully.");

      // 监听推送点击事件
      IzootoPlugin.onMessageOpened.listen((message) {
        print("Message opened: ${message.toMap()}");
        // 根据需要处理消息点击事件
      });

      // 监听推送接收事件
      IzootoPlugin.onMessageReceived.listen((message) {
        print("Message received: ${message.toMap()}");
        // 根据需要处理消息接收事件
      });
    } catch (e) {
      print("Error initializing Izooto: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Izooto Plugin Demo'),
        ),
        body: Center(
          child: Text('Check the console for Izooto events.'),
        ),
      ),
    );
  }
}

在上面的代码中,我们首先初始化了izooto_plugin,提供了App Key和App Secret。然后,我们监听了两个事件:onMessageOpenedonMessageReceived,分别在用户点击推送通知和接收到推送通知时触发。

请确保你已经从Izooto平台获取了正确的App Key和App Secret,并且已经按照Izooto的官方文档完成了所有必要的配置。

这个示例仅展示了基本的初始化和事件监听,你可以根据需求进一步扩展功能,比如处理不同类型的推送消息、自定义通知样式等。

回到顶部