又到了推荐好插件的时候了。开发 APP 避免不了使用「推送」功能。好比,新上架一个商品,或者最新的一条体育新闻,实时推送给用户。php
比较了几家推送平台,貌似「极光」出了 Flutter 插件,因此就拿它试试手,顺便记录下整个推送功能开发流程。html
说到「推送」,天然有推送端和接收端,接收端天然包括 Android 端和 iOS 端。android
引入插件:ios
flutter_jpush: ^0.0.4
复制代码
在 main.dart
加入初始化代码:git
void _initJPush() async {
await FlutterJPush.startup();
print("初始化jpush成功");
// 获取 registrationID
var registrationID =await FlutterJPush.getRegistrationID();
print(registrationID);
// 注册接收和打开 Notification()
_initNotification();
}
void _initNotification() async {
FlutterJPush.addReceiveNotificationListener(
(JPushNotification notification) {
print("收到推送提醒: $notification");
}
);
FlutterJPush.addReceiveOpenNotificationListener(
(JPushNotification notification) {
print("打开了推送提醒: $notification");
}
);
}
复制代码
在极光后台建立应用,生成 appkey 等信息,Android 配置好说,添加包名便可。github
在项目 Android 工程 build.gradle
代码中,增长配置信息:编程
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.*.*"
minSdkVersion 16
targetSdkVersion 27
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
manifestPlaceholders = [
JPUSH_PKGNAME : applicationId,
JPUSH_APPKEY : "****", // 极光上注册的包名对应的appkey.
JPUSH_CHANNEL : "developer-default",
]
}
复制代码
好了,咱们先在极光后台编写一条消息通知,看看效果。json
当 APP 处于打开状态,经过命令好 log,咱们能看到「收到推送提醒」: api
同时,咱们在通知栏上也能收到这条消息推送通知:bash
打开这条通知后,执行的是「addReceiveOpenNotificationListener」
就是这么简单。
如何申请证书和签权,具体看极光的说明:docs.jiguang.cn/jpush/clien…
须要注意的是,先在 Xcode 那打开「Push Notifications」
在「iOS」工程下,添加极光配置信息:
增长
#include "FlutterJPushPlugin.h"
增长
[self startupJPush:launchOptions appKey:@"你的key" channel:@"你的渠道" isProduction:是否生产版本];
复制代码
好了,配置以后,dart 端仍是上面的一样代码,仍是利用极光的后台,推送一条测试通知,看看效果:
打开该通知后,也执行 print
了:
只要消息能到达客户端,那具体怎么使用,或者打开客户端跳转到具体页面,这些工做就好说了,此处就不必展开说了。
剩下的就是后台接口推送通知了,总不能每次都要在「极光」后台作推送吧!
因此咱们须要借助「极光」提供的接口了。
极光提供了多语言服务端 SDK,基本能够知足咱们的集成须要了。
我仍是以 Laravel 为案例,简要说一说集成。
1. composer.json
文件中添加 jpush
依赖.
"jpush/jpush": "^3.5"
复制代码
2. 写一个 demo 命令行推送服务:
Artisan::command('jpush', function () {
$client = new \JPush\Client($app_key, $master_secret);
})->describe('jpush');
复制代码
3. 发送一个通知试试:
$client->push()
->setPlatform('all')
->addAllAudience()
->setNotificationAlert('你好, 极光推送')
->send();
复制代码
执行命令:php artisan jpush
看看:
okey,到目前为止,经过简单的例子,就能够把从服务端到客户端走通 Push 流程。
注:服务端 SDK 参考
若是知道怎么结合原生 Android 和 iOS 插件集成到 Flutter 上,那使用极光推送,也能够不须要官方提供的 Flutter 插件,相信你也能写。
相反地,使用官方提供的 Flutter 插件和集成文档,可让咱们快速的完成 push 通知功能,可让咱们更聚焦于咱们的产品逻辑和功能上。