推送消息不打烊--Flutter集成个推SDK实现Android和IOS原生推送


theme: condensed-night-purple
highlight: a11y-dark

嗨!这里是甜瓜看代码,大家五一快乐呀,这篇文章跟大家聊聊怎么集成个推。

Flutter集成个推SDK

  个推是一款支持多平台的推送服务平台,Flutter提供了多个第三方库来支持个推SDK的集成,其中最为常用的是 flutter_getui 库。

安装

pubspec.yaml 文件中添加以下依赖:

dependencies:
  flutter_getui: ^4.1.0

然后执行以下命令:

$ flutter pub get

配置

安卓配置

  1. android/app/build.gradle 文件中添加以下代码:
android {
    defaultConfig {
        //...
        manifestPlaceholders = [
            GETUI_APP_ID: "<your_app_id>",
            GETUI_APP_KEY: "<your_app_key>",
            GETUI_APP_SECRET: "<your_app_secret>"
        ]
    }
}

  将 <your_app_id>, <your_app_key>, <your_app_secret> 替换为个推官网申请的应用ID、应用Key和应用Secret。

  1. AndroidManifest.xml 文件中添加以下权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_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" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

iOS配置

Info.plist 文件中添加以下代码:

<key>com.getui.demo.appid</key>
<string><your_app_id></string>
<key>com.getui.demo.appkey</key>
<string><your_app_key></string>
<key>com.getui.demo.appsecret</key>
<string><your_app_secret></string>

  将 <your_app_id>, <your_app_key>, <your_app_secret> 替换为个推官网申请的应用ID、应用Key和应用Secret。

使用

  在Flutter应用中使用个推SDK需要在启动时初始化SDK,并在需要接收推送消息的页面注册推送消息回调函数。

以下是一个简单的示例代码,用于在Flutter应用中发送和接收推送消息:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterGetui.startUp(); // 初始化SDK
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '个推示例',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String message = '';

  
  void initState() {
    super.initState();
    FlutterGetui.addEventHandler(
      onReceiveMessage: (Map<String, dynamic> message) async {
        setState(() {
          this.message = message.toString();
       
  },
  //还有很多回调方法,自己可以看
    );
  }

  void sendPushMessage() {
    // 构造推送消息
    PushMessage message = PushMessage(
      title: '测试标题',
      content: '测试内容',
      payload: '测试负载',
    );
    // 发送推送消息
    FlutterGetui.sendPushMessage(message);
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('个推示例'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: sendPushMessage,
              child: Text('发送推送消息'),
            ),
            SizedBox(height: 20),
            Text(
              message,
              style: TextStyle(fontSize: 16),
            ),
          ],
        ),
      ),
    );
  }
}

  在上述代码中,我们首先在 main() 函数中初始化个推SDK,然后在 HomePage 中注册推送消息回调函数,并在 sendPushMessage() 函数中构造并发送推送消息。

  当应用接收到推送消息时,onReceiveMessage() 回调函数会被调用,并将推送消息的内容传递给它。在上述代码中,我们将推送消息的内容显示在了应用界面上,以方便调试。

总结

  使用 flutter_getui 库集成个推SDK可以很方便地在Flutter应用中实现推送消息的发送和接收。在使用过程中,需要注意在安卓和iOS平台上分别配置相应的参数和权限。

  希望本文能对你理解如何集成个推SDK提供一些帮助。这里是甜瓜看代码,期待你的关注!

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是Flutter集成极光推送的步骤: 1. 在极光官网注册账号并创建应用,获取AppKey。 2. 在Flutter项目中添加极光推送插件,如:jpush_flutter。 3. 在AndroidManifest.xml文件中添加以下代码: ```xml <!-- 极光推送权限 --> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- 极光推送服务 --> <service android:name="cn.jpush.android.service.PushService" android:enabled="true" android:exported="false" android:process=":pushcore" > <intent-filter> <action android:name="cn.jpush.android.intent.REGISTER" /> <action android:name="cn.jpush.android.intent.REPORT" /> <action android:name="cn.jpush.android.intent.PushService" /> <action android:name="cn.jpush.android.intent.PUSH_TIME" /> </intent-filter> </service> <receiver android:name="cn.jpush.android.service.PushReceiver" android:enabled="true" android:exported="false" > <intent-filter android:priority="1000"> <action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED_PROXY" /> <category android:name="你的包名" /> </intent-filter> <intent-filter> <action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED_PROXY" /> <category android:name="你的包名" /> </intent-filter> <intent-filter> <action android:name="cn.jpush.android.intent.REGISTRATION" /> <category android:name="你的包名" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.USER_PRESENT" /> <category android:name="你的包名" /> </intent-filter> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <category android:name="你的包名" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.PACKAGE_ADDED" /> <data android:scheme="package" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.PACKAGE_REMOVED" /> <data android:scheme="package" /> </intent-filter> </receiver> ``` 4. 在iOS项目中,到极光官网下载JPush SDK并导入到项目中,在AppDelegate.m文件中添加以下代码: ```objective-c #import "JPUSHService.h" // iOS 10 及以上需导入 UserNotifications.framework #import <UserNotifications/UserNotifications.h> // Override point for customization after application launch. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 初始化 JPush SDK [JPUSHService setupWithOption:launchOptions appKey:@"your_appkey" channel:nil apsForProduction:NO]; return YES; } // 注册APNs成功并上报DeviceToken - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [JPUSHService registerDeviceToken:deviceToken]; } // 实现注册APNs失败接口 - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error); } // 添加处理APNs通知回调方法 #ifdef NSFoundationVersionNumber_iOS_9_x_Max // iOS 10之前收到通知 - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { // Required, iOS 7 Support [JPUSHService handleRemoteNotification:userInfo]; completionHandler(UIBackgroundFetchResultNewData); } // iOS 10之前收到本地通知 - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { // Required, iOS 7 Support [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil]; } // iOS 10及以上收到通知 - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler { NSDictionary * userInfo = notification.request.content.userInfo; if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { [JPUSHService handleRemoteNotification:userInfo]; } completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound); } // iOS 10及以上收到本地通知 - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler { NSDictionary * userInfo = response.notification.request.content.userInfo; if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { [JPUSHService handleRemoteNotification:userInfo]; } completionHandler(); } #endif ``` 5. 在Flutter代码中,初始化JPush并监听推送事件: ```dart import 'package:jpush_flutter/jpush_flutter.dart'; // 初始化JPush JPush jpush = new JPush(); // 监听推送事件 jpush.addEventHandler( onReceiveNotification: (Map<String, dynamic> message) async { print("Flutter onReceiveNotification: $message"); }, onOpenNotification: (Map<String, dynamic> message) async { print("Flutter onOpenNotification: $message"); }, onReceiveMessage: (Map<String, dynamic> message) async { print("Flutter onReceiveMessage: $message"); }, ); // 启动JPush jpush.setup( appKey: "your_appkey", // 极光官网申请的AppKey channel: "developer-default", // 渠道,默认值为“developer-default” production: false, // 是否生产环境 debug: true, // 是否开启调试模式 ); ``` 以上就是Flutter集成极光推送的步骤,希望能对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值