Flutter推送通知插件airship_flutter的使用

发布于 1周前 作者 gougou168 来自 Flutter

Flutter推送通知插件 airship_flutter 的使用

资源

问题反馈

如果您在集成或使用此模块时遇到任何问题,请访问 Airship 支持页面

示例 Demo

下面是一个完整的示例,展示了如何在 Flutter 应用中使用 airship_flutter 插件来处理推送通知。

主文件 main.dart

import 'package:flutter/material.dart' hide Notification;
import 'package:airship_flutter/airship_flutter.dart';
import 'package:flutter/services.dart' show DeviceOrientation, SystemChrome;

// 导入其他页面和样式
import 'styles.dart';
import 'screens/home.dart';
import 'screens/message_center.dart';
import 'screens/preference_center.dart';
import 'screens/settings.dart';

// Supported deep links
const String home_deep_link = "home";
const String message_center_deep_link = "message_center";
const String settings_deep_link = "settings";

@pragma('vm:entry-point')
Future<void> backgroundMessageHandler(PushReceivedEvent event) async {
  debugPrint("Background Push Received $event");
}

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);

  var config = AirshipConfig(
    androidConfig: AndroidConfig(
        notificationConfig: AndroidNotificationConfig(
      icon: "ic_notification",
    )),
    defaultEnvironment: ConfigEnvironment(
        appKey: "APP_KEY",
        appSecret: "APP_SECRET",
        logLevel: LogLevel.verbose,
        ios: IOSEnvironment(logPrivacyLevel: AirshipLogPrivacyLevel.public)),
  );

  Airship.takeOff(config);
  Airship.push.android.setBackgroundPushReceivedHandler(backgroundMessageHandler);

  Airship.push.iOS.setForegroundPresentationOptions([
    IOSForegroundPresentationOption.banner,
    IOSForegroundPresentationOption.list
  ]);
  Airship.contact.identify("FlutterUser");

  Airship.messageCenter.setAutoLaunchDefaultMessageCenter(false);
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
  late TabController controller;
  final GlobalKey<NavigatorState> key = GlobalKey();

  @override
  void initState() {
    super.initState();
    controller = TabController(length: 4, vsync: this);
    initPlatformState();
    addFlutterTag();
    trackFeatureFlagInteraction();
  }

  static void trackFeatureFlagInteraction() {
    Airship.featureFlagManager.flag("rad_flag").then((flag) {
      Airship.featureFlagManager.trackInteraction(flag);
    }).catchError((e) {
      debugPrint('Error: $e');
    });
  }

  static void addFlutterTag() {
    Airship.channel.addTags(["flutter"]);
  }

  Future<void> initPlatformState() async {
    Airship.push.onPushReceived.listen((event) {
      debugPrint('Push Received $event');
    });

    Airship.push.onNotificationResponse.listen((event) {
      debugPrint('Notification Response $event');
    });

    Airship.push.onPushTokenReceived.listen((event) {
      debugPrint('Push token received $event');
    });

    Airship.push.onNotificationStatusChanged.listen((event) {
      debugPrint('Notification status changed $event');
    });

    Airship.push.iOS.onAuthorizedSettingsChanged.listen((event) {
      debugPrint('Authorized settings changed $event');
    });

    Airship.push.iOS.authorizedNotificationSettings.then((value) =>
        debugPrint("authorizedNotificationSettings $value"));
    Airship.push.iOS.authorizedNotificationStatus.then((value) =>
        debugPrint("authorizedNotificationStatus $value"));

    Airship.onDeepLink.listen((event) {
      const home_tab = 0;
      const message_tab = 1;
      const settings_tab = 2;

      switch (event.deepLink) {
        case home_deep_link:
          controller.animateTo(home_tab);
          break;
        case message_center_deep_link:
          controller.animateTo(message_tab);
          break;
        case settings_deep_link:
          controller.animateTo(settings_tab);
          break;
      }
    });

    Airship.inApp.onEmbeddedInfoUpdated
        .listen((event) => debugPrint('Embedded info updated $event'));

    Airship.messageCenter.onInboxUpdated
        .listen((event) => debugPrint('Inbox updated $event'));

    Airship.messageCenter.onDisplay.listen((event) {
      key.currentState?.push(MaterialPageRoute<void>(builder: (BuildContext context) {
        return event.messageId != null
            ? MessageView(messageId: event.messageId ?? "")
            : SizedBox();
      }));
    });

    Airship.channel.onChannelCreated.listen((event) {
      debugPrint('Channel created $event');
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      navigatorKey: key,
      title: "Airship Sample App",
      theme: ThemeData(
        primaryColor: Styles.borders,
        colorScheme: ColorScheme.fromSwatch().copyWith(
          secondary: Styles.airshipBlue,
        ),
        switchTheme: SwitchThemeData(
          trackColor: WidgetStateProperty.all(Styles.airshipBlue),
        ),
      ),
      initialRoute: "/",
      routes: {
        '/': (context) => tabBarView(),
      },
    );
  }

  Widget bottomNavigationBar() {
    return Container(
      color: Styles.borders,
      child: SafeArea(
        bottom: true,
        child: Material(
          color: Colors.transparent,
          child: Container(
            color: Styles.borders,
            child: TabBar(
              indicatorColor: Styles.airshipRed,
              unselectedLabelColor: Colors.grey,
              labelColor: Styles.airshipBlue,
              tabs: const <Tab>[
                Tab(icon: Icon(Icons.home)),
                Tab(icon: Icon(Icons.inbox)),
                Tab(icon: Icon(Icons.menu)),
                Tab(icon: Icon(Icons.settings)),
              ],
              controller: controller,
            ),
          ),
        ),
      ),
    );
  }

  Widget tabBarView() {
    return PopScope(
      onPopInvoked: null,
      child: Scaffold(
        backgroundColor: Styles.borders,
        body: TabBarView(
          controller: controller,
          children: const <Widget>[
            Home(),
            MessageCenter(),
            PreferenceCenter(),
            Settings()
          ],
        ),
        bottomNavigationBar: bottomNavigationBar(),
      ),
    );
  }
}

样式文件 styles.dart

class Styles {
  static const Color borders = Color(0xFFECECEC);
  static const Color airshipBlue = Color(0xFF007AFF);
  static const Color airshipRed = Color(0xFFD32F2F);
}

其他页面

你需要创建以下页面:

  • home.dart
  • message_center.dart
  • preference_center.dart
  • settings.dart

这些页面可以根据你的应用需求进行定制。上面的代码已经包含了对这些页面的基本引用。

配置

确保你已经在 AndroidManifest.xmlInfo.plist 中正确配置了推送通知权限,并且在 Airship 控制台中设置了正确的应用密钥和密钥。

通过以上步骤,你应该能够在 Flutter 应用中成功集成并使用 airship_flutter 插件来处理推送通知。


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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用airship_flutter插件来实现推送通知的基本代码示例。airship_flutter是Urban Airship提供的官方Flutter插件,用于集成Urban Airship的推送通知服务。

前提条件

  1. Urban Airship账号:确保你已经在Urban Airship注册并创建了一个应用。
  2. Flutter环境:确保你的Flutter环境已经配置好,并且你有一个正在开发的Flutter项目。

步骤

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  airship_flutter: ^版本号  # 替换为最新版本号

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

2. 配置Android

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

    <application
        ... >

        <service
            android:name="com.urbanairship.push.PushService"
            android:exported="true">
            <intent-filter>
                <action android:name="com.urbanairship.push.ACTION_PUSH_RECEIVED" />
            </intent-filter>
        </service>

        <receiver android:name="com.urbanairship.CoreReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.PACKAGE_REPLACED" />
                <action android:name="com.urbanairship.ACTION_CHANNEL_UPDATED" />
            </intent-filter>
        </receiver>

        <!-- 其他配置 -->

    </application>
</manifest>

android/app/build.gradle中添加Urban Airship的Maven仓库和依赖:

android {
    ...
    defaultConfig {
        ...
        manifestPlaceholders = [
                'UA_APP_KEY': '你的Urban Airship应用密钥',
                'UA_APP_SECRET': '你的Urban Airship应用密钥密文'
        ]
    }
}

repositories {
    google()
    jcenter()
    maven { url 'https://maven.urbanairship.com/content/repositories/releases/' }
}

dependencies {
    implementation 'com.urbanairship:urbanairship-sdk:版本号'  // 替换为最新版本号
}

3. 配置iOS

ios/Runner/Info.plist中添加必要的权限声明:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>

ios/Podfile中添加Urban Airship的Pod依赖:

platform :ios, '10.0'

target 'Runner' do
  use_frameworks!
  
  # Pods for Runner
  pod 'UrbanAirship-iOS-SDK', '~> 版本号'  # 替换为最新版本号
end

然后运行pod install

4. 初始化Urban Airship

在你的Flutter项目的main.dart或合适的初始化位置,添加以下代码来初始化Urban Airship:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化Urban Airship
  await Airship.instance.configure({
    "developmentAppKey": "你的开发App Key",
    "developmentAppSecret": "你的开发App Secret",
    "productionAppKey": "你的生产App Key",
    "productionAppSecret": "你的生产App Secret",
    "inProduction": false // 根据环境设置
  });

  // 注册设备
  await Airship.instance.registerDevice();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '等待推送通知...',
            ),
          ],
        ),
      ),
    );
  }
}

注意事项

  1. 替换密钥:确保替换所有示例代码中的App KeyApp Secret为你的Urban Airship应用的实际密钥。
  2. 调试与生产环境:根据你的开发环境(调试或生产),设置inProductiontruefalse
  3. 推送通知处理:你可能需要处理推送通知的接收和显示,这可以通过监听Urban Airship的事件来实现。

这个示例提供了一个基本的框架,你可以根据具体需求进一步扩展和定制。

回到顶部