Flutter自定义通知插件mc_custom_notification的使用
Flutter自定义通知插件mc_custom_notification的使用
mc_custom_notification
是一个强大的Flutter插件,用于在Android平台上创建和管理自定义通知。本文将介绍如何安装和使用该插件,并提供完整的示例代码。
安装
首先,在您的 pubspec.yaml
文件中添加 mc_custom_notification
依赖:
dependencies:
flutter:
sdk: flutter
mc_custom_notification: ^latest_version
然后运行以下命令来安装插件:
flutter pub get
初始化库
在应用程序启动时初始化插件:
import 'package:mc_custom_notification/mc_custom_notification.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
McCustomNotification().initialize(
onClick: (payload) {
// 处理通知点击事件
},
);
runApp(MyApp());
}
使用示例
显示来电通知
import 'package:mc_custom_notification/mc_custom_notification.dart';
Future<void> showCallNotification() async {
await McCustomNotification().showNotificationCall(
model: NotificationCall(
id: 1,
tag: 'tag1',
title: 'New Notification',
body: 'This is the body of the notification',
image: "https://vpsserver.meta-code-ye.com/files/image?name=IMG-20240314-WA0007.jpg",
payload: {'id': 55, "name": "ali"},
groupKey: "call",
onAccepted: (payload) {
// 接受来电时的操作
},
onDenied: () {
// 拒绝来电时的操作
},
),
);
}
显示通话通知
import 'package:mc_custom_notification/mc_custom_notification.dart';
Future<void> showCallingNotification() async {
await McCustomNotification().showNotificationCalling(
model: NotificationCalling(
id: 52,
tag: 'tag18',
title: 'Normal notification ',
body: 'This is the body of the notification',
payload: {'id': 55, "name": "ali"},
groupKey: "normal53",
onEndCall: (payload) {
// 结束通话时的操作
},
),
);
}
显示消息通知(带InBox)
import 'package:mc_custom_notification/mc_custom_notification.dart';
Future<void> showMessageWithInboxNotification() async {
List<String> names = ['younas', 'ali', 'mohammed', 'ahmed', 'salh'];
List<String> dis = [
'nice to meet you',
'hellow man',
'how are you',
'I need Vs code',
'no thanks its work'
];
for (int x = 0; x < names.length; x++) {
await McCustomNotification().showNotificationMessage(
model: NotificationMessage(
useInbox: true,
id: 11 + x,
tag: 'tag111$x',
title: names[x],
body: dis[x],
payload: {'id': 55, "name": "ali"},
groupKey: "chat55214",
isVibration: true,
onRead: (payload) {
// 阅读消息时的操作
},
onReply: (payload) {
// 回复消息时的操作
},
),
);
}
}
发送Firebase通知
发送给单个用户
import 'package:mc_custom_notification/mc_custom_notification.dart';
Future<void> sendNotificationToUser(String token) async {
await McCustomNotification().sendNotification(
token: token,
model: NotificationModel(
title: "younas ali",
body: "hello how are you",
id: 150,
image: "https://vpsserver.meta-code-ye.com/files/image?name=IMG-20240314-WA0007.jpg",
payload: {"id": 1, "name": "younas"},
),
);
}
发送给多个用户
import 'package:mc_custom_notification/mc_custom_notification.dart';
Future<void> sendNotificationToMultipleUsers() async {
await McCustomNotification().sendNotificationToAll(
topics: "'meta' in topics || 'code' in topics ||'allUsers' in topics",
model: NotificationModel(
title: "younas ali",
body: "hello how are you",
groupKey: 'normal_notification',
id: 150,
image: "https://vpsserver.meta-code-ye.com/files/image?name=IMG-20240314-WA0007.jpg",
payload: {"id": 1, "name": "younas"},
),
);
}
Firebase背景通知处理
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:mc_custom_notification/mc_custom_notification.dart';
Future<void> handleBackgroundMessage(RemoteMessage message) async {
var payloadData = message.data;
var model = NotificationModel.fromMap(payloadData);
await McCustomNotification().showNotificationMessage(
model: NotificationMessage(
id: 1,
tag: message.notification?.android?.tag,
title: model.title,
body: model.body,
image: model.image,
payload: model.payload,
onRead: (payload) {
// 阅读消息时的操作
},
onReply: (payload) {
// 回复消息时的操作
},
),
);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(handleBackgroundMessage);
runApp(MyApp());
}
全部通知操作
显示所有通知
import 'package:mc_custom_notification/mc_custom_notification.dart';
import 'package:fluttertoast/fluttertoast.dart';
Future<void> showAllNotifications() async {
var notifications = await McCustomNotification().getAllNotificcations();
Fluttertoast.showToast(
msg: notifications.toString(),
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0,
);
}
取消所有通知
import 'package:mc_custom_notification/mc_custom_notification.dart';
void cancelAllNotifications() {
McCustomNotification().cancelAllNotifications();
}
取消特定通知
import 'package:mc_custom_notification/mc_custom_notification.dart';
void cancelSpecificNotification() {
McCustomNotification().cancelNotification(id: 555, tag: "tag55");
}
以上是 mc_custom_notification
插件的基本使用方法和示例代码。更多详细信息请参考官方文档和GitHub仓库。希望这些内容能帮助您快速上手并实现所需功能。
更多关于Flutter自定义通知插件mc_custom_notification的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter自定义通知插件mc_custom_notification的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中集成和使用mc_custom_notification
插件的一个示例代码案例。这个插件允许你自定义Android和iOS的通知样式。
1. 添加依赖
首先,你需要在pubspec.yaml
文件中添加mc_custom_notification
依赖:
dependencies:
flutter:
sdk: flutter
mc_custom_notification: ^最新版本号 # 请替换为实际的最新版本号
然后运行flutter pub get
来获取依赖。
2. 配置Android和iOS
Android
通常,Flutter插件会自动处理大部分Android配置,但你可能需要在AndroidManifest.xml
中添加一些必要的权限,比如通知权限。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourapp">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<!-- 其他配置 -->
</manifest>
iOS
对于iOS,你需要在Info.plist
中添加一些必要的配置,比如通知权限请求。此外,确保在Xcode中启用了Background Modes中的Remote Notifications。
3. 使用插件
以下是一个基本的示例,展示如何使用mc_custom_notification
插件来显示自定义通知。
import 'package:flutter/material.dart';
import 'package:mc_custom_notification/mc_custom_notification.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Custom Notification Example'),
),
body: Center(
child: ElevatedButton(
onPressed: _showCustomNotification,
child: Text('Show Notification'),
),
),
),
);
}
void _showCustomNotification() async {
// 配置通知内容
var androidConfig = AndroidNotificationConfig(
title: 'Custom Title',
body: 'This is a custom notification body.',
channelId: 'default_channel', // 确保在Android中已创建此通道
smallIcon: 'ic_notification', // 资源文件中的图标名
largeIcon: 'large_icon', // 资源文件中的大图标名(可选)
color: Colors.blue.value, // 通知颜色
priority: Priority.HIGH, // 通知优先级
importance: Importance.HIGH, // 通知重要性
style: NotificationStyle.BIG_PICTURE, // 通知样式(可选)
bigPicture: 'big_picture', // 大图资源文件名(如果使用了BIG_PICTURE样式)
);
var iosConfig = IOSNotificationConfig(
title: 'Custom Title',
body: 'This is a custom notification body.',
sound: true,
badge: true,
alert: true,
);
var notificationConfig = NotificationConfig(
android: androidConfig,
ios: iosConfig,
);
// 显示通知
await McCustomNotification.show(
id: 1,
title: 'Notification Title',
body: 'Notification body',
payload: 'Optional payload data',
config: notificationConfig,
);
}
}
4. 初始化通知通道(仅Android)
在Android上,你需要在应用启动时初始化通知通道。这通常在MainActivity.kt
或MainActivity.java
中完成。由于mc_custom_notification
插件可能已经处理了大部分初始化工作,你可能只需要确保通道ID与你在代码中使用的相匹配。
// MainActivity.kt 示例
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 初始化通知通道(如果需要)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "default_channel"
val channelName = "Default Channel"
val importance = NotificationManagerCompat.IMPORTANCE_HIGH
val channel = NotificationCompat.Channel(channelId, channelName, importance)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManagerCompat
notificationManager.createNotificationChannel(channel)
}
}
}
这个示例展示了如何在Flutter应用中使用mc_custom_notification
插件来显示自定义通知。请确保根据你的应用需求调整配置和样式。