flutter开发实战-实现推送功能Push Notification
推送服务现在可以说是所有 App 的标配了,最近在Flutter工程项目上实现推送功能。flutter上实现推送功能需要依赖原生的功能,需要插件实现,这里使用的是极光推送的服务。
一、效果图
效果图如下
二、代码实现
在使用极光推送功能时,需要使用的是极光提供的flutter推送插件jpush_flutter
2.1、引入jpush_flutter
在工程的pubspec.yaml文件中引入库
# 集成极光推送 pub 集成
jpush_flutter: ^2.4.2
flutter_app_badger: ^1.5.0
2.2、配置
配置
Android:
在 /android/app/build.gradle 中添加下列代码:
android: {
....
defaultConfig {
applicationId "替换成自己应用 ID"
...
ndk {
//选择要添加的对应 cpu 类型的 .so 库。
abiFilters 'armeabi', 'armeabi-v7a', 'x86', 'x86_64', 'mips', 'mips64', 'arm64-v8a',
}
manifestPlaceholders = [
JPUSH_PKGNAME : applicationId,
JPUSH_APPKEY : "appkey", // NOTE: JPush 上注册的包名对应的 Appkey.
JPUSH_CHANNEL : "developer-default", //暂时填写默认值即可.
]
}
iOS:
在 xcode8 之后需要点开推送选项: TARGETS -> Capabilities -> Push Notification 设为 on 状态
iOS需要使用开发者账号配置推送证书。这里就不描述了。
2.3、实现JPushManager
针对极光的推送服务,我们需要封装一下,实现JPushManager。
初始化setup
需要先调用 JPush.setup 来初始化插件,才能保证其他功能正常工作。
实现代码
import 'package:flutter_app_dfaceintl/config/logger_manager.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
typedef OnJPushEventHandler = void Function(Map<String, dynamic> event);
// 处理极光推送
class JPushManager {
// 私有构造函数
JPushManager._internal() {
// 添加callback
addJPushEventHandler();
}
// 保存单例
static JPushManager _singleton = JPushManager._internal();
// 工厂构造函数
factory JPushManager() => _singleton;
final JPush jpush = new JPush();
void addJPushEventHandler() {
// 添加callback
jpush.addEventHandler(
onReceiveNotification: (Map<String, dynamic> message) async {
LoggerManager().debug("flutter onReceiveNotification: $message");
}, onOpenNotification: (Map<String, dynamic> message) async {
LoggerManager().debug("flutter onOpenNotification: $message");
}, onReceiveMessage: (Map<String, dynamic> message) async {
LoggerManager().debug("flutter onReceiveMessage: $message");
}, onReceiveNotificationAuthorization:
(Map<String, dynamic> message) async {
LoggerManager().debug("flutter onReceiveNotificationAuthorization: $message");
});
}
void jPushRegister({
required String appKey,
required String channel,
required bool production,
required bool debug,
bool sound = true,
bool alert = true,
bool badge = true,
Function(String? registrationID)? onRegisterCallback,
}) {
jpush.setup(
appKey: appKey, //你自己应用的 AppKey
channel: channel,
production: production,
debug: debug,
);
jpush.applyPushAuthority(
new NotificationSettingsIOS(sound: sound, alert: alert, badge: badge));
// Platform messages may fail, so we use a try/catch PlatformException.
jpush.getRegistrationID().then((rid) {
LoggerManager().debug("flutter get registration id : $rid");
if (onRegisterCallback != null) {
onRegisterCallback(rid);
}
});
}
// 发送本地推送
void sendLocalNotification(
{required int id,
required String title,
required String content,
required DateTime fireTime,
int? buildId,
Map<String, String>? extra,
int badge = 0,
String? soundName,
String? subtitle,
Function(String? res)? onCallback}) {
// 三秒后出发本地推送
var fireDate = DateTime.fromMillisecondsSinceEpoch(
DateTime.now().millisecondsSinceEpoch + 3000);
var localNotification = LocalNotification(
id: id,
// 通知 id, 可用于取消通知
title: title,
buildId: buildId,
// 通知样式:1 为基础样式,2 为自定义样式
content: content,
fireTime: fireTime,
subtitle: subtitle,
badge: badge,
extra: extra);
jpush.sendLocalNotification(localNotification).then((res) {
if (onCallback != null) {
onCallback(res);
}
});
}
// 获取App启动的通知
void getLaunchAppNotification({
Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
}) {
jpush.getLaunchAppNotification().then((map) {
LoggerManager().debug("flutter getLaunchAppNotification:$map");
if (onCallback != null) {
onCallback(map, null);
}
}).catchError((error) {
if (onCallback != null) {
onCallback(null, error);
}
});
}
// 设置setTags
void setTags({
required List<String> tags,
Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
}) {
jpush.setTags(tags).then((map) {
var tags = map['tags'];
if (onCallback != null) {
onCallback(map, null);
}
}).catchError((error) {
if (onCallback != null) {
onCallback(null, error);
}
});
}
// 添加addTags
void addTags({
required List<String> tags,
Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
}) {
jpush.addTags(tags).then((map) {
var tags = map['tags'];
if (onCallback != null) {
onCallback(map, null);
}
}).catchError((error) {
if (onCallback != null) {
onCallback(null, error);
}
});
}
// 删除deleteTags
void deleteTags({
required List<String> tags,
Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
}) {
jpush.deleteTags(tags).then((map) {
var tags = map['tags'];
if (onCallback != null) {
onCallback(map, null);
}
}).catchError((error) {
if (onCallback != null) {
onCallback(null, error);
}
});
}
// 获取所有Tags getAllTags
void getAllTags({
Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
}) {
jpush.getAllTags().then((map) {
var tags = map['tags'];
if (onCallback != null) {
onCallback(map, null);
}
}).catchError((error) {
if (onCallback != null) {
onCallback(null, error);
}
});
}
// 清理tags cleanTags
void cleanTags({
Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
}) {
jpush.cleanTags().then((map) {
var tags = map['tags'];
if (onCallback != null) {
onCallback(map, null);
}
}).catchError((error) {
if (onCallback != null) {
onCallback(null, error);
}
});
}
// 设置别名
void setAlias({
required String alias,
Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
}) {
jpush.setAlias(alias).then((map) {
var tags = map['tags'];
if (onCallback != null) {
onCallback(map, null);
}
}).catchError((error) {
if (onCallback != null) {
onCallback(null, error);
}
});
}
// 删除别名 deleteAlias
void deleteAlias({
Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
}) {
jpush.deleteAlias().then((map) {
var tags = map['tags'];
if (onCallback != null) {
onCallback(map, null);
}
}).catchError((error) {
if (onCallback != null) {
onCallback(null, error);
}
});
}
// stopPush
void stopPush() {
jpush.stopPush();
}
// resumePush
void resumePush() {
jpush.resumePush();
}
// clearAllNotifications
void clearAllNotifications() {
jpush.clearAllNotifications();
}
// 设置setBadge
void setBadge({
required int badge,
Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
}) {
jpush.setBadge(badge).then((map) {
if (onCallback != null) {
onCallback(map, null);
}
}).catchError((error) {
if (onCallback != null) {
onCallback(null, error);
}
});
}
// 通知授权是否打开
void getNotificationEnabled({
Function(bool value, dynamic? error)? onCallback,
}) {
jpush.isNotificationEnabled().then((bool value) {
if (onCallback != null) {
onCallback(value, null);
}
}).catchError((onError) {
if (onCallback != null) {
onCallback(false, onError);
}
});
}
// 打开系统设置
void openSettingsForNotification() {
jpush.openSettingsForNotification();
}
}
2.3、使用Jpush极光推送
首先在MyApp.dart中进行初始化。
/// 配置推送JPush
void initState() {
// TODO: implement initState
super.initState();
configJPush();
jPushResetBadge();
}
void configJPush() {
// TODO 替换极光推送的appKey,channel
JPushManager().jPushRegister(
appKey: "appKey",
channel: "app-ios",
production: false,
debug: true,
sound: true,
alert: true,
badge: true,
onRegisterCallback: (String? registrationID) {
LoggerManager().debug("configJPush registrationID:${registrationID}");
},
);
}
/// 重置Badge
Future<void> jPushResetBadge() async {
JPushManager().setBadge(
badge: 0,
onCallback: (Map<dynamic, dynamic>? map, dynamic? error) {
LoggerManager().debug("JPush resetBadge map:${map}, error:${error}");
},
);
//直接使用remove方法
bool isSupported = await FlutterAppBadger.isAppBadgeSupported();
if (isSupported) {
FlutterAppBadger.removeBadge();
}
}
具体效果
三、小结
flutter开发实战-实现推送功能Push Notification。推送服务现在可以说是所有 App 的标配了,最近在Flutter工程项目上实现推送功能。使用极光推送的服务jpush_flutter。
学习记录,每天不停进步。