Flutter推送通知插件amplify_push_notifications_pinpoint的使用
Flutter推送通知插件amplify_push_notifications_pinpoint的使用
插件介绍
amplify_push_notifications_pinpoint
是Amplify Flutter Push Notifications类别的一个插件,它使用AWS Pinpoint作为提供者。该插件支持Android、iOS平台的通知推送功能。
平台支持情况
Category | Android | iOS | Web | Windows | MacOS | Linux |
---|---|---|---|---|---|---|
Analytics | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
API (REST) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
API (GraphQL) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Authentication | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
DataStore | ✅ | ✅ | 🔴 | 🔴 | 🔴 | 🔴 |
Storage | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Notifications | ✅ | ✅ | 🔴 | 🔴 | 🔴 | 🔴 |
开始使用
要了解更多关于AWS Amplify的信息,请访问我们的官方网站。
示例代码
以下是一个完整的示例demo,演示如何在Flutter项目中集成和使用amplify_push_notifications_pinpoint
插件。
主文件:main.dart
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// ignore_for_file: avoid_print
import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
import 'package:amplify_flutter/amplify_flutter.dart';
import 'package:amplify_push_notifications_pinpoint/amplify_push_notifications_pinpoint.dart';
import 'package:flutter/material.dart';
import 'amplifyconfiguration.dart';
Future<void> myCallback(PushNotificationMessage notification) async {
print('🚀 onNotificationReceivedInBackground callback: $notification');
await Future<void>.delayed(const Duration(seconds: 5));
print(
' 🚀 onNotificationReceivedInBackground callback: delayed for 5 seconds to complete',
);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
try {
final authPlugin = AmplifyAuthCognito();
final notificationsPlugin = AmplifyPushNotificationsPinpoint();
// Needs to be given in the main function here so iOS can wire up the callback when the app wakes up from killed state
notificationsPlugin.onNotificationReceivedInBackground(myCallback);
if (!Amplify.isConfigured) {
await Amplify.addPlugins([authPlugin, notificationsPlugin]);
await Amplify.configure(amplifyconfig);
// Required to call this after Amplify.configure.
// Doesn't get called on app start as event is swallowed by library to register device.
Amplify.Notifications.Push.onTokenReceived.listen((event) {
print('🚀 onTokenReceived $event');
});
// Required to call this after Amplify.configure.
Amplify.Notifications.Push.onNotificationReceivedInForeground
.listen((event) {
print('🚀 onNotificationReceivedInForeground $event');
});
// Required to call this after Amplify.configure.
Amplify.Notifications.Push.onNotificationOpened.listen((event) {
print('🚀 onNotificationOpened $event');
});
}
} on Exception catch (e) {
safePrint(e.toString());
}
AmplifyLogger().logLevel = LogLevel.info;
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool isConfigured = false;
bool isForegroundListenerInitialized = false;
bool isBackgroundListenerInitialized = false;
bool notificationOpenedListenerInitialized = false;
int globalBgCallbackCount = 0;
PushNotificationMessage? foregroundMessage;
PushNotificationMessage? backgroundMessage;
PushNotificationMessage? notificationOpenedMessage;
PushNotificationPermissionStatus? getPermissionStatus;
bool? requestPermissionsResult;
PushNotificationMessage? launchNotificationAvailable;
void getLaunchNotification() {
setState(() {
launchNotificationAvailable =
Amplify.Notifications.Push.launchNotification;
});
}
Widget headerText(String title) => Padding(
padding: const EdgeInsets.only(top: 16),
child: Center(
child: Text(
title,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Amplify Push Notifications Pinpoint Example'),
),
body: Center(
child: ListView(
children: [
headerText('Permissions APIs'),
ElevatedButton(
onPressed: () async {
final status =
await Amplify.Notifications.Push.getPermissionStatus();
setState(() {
getPermissionStatus = status;
});
},
child: const Text('getPermissionStatus'),
),
if (getPermissionStatus != null)
Text('Permission status: $getPermissionStatus'),
ElevatedButton(
onPressed: () async {
final result =
await Amplify.Notifications.Push.requestPermissions();
setState(() {
requestPermissionsResult = result;
});
},
child: const Text('requestPermissions'),
),
if (requestPermissionsResult != null)
Text(
'Requesting permission result: $requestPermissionsResult',
),
const Divider(
height: 20,
),
headerText('Analytics APIs'),
ElevatedButton(
onPressed: () async {
await Amplify.Notifications.Push.identifyUser(
userId: 'test-user-101',
userProfile: const UserProfile(name: 'test-name-101'),
);
},
child: const Text('identifyUser'),
),
const Divider(
height: 20,
),
headerText('Notification Handling APIs'),
ElevatedButton(
onPressed: getLaunchNotification,
child: const Text('get Launch Notification'),
),
if (launchNotificationAvailable != null)
ListTile(
title: Text(
'launchNotificationAvailable: $launchNotificationAvailable',
),
),
],
),
),
),
);
}
}
配置文件:amplifyconfiguration.dart
确保你已经配置了Amplify,并且拥有正确的配置文件。以下是amplifyconfiguration.dart
的一个示例:
import 'package:amplify_core/amplify_core.dart';
const amplifyconfig = '''{
"UserAgent": "aws-amplify-cli/2.0",
"Version": "1.0",
"analytics_pinpoint": {
"AWSPinpointAnalytics": {
"appId": "YOUR_PINPOINT_APP_ID",
"region": "YOUR_PINPOINT_REGION"
}
},
"auth": {
"plugins": {
"awsCognitoAuthPlugin": {
"UserAgent": "aws-amplify-cli/0.1.0",
"Version": "0.1.0",
"IdentityManager": {
"Default": {}
},
"CredentialsProvider": {
"CognitoIdentity": {
"Default": {
"PoolId": "YOUR_COGNITO_POOL_ID",
"Region": "YOUR_COGNITO_REGION"
}
}
},
"CognitoUserPool": {
"Default": {
"PoolId": "YOUR_USER_POOL_ID",
"AppClientId": "YOUR_APP_CLIENT_ID",
"AppClientSecret": "YOUR_APP_CLIENT_SECRET",
"Region": "YOUR_USER_POOL_REGION"
}
},
"Auth": {
"Default": {
"authenticationFlowType": "USER_SRP_AUTH"
}
}
}
}
}
}''';
请将上述代码中的占位符替换为你的实际AWS资源ID和区域信息。
通过以上步骤,你应该能够在Flutter应用中成功集成并使用amplify_push_notifications_pinpoint
插件来处理推送通知。
更多关于Flutter推送通知插件amplify_push_notifications_pinpoint的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter推送通知插件amplify_push_notifications_pinpoint的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中使用amplify_push_notifications_pinpoint
插件来实现推送通知的示例代码。这个插件是AWS Amplify的一部分,用于通过Amazon Pinpoint发送推送通知。
前提条件
- AWS Amplify 设置:确保你已经在AWS Amplify控制台中设置了你的项目,并配置了Amazon Pinpoint。
- Flutter 环境:确保你的Flutter环境已经配置好,并且你的项目已经初始化。
步骤
1. 添加依赖
首先,在你的pubspec.yaml
文件中添加amplify_push_notifications_pinpoint
依赖:
dependencies:
flutter:
sdk: flutter
amplify_flutter: ^0.x.x # 确保使用与amplify_push_notifications_pinpoint兼容的版本
amplify_push_notifications_pinpoint: ^0.x.x # 替换为最新版本
然后运行flutter pub get
来安装依赖。
2. 配置Amplify
在你的lib
目录下创建一个新的Dart文件,比如amplify_configuration.dart
,并添加以下代码来配置Amplify:
import 'package:amplify_flutter/amplify.dart';
import 'package:amplify_flutter/amplify_auth_cognito.dart';
import 'package:amplify_flutter/amplify_api.dart';
import 'package:amplify_flutter/amplify_datastore.dart';
import 'package:amplify_flutter/amplify_storage_s3.dart';
import 'package:amplify_push_notifications_pinpoint/amplify_push_notifications_pinpoint.dart';
void configureAmplify() async {
try {
const config = '''{
"awsconfig": {
"auth": {
"plugins": {
"awsCognitoAuthPlugin": {
"UserPoolId": "YOUR_USER_POOL_ID",
"Region": "YOUR_REGION",
"AppClientId": "YOUR_APP_CLIENT_ID",
"IdentityPoolId": "YOUR_IDENTITY_POOL_ID"
}
}
},
"api": {
"plugins": {
"awsApiPlugin": {
"YOUR_API_NAME": {
"endpointType": "GRAPHQL_API",
"endpoint": "https://YOUR_GRAPHQL_ENDPOINT.appsync-api.YOUR_REGION.amazonaws.com/graphql",
"region": "YOUR_REGION",
"authorizationType": "AMAZON_COGNITO_USER_POOLS"
}
}
}
},
"storage": {
"plugins": {
"awsS3StoragePlugin": {
"bucketName": "YOUR_BUCKET_NAME",
"region": "YOUR_REGION",
"authenticationType": "AMAZON_COGNITO_USER_POOLS"
}
}
},
"datastore": {
"plugins": {
"awsDataStorePlugin": {
"storage": {
"type": "AMAZON_DYNAMODB",
"region": "YOUR_REGION",
"authenticationType": "AMAZON_COGNITO_USER_POOLS"
},
"syncConfig": {
"conflictResolutionStrategy": "AUTO_MERGE"
}
}
}
},
"push": {
"plugins": {
"awsPushNotificationPinpointPlugin": {
"appId": "YOUR_PINPOINT_APP_ID",
"region": "YOUR_REGION"
}
}
}
}
}''';
await Amplify.configure(config);
print('Amplify configured successfully');
} catch (e) {
print('Error configuring Amplify: $e');
}
}
确保替换上述代码中的占位符(如YOUR_USER_POOL_ID
、YOUR_REGION
等)为你的实际AWS配置信息。
3. 初始化Amplify
在你的main.dart
文件中,调用configureAmplify
函数来初始化Amplify:
import 'package:flutter/material.dart';
import 'amplify_configuration.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await configureAmplify();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Amplify Push Notifications'),
),
body: Center(
child: Text('Check the console for Amplify configuration status.'),
),
),
);
}
}
4. 订阅推送通知
在你的应用中,你可以订阅推送通知。例如,在MyApp
的某个地方(比如一个按钮点击事件中):
import 'package:amplify_push_notifications_pinpoint/amplify_push_notifications_pinpoint.dart';
// 假设这是在一个按钮点击事件中
void subscribeToPushNotifications() async {
try {
await AmplifyPushNotificationsPinpoint.addSubscription(
endpoint: 'YOUR_ENDPOINT_ARN', // 替换为你的实际ARN
);
print('Successfully subscribed to push notifications');
} catch (e) {
print('Error subscribing to push notifications: $e');
}
}
注意:YOUR_ENDPOINT_ARN
通常是由AWS Pinpoint自动管理的,你可能不需要手动指定它,除非你有特定的需求。
5. 处理推送通知
为了处理接收到的推送通知,你需要配置你的应用以监听通知。这通常涉及到平台特定的代码(如iOS的AppDelegate
和Android的MainActivity
)。由于篇幅限制,这里不详细展开,但你可以参考Amplify Flutter文档获取更多信息。
总结
以上是一个基本的示例,展示了如何在Flutter项目中使用amplify_push_notifications_pinpoint
插件来配置和订阅推送通知。根据你的具体需求,你可能需要调整代码和配置。确保你查阅了最新的Amplify Flutter文档以获取最新的信息和最佳实践。