Sli*_*nTN 14 mobile-application push-notification apple-push-notifications android-notifications flutter
我已经构建了一个带有颤动的应用程序,就像提醒一样.
即使应用程序已关闭,如何向用户显示通知?
小智 14
我找到了解决这个问题的方法。我们只需要在 Application 类中注册本地通知插件。
首先创建一个类 FlutterLocalNotificationPluginRegistrant,我在 Kotlin 中创建了这个。
class FlutterLocalNotificationPluginRegistrant {
companion object {
fun registerWith(registry: PluginRegistry) {
if (alreadyRegisteredWith(registry)) {
Log.d("Local Plugin", "Already Registered");
return
}
FlutterLocalNotificationsPlugin.registerWith(registry.registrarFor("com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin"))
Log.d("Local Plugin", "Registered");
}
private fun alreadyRegisteredWith(registry: PluginRegistry): Boolean {
val key = FlutterLocalNotificationPluginRegistrant::class.java.canonicalName
if (registry.hasPlugin(key)) {
return true
}
registry.registrarFor(key)
return false
}
}}
Run Code Online (Sandbox Code Playgroud)
现在创建一个扩展 FlutterApplication 的 Application 类并实现 PluginRegistry.PluginRegistrantCallback。
class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
override fun onCreate() {
super.onCreate()
}
override fun registerWith(registry: PluginRegistry?) {
if (registry != null) {
FlutterLocalNotificationPluginRegistrant.registerWith(registry)
}
}}
Run Code Online (Sandbox Code Playgroud)
并在 AndroidManifest.xml 中注册 Application 类
<application
android:name="com.packagename.Application"/>
Run Code Online (Sandbox Code Playgroud)
全部完成。现在编写一个函数来显示通知并从 Firebase 消息传递的后台处理程序方法中调用它。
Future _showNotificationWithDefaultSound(String title, String message) async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'channel_id', 'channel_name', 'channel_description',
importance: Importance.Max, priority: Priority.High);
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
'$title',
'$message',
platformChannelSpecifics,
payload: 'Default_Sound',
);
}
Run Code Online (Sandbox Code Playgroud)
并这样称呼它。
Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
if (message['data'] != null) {
final data = message['data'];
final title = data['title'];
final body = data['message'];
await _showNotificationWithDefaultSound(title, message);
}
return Future<void>.value();
}
Run Code Online (Sandbox Code Playgroud)
a2e*_*2en 13
为了提醒我,我建议使用Flutter Local Notifications插件。它具有强大的调度API。从本地通知的文档中:
安排应在何时出现通知-定期显示通知(基于时间间隔)-安排在指定时间每天显示一次通知-安排在指定日期和时间每周显示一次通知-能够在用户点击时进行处理当应用程序是前台,后台或终止时在通知上显示
对于推送通知,您可以使用Firebase Cloud Messaging 或一个信号插件,也可以通过平台渠道本地实现
编辑:即使应用程式终止,您也可以根据特定条件触发通知。这可以通过在后台运行飞镖代码来解决。引用官方常见问题解答:
我可以在Flutter应用程序的后台运行Dart代码吗?是的,您可以在iOS和Android的后台进程中运行Dart代码。有关更多信息,请参见中篇文章“使用Flutter插件和地理围栏在后台执行Dart”。
| 归档时间: |
|
| 查看次数: |
14767 次 |
| 最近记录: |