Flutter推送服务插件pushpushgo_sdk的使用
Flutter推送服务插件pushpushgo_sdk的使用
官方PushPushGo SDK客户端适用于Flutter应用(iOS、Android)
重要
版本1.0.0+的破坏性更改
- 为了能够使用v1.0.0+,您需要向您的iOS项目目标添加AppGroups功能。
支持平台
- iOS
- Android
要求
- PPG项目
- 访问Firebase控制台
- 访问Apple开发者控制台
- 对于iOS - 使用Cocoapods(或其他包管理器)
集成时间(不包括进一步实现):约2-3小时
环境设置
确保已经安装了flutter,并且flutter doctor
命令通过。
$ flutter doctor
如果没有异常,则可以继续下一步。
1. 在现有应用程序中添加SDK
1.1 安装flutter包
$ flutter pub add pushpushgo_sdk
1.2 向main.dart
文件中添加代码
1.2.1 导入库
import 'package:pushpushgo_sdk/pushpushgo_sdk.dart';
1.2.2 初始化客户端
在您的主应用程序类中声明并初始化PPG客户端:
final pushpushgo = PushpushgoSdk({
"apiToken": "my-api-key-from-pushpushgo-app",
"projectId": "my-project-id-from-pushpushgo-app",
"appGroupId": "your-app-group-id-from-provisioning-profile" // 从v1.0.0+开始需要
});
pushpushgo.initialize(onNewSubscriptionHandler: (subscriberId) {
log(subscriberId);
});
然后用您的PPG项目的凭证填充apiToken
和projectId
。
注意: 如果您想查看测试应用程序的集成示例,请访问:https://github.com/ppgco/flutter-example-integration
2. iOS支持
2.1 在Xcode中打开Podfile
文件(位于/ios/
目录下)
接下来的步骤使用Cocoapods包管理器。
确保您的最低部署平台版本至少为14.0
在target 'Runner' do
声明的末尾添加以下内容:
pod 'PPG_framework', :git => 'https://github.com/ppgco/ios-sdk.git'
之后,在终端中导航到您的Flutter项目的ios/
目录并运行命令:
$ pod install
2.2 使用XCode打开ios/
目录
$ xed ios/
2.2.1 在项目目标中启用推送通知功能
- 选择文件树中名为
<strong>your_project_name</strong>
的根项(带有蓝色图标),并在Target
部分选择<strong>your_project_name</strong>
。 - 前往
Signing & Capabilities
选项卡并点击<strong>+ Capability</strong>
。 - 选择
<strong>Push Notifications</strong>
、<strong>Background Modes</strong>
和<strong>AppGroups (from v1.0.0+)</strong>
。 - 在
<strong>Background Modes</strong>
中选择以下项目:- Remote notifications
- Background fetch
2.2.2 添加NotificationServiceExtension
- 前往文件 -> 新建 -> 目标
- 搜索
<strong>Notification Service Extension</strong>
并选择产品名称,例如<strong>NSE</strong>
。 - 完成过程并点击
<strong>Cancel</strong>
以取消激活<strong>NSE</strong>
方案。 - 打开
NotificationService.swift
文件。 - 粘贴以下代码:
import UserNotifications
import PPG_framework
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
guard let content = bestAttemptContent else { return }
// 等待交付事件结果及图像获取后再从扩展程序返回
let group = DispatchGroup()
group.enter()
group.enter()
// 填写您的应用组ID
SharedData.shared.appGroupId = "YOUR APP GROUP ID"
PPG.notificationDelivered(notificationRequest: request) { _ in
group.leave()
}
DispatchQueue.global().async { [weak self] in
self?.bestAttemptContent = PPG.modifyNotification(content)
group.leave()
}
group.notify(queue: .main) {
contentHandler(self.bestAttemptContent ?? content)
}
}
override func serviceExtensionTimeWillExpire() {
// 当系统即将终止扩展程序时调用。
// 这是一个机会,提供您的“最佳尝试”修改内容,否则将使用原始推送有效负载。
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}
- 将
NotificationServiceExtension
目标添加到Podfile
中: 使用您创建的文件名 - 在我们的情况下是NSE
:
target 'NSE' do
use_frameworks!
use_modular_headers!
pod 'PPG_framework', :git => 'https://github.com/ppgco/ios-sdk.git'
end
- 再次在终端中导航到您的Flutter项目的
ios/
目录并运行命令:
$ pod install
- (可选)在
Info.plist
中添加以下内容以启用深度链接:
<key>FlutterDeepLinkingEnabled</key>
<true/>
2.3 准备证书
- 前往Apple Developer Portal - Identifiers并进入
Identifiers
部分。 - 从列表中选择您的应用Bundle ID,如
com.example.your_project_name
。 - 查找
PushNotifications
并点击<strong>Configure</strong>
按钮。 - 选择您的
Certificate Signing Request
文件。 - 下载证书并双击在macOS中打开。
- 在密钥链访问中找到此证书,右键单击选择导出为
.p12
格式文件并输入密码。 - 登录到应用程序并上传此
<code>Certificate.p12</code>
文件及其密码(https://next.pushpushgo.com/projects/YourProjectID/settings/integration/fcm)。
对于手动证书生成,请参阅我们的教程:https://docs.pushpushgo.company/application/providers/mobile-push/apns
3. Android支持
3.1 Firebase CLI
- 安装Firebase CLI - 打开终端并运行命令:
$ curl -sL https://firebase.tools | bash
- 安装FlutterFire CLI - 打开终端并运行命令:
$ dart pub global activate flutterfire_cli
- 在终端中登录到Firebase:
$ firebase login
- 导航到您的Flutter项目的根目录并运行:
$ flutterfire configure --project=your-firebase-project-id
按照终端中提供的说明进行操作。
注意:如果无法使用flutterfire命令,请将export PATH="$PATH":"$HOME/.pub-cache/bin"
添加到您的.zshrc文件中。
3.2 在根build.gradle
文件中添加代码(/android/build.gradle
)
添加jitpack和huawei仓库:
// build.gradle (root) 或 settings.gradle (dependencyResolutionManagement)
allprojects {
repositories {
// jitpack
maven { url 'https://jitpack.io' }
// 仅当使用HMS时
maven { url 'https://developer.huawei.com/repo/' }
}
}
对于HMS添加:
dependencies {
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
}
警告: 如果您遇到来自pushpushgo_sdk的包名错误,请添加以下代码:
subprojects { subproject ->
if (subproject.name == "pushpushgo_sdk") {
subproject.afterEvaluate {
subproject.android {
namespace 'com.pushpushgo.pushpushgo_sdk'
}
}
}
}
3.3 向AndroidManifest.xml
中添加代码
该文件位于android/app/src/main/
目录下。
3.3.1 在主活动级别添加活动
<intent-filter>
<action android:name="APP_PUSH_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
如果您没有自定义的应用程序文件:
3.3.2 在<application>
标签中添加
<application
android:name=".MainApplication"
...>
并创建名为<code>MainApplication</code>
的文件,内容如下:
package ...;
import com.pushpushgo.pushpushgo_sdk.PushPushGoHelpers
import io.flutter.app.FlutterApplication
class MainApplication: FlutterApplication() {
override fun onCreate() {
PushPushGoHelpers.initialize(this)
super.onCreate()
}
}
如果需要深度链接,可添加:
<meta-data android:name="flutter_deeplinking_enabled" android:value="true" />
3.4 向MainActivity
中添加逻辑
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import com.pushpushgo.pushpushgo_sdk.PushPushGoHelpers
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
@RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
private fun requestNotificationsPermission() {
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.POST_NOTIFICATIONS
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this,
arrayOf<String>(Manifest.permission.POST_NOTIFICATIONS),
0
)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestNotificationsPermission();
}
PushPushGoHelpers.onCreate(this.application, intent, savedInstanceState)
}
override fun onNewIntent(intent: Intent) {
PushPushGoHelpers.onNewIntent(this.application, intent)
}
}
3.4 修改build.gradle
在build.gradle
(应用级别)中添加依赖项:
3.4.1 对于FCM
// build.gradle (:app)
dependencies {
...
implementation "com.github.ppgco.android-sdk:sdk:2.0.6"
implementation platform('com.google.firebase:firebase-bom:33.3.0')
implementation 'com.google.firebase:firebase-messaging'
}
3.4.2 对于HMS
dependencies {
...
implementation "com.github.ppgco.android-sdk:sdk:2.0.6"
implementation 'com.huawei.agconnect:agconnect-core:1.7.0.300'
implementation 'com.huawei.hms:push:6.5.0.300'
}
在顶部添加:
将以下内容粘贴在com.android.library
下方:
id 'com.huawei.agconnect'
3.5 生成FCM v1凭据并将其上传到PPG应用
- 前往您的Firebase控制台并导航至项目设置。
- 打开云消息传递标签。
- 点击“管理服务帐户”。
- 点击您的服务帐户电子邮件。
- 导航到“密钥”标签。
- 点击“添加密钥”。
- 点击“创建新密钥”。
- 选择JSON类型并点击创建。
- 下载文件并上传到PushPushGo应用(https://next.pushpushgo.com/projects/YourProjectID/settings/integration/fcm)。
可用方法
// 订阅通知
_pushpushgo.registerForNotifications();
// 取消订阅通知
_pushpushgo.unregisterFromNotifications();
// 获取订阅者ID
_pushpushgo.getSubscriberId();
// 发送订阅者的信标
_pushpushgo.sendBeacon(
Beacon(
tags: {
Tag.fromString("my:tag"),
Tag(
key: "myaa",
value: "aaaa",
strategy: "append",
ttl: 1000)
},
tagsToDelete: {},
customId: "my_id",
selectors: {"my": "data"}
)
);
示例代码
import 'dart:log';
import 'package:flutter/material.dart';
import 'package:pushpushgo_sdk/beacon.dart';
import 'dart:async';
import 'package:pushpushgo_sdk/pushpushgo_sdk.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _pushpushgo = PushpushgoSdk({"apiToken": "my-api-key", "projectId": "my-project-id"});
[@override](/user/override)
void initState() {
super.initState();
initialize();
}
// 平台消息是异步的,因此我们在异步方法中初始化。
Future<void> initialize() async {
// 待定逻辑
_pushpushgo.initialize(onNewSubscriptionHandler: (subscriberId) {
log("MY SUBSCRIBER ID IS");
log(subscriberId);
});
if (!mounted) return;
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
routes: {
'/': (context) => HomeScreen(pushpushgo: _pushpushgo),
'/details': (context) => const DetailScreen(),
},
);
}
}
class HomeScreen extends StatelessWidget {
final PushpushgoSdk pushpushgo;
const HomeScreen({
super.key,
required this.pushpushgo,
});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('插件示例应用'),
),
body: Column(
children: [
Center(
child: ElevatedButton(
child: const Text("转到详情屏幕"),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const DetailScreen(),
),
);
})),
Center(
child: ElevatedButton(
child: const Text("获取订阅者ID"),
onPressed: () async {
var result = await pushpushgo.getSubscriberId();
log('获取订阅者ID结果');
log(result as String);
})),
Center(
child: ElevatedButton(
child: const Text("发送随机信标"),
onPressed: () async {
var result = await pushpushgo.sendBeacon(Beacon(
tags: {
Tag.fromString("my:tag"),
Tag(
key: "myaa",
value: "aaaa",
strategy: "append",
ttl: 1000)
},
tagsToDelete: {},
customId: "my_id",
selectors: {"my": "data"}));
log('信标结果');
log(result as String);
})),
Center(
child: ElevatedButton(
child: const Text("注册"),
onPressed: () {
pushpushgo.registerForNotifications();
})),
Center(
child: ElevatedButton(
child: const Text("取消注册"),
onPressed: () {
pushpushgo.unregisterFromNotifications();
})),
],
)),
);
}
}
class DetailScreen extends StatelessWidget {
const DetailScreen({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('插件示例应用'),
),
body: const Center(child: Text("详情屏幕")),
),
);
}
}
更多关于Flutter推送服务插件pushpushgo_sdk的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter推送服务插件pushpushgo_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
pushpushgo_sdk
是一个用于集成推送服务的 Flutter 插件,它可以帮助开发者在 Flutter 应用中实现推送通知功能。以下是如何使用 pushpushgo_sdk
插件的基本步骤:
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 pushpushgo_sdk
插件的依赖:
dependencies:
flutter:
sdk: flutter
pushpushgo_sdk: ^1.0.0 # 请使用最新版本
然后运行 flutter pub get
来获取依赖。
2. 初始化 SDK
在 main.dart
文件中初始化 pushpushgo_sdk
。通常,你会在 main
函数中初始化 SDK:
import 'package:flutter/material.dart';
import 'package:pushpushgo_sdk/pushpushgo_sdk.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 初始化 PushPushGo SDK
await PushPushGoSdk.initialize(
apiKey: 'YOUR_API_KEY',
projectId: 'YOUR_PROJECT_ID',
);
runApp(MyApp());
}
请确保将 YOUR_API_KEY
和 YOUR_PROJECT_ID
替换为你在 PushPushGo 控制台中获取的实际值。
3. 请求通知权限
在 iOS 设备上,你需要请求用户允许发送通知。你可以在应用启动时或在某个页面中请求权限:
import 'package:pushpushgo_sdk/pushpushgo_sdk.dart';
void requestNotificationPermission() async {
await PushPushGoSdk.requestNotificationPermission();
}
4. 处理推送通知
你可以监听推送通知的点击事件,并在用户点击通知时执行相应的操作。通常,你会在应用的某个地方(如 initState
中)设置监听器:
import 'package:flutter/material.dart';
import 'package:pushpushgo_sdk/pushpushgo_sdk.dart';
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
PushPushGoSdk.onNotificationOpened.listen((notification) {
// 处理通知点击事件
print('Notification opened: $notification');
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('PushPushGo Example'),
),
body: Center(
child: Text('Hello, PushPushGo!'),
),
),
);
}
}
5. 发送测试通知
你可以在 PushPushGo 控制台中发送测试通知,或者通过 API 发送通知来测试集成是否成功。
6. 处理后台通知
如果你的应用在后台或关闭时需要处理通知,你可以在 PushPushGoSdk.initialize
中设置 backgroundHandler
:
PushPushGoSdk.initialize(
apiKey: 'YOUR_API_KEY',
projectId: 'YOUR_PROJECT_ID',
backgroundHandler: (notification) async {
// 处理后台通知
print('Background notification: $notification');
},
);