Flutter推送通知插件pushwoosh_flutter的使用
Flutter推送通知插件pushwoosh_flutter的使用
安装
- 在
pubspec.yaml
文件中添加以下依赖:
dependencies:
pushwoosh_flutter: '^2.3.7'
-
配置Firebase Android项目:
- 登录到Firebase控制台。
-
将
google-services.json
文件放置在项目的android/app
目录下。
使用
在你的应用中初始化Pushwoosh插件,并设置相应的监听器来处理推送通知事件:
import 'package:pushwoosh_flutter/pushwoosh_flutter.dart';
...
void main() {
runApp(const MyApp());
// 初始化Pushwoosh SDK
// 参数示例:{"app_id": "YOUR_APP_ID", "sender_id": "FCM_SENDER_ID"}
Pushwoosh.initialize({"app_id": "XXXXX-XXXXX", "sender_id": "XXXXXXXXXXXX"});
// 设置默认Live Activity
Pushwoosh.getInstance.defaultSetup();
// 设置推送接收监听器
Pushwoosh.getInstance.onPushReceived.listen((event) {
if (kDebugMode) {
print(event.pushwooshMessage.payload);
}
});
// 设置推送接受监听器
Pushwoosh.getInstance.onPushAccepted.listen((event) {
if (kDebugMode) {
print(event.pushwooshMessage.payload);
}
});
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(title: 'PUSHWOOSH DEMO'),
);
}
}
示例代码
下面是一个完整的示例代码,展示了如何在Flutter应用中使用Pushwoosh插件进行推送通知的配置和操作:
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';
// 导入Pushwoosh插件
import 'package:pushwoosh_flutter/pushwoosh_flutter.dart';
import 'package:pushwoosh_geozones/pushwoosh_geozones.dart';
import 'package:pushwoosh_inbox/pushwoosh_inbox.dart';
void main() {
runApp(const MyApp());
// 初始化Pushwoosh SDK
Pushwoosh.initialize({"app_id": "XXXXX-XXXXX", "sender_id": "XXXXXXXXXXXX"});
// 设置默认Live Activity
Pushwoosh.getInstance.defaultSetup();
// 设置推送接收监听器
Pushwoosh.getInstance.onPushReceived.listen((event) {
if (kDebugMode) {
print(event.pushwooshMessage.payload);
}
});
// 设置推送接受监听器
Pushwoosh.getInstance.onPushAccepted.listen((event) {
if (kDebugMode) {
print(event.pushwooshMessage.payload);
}
});
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(title: 'PUSHWOOSH DEMO'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
[@override](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
late TabController _tabController;
bool notificationsEnabled = false;
bool foregroundAlertEnabled = true;
String userId = '';
String eventName = '';
String tagKey = '';
String tagValue = '';
String language = '';
String email = '';
int badges = 0;
int seconds = 0;
bool isRunning = false;
Timer? timer;
[@override](/user/override)
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this);
}
void registerForRemoteNotification(bool value) {
setState(() {
notificationsEnabled = value;
if (value == false) {
// 取消推送通知注册
Pushwoosh.getInstance.unregisterForPushNotifications();
} else {
// 注册推送通知
Pushwoosh.getInstance.registerForPushNotifications();
}
});
}
void showForegroundAlert(bool value) {
setState(() {
foregroundAlertEnabled = value;
if (foregroundAlertEnabled == true) {
showAlert(context, 'INFO', "FOREGROUND ALERTS ENABLED");
} else {
showAlert(context, 'INFO', "FOREGROUND ALERTS DISABLED");
}
Pushwoosh.getInstance.setShowForegroundAlert(value);
});
}
void showAlert(BuildContext context, String title, String content) async {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(title),
content: Text(content),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('OK'),
),
],
);
},
);
}
void showToken() async {
// 获取推送通知令牌或null(如果设备尚未注册)
String? token = await Pushwoosh.getInstance.getPushToken;
showAlert(context, "Push Token", token!);
}
void showHWID() async {
// 获取当前设备的Pushwoosh HWID
String hwid = await Pushwoosh.getInstance.getHWID;
showAlert(context, "HWID", hwid);
}
Widget buildButtonRow(
String buttonText,
void Function()? onPressed, {
double? buttonWidth,
}) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
if (buttonWidth != null)
SizedBox(
width: buttonWidth,
child: ElevatedButton(
onPressed: onPressed,
child: Text(
buttonText,
style: TextStyle(
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 25, 14, 184)),
),
),
)
else
Expanded(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 5.0),
child: ElevatedButton(
onPressed: onPressed,
child: Text(
buttonText,
style: TextStyle(
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 25, 14, 184)),
),
),
),
),
],
);
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color.fromARGB(255, 101, 240, 154),
title: Text(
widget.title,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
body: TabBarView(
controller: _tabController,
children: [
ListView(
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 65,
height: 65,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
image: DecorationImage(
image: AssetImage('assets/images/logo.png'),
fit: BoxFit.cover,
),
),
),
],
),
SizedBox(
height: 16,
),
Row(
children: [
buildButtonRow('SET USER ID', () async {
// 设置用户标识符
Pushwoosh.getInstance.setUserId(userId);
}, buttonWidth: 170),
SizedBox(width: 16),
Expanded(
child: CupertinoTextField(
placeholder: 'USER ID',
onChanged: (value) {
setState(() {
userId = value;
});
},
),
),
],
),
Row(
children: [
buildButtonRow('POST EVENT', () async {
// 发布事件
Pushwoosh.getInstance.postEvent(
eventName, {"KEY1": "VALUE1", "KEY2": "VALUE2"});
}, buttonWidth: 170),
SizedBox(width: 16),
Expanded(
child: CupertinoTextField(
placeholder: 'EVENT NAME',
onChanged: (value) {
setState(() {
eventName = value;
});
},
),
),
],
),
Row(
children: [
buildButtonRow('SET TAGS', () async {
// 设置标签
Pushwoosh.getInstance.setTags({tagKey: tagValue});
}, buttonWidth: 170),
SizedBox(width: 16),
Expanded(
child: CupertinoTextField(
placeholder: 'KEY',
onChanged: (value) {
setState(() {
tagKey = value;
});
},
),
),
SizedBox(width: 8),
Expanded(
child: CupertinoTextField(
placeholder: 'VALUE',
onChanged: (value) {
setState(() {
tagValue = value;
});
},
),
),
],
),
Row(
children: [
buildButtonRow('SET LANGUAGE', () {
// 设置语言
Pushwoosh.getInstance.setLanguage(language);
}, buttonWidth: 170),
SizedBox(width: 16),
Expanded(
child: CupertinoTextField(
placeholder: 'en',
onChanged: (value) {
setState(() {
language = value;
});
},
),
),
],
),
Row(
children: [
buildButtonRow('SET EMAIL', () {
// 设置电子邮件
Pushwoosh.getInstance.setEmail(email);
}, buttonWidth: 170),
SizedBox(width: 16),
Expanded(
child: CupertinoTextField(
placeholder: 'en',
onChanged: (value) {
setState(() {
email = value;
});
},
),
),
],
),
buildButtonRow('GET HWID', () async {
showHWID();
}),
buildButtonRow('GET PUSH TOKEN', () async {
showToken();
}),
buildButtonRow('GET TAGS', () async {
// 获取当前设备关联的标签
Map<dynamic, dynamic> tags = await Pushwoosh.getInstance.getTags();
String tagToString = tags.toString();
showAlert(context, 'TAGS', tagToString);
}),
buildButtonRow('RESET BADGES', () async {
// 重置应用图标徽章数
Pushwoosh.getInstance.setApplicationIconBadgeNumber(0);
}),
SizedBox(height: 16),
Row(
children: [
Text(
'FOR HUAWEI DEVICES',
style: TextStyle(
fontWeight: FontWeight.bold,
),
)
],
),
buildButtonRow('ENABLE HUAWEI NOTIFICATIONS', () async {
// 启用华为通知
Pushwoosh.getInstance.enableHuaweiNotifications();
}),
buildButtonRow('START LOCATION TRACKING', () async {
// 开始位置跟踪
PushwooshGeozones.startLocationTracking();
}),
buildButtonRow('STOP LOCATION TRACKING', () async {
// 停止位置跟踪
PushwooshGeozones.stopLocationTracking();
}),
buildButtonRow('SHOW INBOX', () async {
// 显示消息中心
_showInbox();
}),
],
),
),
],
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
notificationsEnabled
? 'UNREGISTER FOR PUSH NOTIFICATIONS'
: 'REGISTER FOR PUSH NOTIFICATIONS',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
Switch(
value: notificationsEnabled,
onChanged: registerForRemoteNotification,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'SHOW FOREGROUND ALERT',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
Switch(
value: foregroundAlertEnabled,
onChanged: showForegroundAlert,
),
],
),
],
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: buildButtonRow('GO TO LIVE ACTIVITIES (iOS)', () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => StopwatchApp()),
);
}),
),
],
),
),
],
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.accessibility),
label: 'Actions',
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: 'Settings',
),
BottomNavigationBarItem(
icon: Icon(Icons.live_tv),
label: 'Live Activities',
),
],
currentIndex: _tabController.index,
selectedItemColor: Color.fromARGB(255, 25, 14, 184),
onTap: (index) {
setState(() {
_tabController.index = index;
});
},
),
);
}
}
void _showInbox() {
PWInboxStyle style = PWInboxStyle();
style.dateFormat = "dd.MM.yyyy";
style.defaultImage = "assets/inbox-1.png";
style.unreadImage = "assets/bubble-2.png";
style.listErrorImage = "assets/alert-2.png";
style.listEmptyImage = "assets/inbox-1.png";
style.listErrorMessage = "Custom error message";
style.listEmptyMessage = "Custom empty message";
style.barTitle = "Custom inbox title";
style.accentColor = "#FF00FF";
style.backgroundColor = "#FFFF00";
style.highlightColor = "#FF0FFF";
style.imageTypeColor = "#00F0FF";
style.readImageTypeColor = "#FF000F";
style.titleColor = "#00F0FF";
style.readTitleColor = "#00FF0F";
style.defaultTextColor = "#FF00FF";
style.descriptionColor = "#FF000F";
style.readDescriptionColor = "#00FF0F";
style.dateColor = "#00F0FF";
style.readDateColor = "#F0FF0F";
style.dividerColor = "#FF000F";
style.barBackgroundColor = "#FF000F";
style.barAccentColor = "#0000FF";
style.barTextColor = "#00FF00";
PushwooshInbox.presentInboxUI(style: style);
}
更多关于Flutter推送通知插件pushwoosh_flutter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter推送通知插件pushwoosh_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用pushwoosh_flutter
插件来实现推送通知的一个示例。这个示例将展示如何配置插件、初始化Pushwoosh服务以及处理推送通知。
1. 添加依赖
首先,在你的pubspec.yaml
文件中添加pushwoosh_flutter
依赖:
dependencies:
flutter:
sdk: flutter
pushwoosh_flutter: ^x.y.z # 请替换为最新版本号
然后运行flutter pub get
来安装依赖。
2. 配置Pushwoosh
你需要在Pushwoosh控制台创建一个应用程序,并获取你的应用程序ID和应用程序密钥。
3. Android配置
在android/app/src/main/AndroidManifest.xml
中添加Pushwoosh所需的权限和服务:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourapp">
<!-- 其他配置 -->
<!-- Pushwoosh权限 -->
<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" />
<!-- Pushwoosh服务 -->
<service
android:name="com.pushwoosh.messaging.GCMIntentService"
android:exported="false" />
<receiver
android:name="com.pushwoosh.messaging.PushReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</receiver>
<receiver android:name="com.pushwoosh.messaging.PushwooshBroadcastReceiver" android:exported="false">
<intent-filter>
<action android:name="com.pushwoosh.ACTION_PUSH_RECEIVED" />
<action android:name="com.pushwoosh.ACTION_PUSH_OPEN" />
<action android:name="com.pushwoosh.ACTION_GEOLOCATION" />
<action android:name="com.pushwoosh.ACTION_RICHPUSH_CLOSE" />
</intent-filter>
</receiver>
<!-- 其他配置 -->
</manifest>
4. iOS配置
在ios/Runner/Info.plist
中添加Pushwoosh所需的配置:
<key>UIApplicationSupportsMultipleWindows</key>
<true/>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>pw_YOUR_APP_ID</string> <!-- 替换为你的Pushwoosh应用ID -->
</array>
</dict>
</array>
确保在Xcode的Capabilities中启用了Background Modes和Push Notifications。
5. 初始化Pushwoosh
在你的main.dart
文件中初始化Pushwoosh:
import 'package:flutter/material.dart';
import 'package:pushwoosh_flutter/pushwoosh_flutter.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
// 初始化Pushwoosh
Pushwoosh.initialize(
applicationId: 'YOUR_APP_ID', // 替换为你的Pushwoosh应用ID
applicationCode: 'YOUR_APP_CODE', // 替换为你的Pushwoosh应用密钥
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Pushwoosh Example'),
),
body: Center(
child: Text('Check your console for push notifications!'),
),
),
);
}
}
6. 处理推送通知
为了处理推送通知,你可以监听Pushwoosh的事件。例如,在MyApp
类中监听通知打开事件:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
Pushwoosh.onPushOpened.listen((PushOpenedData data) {
print('Push opened: ${data.notification}');
// 在这里处理推送打开事件
});
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Pushwoosh Example'),
),
body: Center(
child: Text('Check your console for push notifications!'),
),
),
);
}
}
这个示例展示了如何在Flutter中使用pushwoosh_flutter
插件进行基本的推送通知配置和处理。根据你的需求,你可以进一步扩展这个示例,例如处理不同类型的推送通知、自定义通知显示等。