Flutter推送通知插件jpush_flutter的使用
Flutter推送通知插件jpush_flutter的使用
JPush Flutter Plugin
flutter 3.0 请切换至 dev-3.x 分支。
安装
在工程 pubspec.yaml
中加入 dependencies
//github 集成
dependencies:
jpush_flutter:
git:
url: git://github.com/jpush/jpush-flutter-plugin.git
ref: dev-3.x
// pub 集成
dependencies:
jpush_flutter: 3.1.9
配置
Android:
在 /android/app/build.gradle
中添加下列代码:
android: {
....
defaultConfig {
applicationId "替换成自己应用 ID"
...
manifestPlaceholders = [
JPUSH_PKGNAME : applicationId,
JPUSH_APPKEY : "appkey", // NOTE: JPush 上注册的包名对应的 Appkey.
JPUSH_CHANNEL : "developer-default", //暂时填写默认值即可.
]
}
}
iOS:
- 在 xcode8 之后需要点开推送选项: TARGETS -> Capabilities -> Push Notification 设为 on 状态
使用
import 'package:jpush_flutter/jpush_flutter.dart';
示例Demo
下面是一个完整的示例demo,展示了如何使用jpush_flutter
插件来接收和处理推送通知。
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
String? debugLable = 'Unknown';
final JPush jpush = new JPush();
@override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String? platformVersion;
try {
jpush.addEventHandler(
onReceiveNotification: (Map<String, dynamic> message) async {
print("flutter onReceiveNotification: $message");
setState(() {
debugLable = "flutter onReceiveNotification: $message";
});
},
onOpenNotification: (Map<String, dynamic> message) async {
print("flutter onOpenNotification: $message");
setState(() {
debugLable = "flutter onOpenNotification: $message";
});
},
onReceiveMessage: (Map<String, dynamic> message) async {
print("flutter onReceiveMessage: $message");
setState(() {
debugLable = "flutter onReceiveMessage: $message";
});
},
onReceiveNotificationAuthorization:
(Map<String, dynamic> message) async {
print("flutter onReceiveNotificationAuthorization: $message");
setState(() {
debugLable = "flutter onReceiveNotificationAuthorization: $message";
});
},
onNotifyMessageUnShow: (Map<String, dynamic> message) async {
print("flutter onNotifyMessageUnShow: $message");
setState(() {
debugLable = "flutter onNotifyMessageUnShow: $message";
});
},
onInAppMessageShow: (Map<String, dynamic> message) async {
print("flutter onInAppMessageShow: $message");
setState(() {
debugLable = "flutter onInAppMessageShow: $message";
});
},
onCommandResult: (Map<String, dynamic> message) async {
print("flutter onCommandResult: $message");
setState(() {
debugLable = "flutter onCommandResult: $message";
});
},
onInAppMessageClick: (Map<String, dynamic> message) async {
print("flutter onInAppMessageClick: $message");
setState(() {
debugLable = "flutter onInAppMessageClick: $message";
});
},
onConnected: (Map<String, dynamic> message) async {
print("flutter onConnected: $message");
setState(() {
debugLable = "flutter onConnected: $message";
});
}
);
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
jpush.setAuth(enable: true);
jpush.setup(
appKey: "xxxxx", //你自己应用的 AppKey
channel: "theChannel",
production: false,
debug: true,
);
jpush.applyPushAuthority(
new NotificationSettingsIOS(sound: true, alert: true, badge: true));
// Platform messages may fail, so we use a try/catch PlatformException.
jpush.getRegistrationID().then((rid) {
print("flutter get registration id : $rid");
setState(() {
debugLable = "flutter getRegistrationID: $rid";
});
});
// iOS要是使用应用内消息,请在页面进入离开的时候配置pageEnterTo 和 pageLeave 函数,参数为页面名。
jpush.pageEnterTo("HomePage"); // 在离开页面的时候请调用 jpush.pageLeave("HomePage");
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
debugLable = platformVersion;
});
}
// 编写视图
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: const Text('Plugin example app'),
),
body: new Center(
child: new Column(children: [
Container(
margin: EdgeInsets.fromLTRB(10, 10, 10, 10),
color: Colors.brown,
child: Text(debugLable ?? "Unknown"),
width: 350,
height: 100,
),
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(" "),
new CustomButton(
title: "发本地推送",
onPressed: () {
// 三秒后出发本地推送
var fireDate = DateTime.fromMillisecondsSinceEpoch(
DateTime.now().millisecondsSinceEpoch + 3000);
var localNotification = LocalNotification(
id: 234,
title: 'fadsfa',
buildId: 1,
content: 'fdas',
fireTime: fireDate,
subtitle: 'fasf',
badge: 5,
extra: {"fa": "0"});
jpush.sendLocalNotification(localNotification).then((res) {
setState(() {
debugLable = res;
});
});
}),
new Text(" "),
new CustomButton(
title: "getLaunchAppNotification",
onPressed: () {
jpush.getLaunchAppNotification().then((map) {
print("flutter getLaunchAppNotification:$map");
setState(() {
debugLable = "getLaunchAppNotification success: $map";
});
}).catchError((error) {
setState(() {
debugLable = "getLaunchAppNotification error: $error";
});
});
}),
]),
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(" "),
new CustomButton(
title: "setTags",
onPressed: () {
jpush.setTags(["lala", "haha"]).then((map) {
var tags = map['tags'];
setState(() {
debugLable = "set tags success: $map $tags";
});
}).catchError((error) {
setState(() {
debugLable = "set tags error: $error";
});
});
}),
new Text(" "),
new CustomButton(
title: "addTags",
onPressed: () {
jpush.addTags(["lala", "haha"]).then((map) {
var tags = map['tags'];
setState(() {
debugLable = "addTags success: $map $tags";
});
}).catchError((error) {
setState(() {
debugLable = "addTags error: $error";
});
});
}),
new Text(" "),
new CustomButton(
title: "deleteTags",
onPressed: () {
jpush.deleteTags(["lala", "haha"]).then((map) {
var tags = map['tags'];
setState(() {
debugLable = "deleteTags success: $map $tags";
});
}).catchError((error) {
setState(() {
debugLable = "deleteTags error: $error";
});
});
}),
]),
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(" "),
new CustomButton(
title: "getAllTags",
onPressed: () {
jpush.getAllTags().then((map) {
setState(() {
debugLable = "getAllTags success: $map";
});
}).catchError((error) {
setState(() {
debugLable = "getAllTags error: $error";
});
});
}),
new Text(" "),
new CustomButton(
title: "cleanTags",
onPressed: () {
jpush.cleanTags().then((map) {
var tags = map['tags'];
setState(() {
debugLable = "cleanTags success: $map $tags";
});
}).catchError((error) {
setState(() {
debugLable = "cleanTags error: $error";
});
});
}),
]),
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(" "),
new CustomButton(
title: "setAlias",
onPressed: () {
jpush.setAlias("thealias11").then((map) {
setState(() {
debugLable = "setAlias success: $map";
});
}).catchError((error) {
setState(() {
debugLable = "setAlias error: $error";
});
});
}),
new Text(" "),
new CustomButton(
title: "deleteAlias",
onPressed: () {
jpush.deleteAlias().then((map) {
setState(() {
debugLable = "deleteAlias success: $map";
});
}).catchError((error) {
setState(() {
debugLable = "deleteAlias error: $error";
});
});
}),
new Text(" "),
new CustomButton(
title: "getAlias",
onPressed: () {
jpush.getAlias().then((map) {
setState(() {
debugLable = "getAlias success: $map";
});
}).catchError((error) {
setState(() {
debugLable = "getAlias error: $error";
});
});
}),
]),
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(" "),
new CustomButton(
title: "stopPush",
onPressed: () {
jpush.stopPush();
}),
new Text(" "),
new CustomButton(
title: "resumePush",
onPressed: () {
jpush.resumePush();
}),
],
),
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(" "),
new CustomButton(
title: "clearAllNotifications",
onPressed: () {
jpush.clearAllNotifications();
}),
new Text(" "),
new CustomButton(
title: "setBadge",
onPressed: () {
jpush.setBadge(66).then((map) {
setState(() {
debugLable = "setBadge success: $map";
});
}).catchError((error) {
setState(() {
debugLable = "setBadge error: $error";
});
});
}),
],
),
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(" "),
new CustomButton(
title: "通知授权是否打开",
onPressed: () {
jpush.isNotificationEnabled().then((bool value) {
setState(() {
debugLable = "通知授权是否打开: $value";
});
}).catchError((onError) {
setState(() {
debugLable = "通知授权是否打开: ${onError.toString()}";
});
});
}),
new Text(" "),
new CustomButton(
title: "打开系统设置",
onPressed: () {
jpush.openSettingsForNotification();
}),
],
),
]),
),
),
);
}
}
/// 封装控件
class CustomButton extends StatelessWidget {
final VoidCallback? onPressed;
final String? title;
const CustomButton({@required this.onPressed, @required this.title});
@override
Widget build(BuildContext context) {
return new TextButton(
onPressed: onPressed,
child: new Text("$title"),
style: new ButtonStyle(
foregroundColor: MaterialStateProperty.all(Colors.white),
overlayColor: MaterialStateProperty.all(Color(0xff888888)),
backgroundColor: MaterialStateProperty.all(Color(0xff585858)),
padding: MaterialStateProperty.all(EdgeInsets.fromLTRB(10, 5, 10, 5)),
),
);
}
}
以上是jpush_flutter
插件的使用方法及一个完整的示例demo。通过这个例子,您可以了解如何初始化JPush、处理各种推送事件以及执行相关操作如设置标签、别名等。希望这对您有所帮助!
更多关于Flutter推送通知插件jpush_flutter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter推送通知插件jpush_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用jpush_flutter
插件来实现推送通知的一个基本示例。这个示例将展示如何配置和初始化JPush,以及如何接收和处理推送通知。
1. 添加依赖
首先,在你的pubspec.yaml
文件中添加jpush_flutter
依赖:
dependencies:
flutter:
sdk: flutter
jpush_flutter: ^最新版本号 # 请替换为实际的最新版本号
然后运行flutter pub get
来安装依赖。
2. 配置Android项目
在android/app/src/main/AndroidManifest.xml
文件中添加以下权限和配置:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourapp">
<!-- 其他配置 -->
<!-- JPush所需权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- JPush服务配置 -->
<application
android:name=".MyApplication" <!-- 请确保你的Application类继承自FlutterApplication或手动处理Flutter的生命周期 -->
... >
<!-- JPush服务接收器 -->
<meta-data
android:name="CN_JPUSH_ANDROID_APPKEY"
android:value="你的AppKey" /> <!-- 请替换为你的JPush AppKey -->
<meta-data
android:name="CN_JPUSH_CHANNEL"
android:value="developer-default" />
<service
android:name="cn.jpush.android.service.JPushService"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="cn.jpush.android.intent.REGISTER" />
<action android:name="cn.jpush.android.intent.UNREGISTER" />
<action android:name="cn.jpush.android.intent.MESSAGE_RECEIVED" />
<action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED" />
<action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED" />
<action android:name="cn.jpush.android.api.JPushInterface.ACTION_RICHPUSH_CALLBACK" />
<category android:name="你的包名" />
</intent-filter>
</service>
<receiver
android:name="cn.jpush.android.service.JPushReceiver"
android:enabled="true"
android:exported="false">
<intent-filter android:priority="1000">
<action android:name="cn.jpush.android.intent.REGISTRATION" />
<action android:name="cn.jpush.android.intent.MESSAGE_RECEIVED" />
<action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED" />
<action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED" />
<action android:name="cn.jpush.android.api.JPushInterface.ACTION_RICHPUSH_CALLBACK" />
<category android:name="你的包名" />
</intent-filter>
</receiver>
<!-- 其他配置 -->
</application>
</manifest>
注意:
- 请确保你的
Application
类已经正确配置,并且继承自io.flutter.embedding.android.FlutterApplication
(如果你使用的是嵌入式v2引擎)或者手动处理Flutter的生命周期。 - 替换
你的AppKey
和你的包名
为实际的值。
3. 配置iOS项目
在ios/Runner/Info.plist
文件中添加以下配置:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>你的iOS_AppKey</string> <!-- 请替换为你的JPush iOS AppKey -->
</array>
</dict>
</array>
<key>JPUSH_APPKEY</key>
<string>你的iOS_AppKey</string> <!-- 请替换为你的JPush iOS AppKey -->
<key>JPUSH_CHANNEL</key>
<string>developer-default</string>
然后,在ios/Podfile
中添加以下配置来确保jpush-flutter-plugin
被正确集成:
platform :ios, '9.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
project 'Runner', {
'Debug': :debug,
'Profile': :release,
'Release': :release,
}
def flutter_root
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
unless File.exist?(generated_xcode_build_settings_path)
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
end
File.foreach(generated_xcode_build_settings_path) do |line|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
return matches[1].strip if matches
end
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try running flutter pub get in your Flutter project directory."
end
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
flutter_ios_podfile_setup
target 'Runner' do
use_frameworks!
use_modular_headers!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
# 添加JPush依赖
pod 'JPush/JCore', '~> 最新版本号' # 请替换为实际的最新版本号
end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
end
end
运行pod install
来安装iOS依赖。
4. 初始化JPush并处理通知
在你的Flutter项目的main.dart
文件中,添加以下代码来初始化JPush并处理通知:
import 'package:flutter/material.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
void main() {
runApp(MyApp());
// 初始化JPush
JPush.init(appKey: "你的AppKey")
.then((result) {
print("JPush initialized: $result");
})
.catchError((error) {
print("Failed to initialize JPush: $error");
});
// 监听通知点击事件
JPush.addNotificationOpenedHandler((Map<String, dynamic> message) {
print("Notification opened: $message");
// 在这里处理通知点击事件,比如导航到某个页面
});
// 监听自定义消息接收事件
JPush.addReceiveNotificationHandler((Map<String, dynamic> message) {
print("Received notification: $message");
// 在这里处理自定义消息接收事件
});
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
[@override](/user/override)
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
[@override](/user/override)