📜  Flutter的后台本地通知

📅  最后修改于: 2021-09-02 05:55:18             🧑  作者: Mango

有时用户需要一些非常重要的功能,如最新新闻更新、最新文章更新、天气状况警报、完成他/她的个人资料更新、未来事件更新等等,而无需打开应用程序,如果您愿意要开发这种 Android 和 iOS 应用程序,那么本文将帮助您这样做。在这个过程中,我们设置了后台作业,定期检查有关最新事件或警报的更新。

Flutter:

是由 Google 创建的开源 UI 软件开发工具包。它在通过单个代码库为 Android、Mac、Windows、Google Fuchsia、iOS、Linux 和 Web 开发应用程序时派上用场。

Dart:

它是一种客户端优化的编程语言,适用于多个平台上的应用程序。它用于开发移动、桌面、服务器和 Web 应用程序。 Dart是一种面向对象的语言,它也具有垃圾收集特性,并且具有类似于 C 编程语言的语法。它可以在本机代码或 JavaScript 中编译。

Flutter振工作管理器:

用作 Android 的 WorkManager 和 iOS performFetchWithCompletionHandler 的包装器,它有效地启用了后台Dart代码的无头执行。 WorkManager 提供了一个易于使用的 API,我们可以在其中定义后台作业应该运行一次,或者定期应用多个约束,例如如果任务需要互联网连接,或者电池是否应该充满电等等。

Flutter本地通知:

它是一个跨平台插件,用于在flutter应用程序中显示本地通知。它提供了一系列功能,例如安排何时出现通知,定期显示通知(基于时间间隔),当应用程序处于前台、后台或终止时处理用户点击通知时,指定自定义通知声音等等。

安卓工作室:

它是谷歌Android操作系统的官方集成开发环境(IDE),建立在JetBrains的IntelliJ IDEA软件之上,专为Android开发而设计,这个洞表示Android Studio将用作IDE。

在这里,我们正在创建具有无头执行的后台作业。首先,我们需要安装某些flutter插件,并且必须在本地系统中安装 Android Studio。

在开始之前,必须安装本地系统中的Flutter开发工具包和Android Studio IDE 中的Flutter插件。

  • 打开Android Studio并创建了一个名为“geeksforgeeks的名字一个新的flutter应用程序项目
  • 创建项目并成功同步后,将您的 Android 设备连接到 Android Studio 并确保开发人员选项和 USB 调试处于开启状态。
  • 通过单击中心顶部的第一个绿色图标来运行项目以交叉检查项目是否已构建并成功运行(第一次 Android Studio 像往常一样需要多一点时间)。
  • 现在,是时候安装必要的插件了,从geeksforgeeks -> pubspec.yaml项目结构中打开“pubspec.yaml”文件并复制粘贴两个依赖项,即 Workmanager 和 flutter_local_notifications,如下所示。
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  # Use with the Workmanger class for background jobs headless execution.
  workmanager: ^0.2.3
  # Use with FlutterLocalNotificationsPlugin class for local push notifications.
  flutter_local_notifications: ^1.4.4+2



  • 一旦完成上述步骤,然后单击出现在中心顶部的“ Packages get” flutter命令以安装所有必要的包和插件。
  • 现在,是时候添加一些所需的权限了,从geeksforgeeks -> android -> app -> src -> main -> AndroidManifest.xml项目目录结构中打开“AndroidManifest.xml”文件并复制粘贴以下权限。




    
        
        
    




现在,是时候编写代码了,打开“main.js”。 dart’文件来自geeksforgeeks -> lib -> main。 dart项目目录结构并复制粘贴整个代码。

Dart
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:workmanager/workmanager.dart';
  
void main() {
    
  // needed if you intend to initialize in the `main` function
  WidgetsFlutterBinding.ensureInitialized();
  Workmanager.initialize(
      
      // The top level function, aka callbackDispatcher
      callbackDispatcher,
      
      // If enabled it will post a notification whenever
      // the task is running. Handy for debugging tasks
      isInDebugMode: true
  );
  // Periodic task registration
  Workmanager.registerPeriodicTask(
    "2",
      
    //This is the value that will be
    // returned in the callbackDispatcher
    "simplePeriodicTask",
      
    // When no frequency is provided
    // the default 15 minutes is set.
    // Minimum frequency is 15 min.
    // Android will automatically change
    // your frequency to 15 min
    // if you have configured a lower frequency.
    frequency: Duration(minutes: 15),
  );
  runApp(MyApp());
}
  
void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) {
      
    // initialise the plugin of flutterlocalnotifications.
    FlutterLocalNotificationsPlugin flip = new FlutterLocalNotificationsPlugin();
      
    // app_icon needs to be a added as a drawable
    // resource to the Android head project.
    var android = new AndroidInitializationSettings('@mipmap/ic_launcher');
    var IOS = new IOSInitializationSettings();
      
    // initialise settings for both Android and iOS device.
    var settings = new InitializationSettings(android, IOS);
    flip.initialize(settings);
    _showNotificationWithDefaultSound(flip);
    return Future.value(true);
  });
}
  
Future _showNotificationWithDefaultSound(flip) async {
    
  // Show a notification after every 15 minute with the first
  // appearance happening a minute after invoking the method
  var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
      'your channel id',
      'your channel name',
      'your channel description',
      importance: Importance.Max,
      priority: Priority.High
  );
  var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
    
  // initialise channel platform for both Android and iOS device.
  var platformChannelSpecifics = new NotificationDetails(
      androidPlatformChannelSpecifics,
      iOSPlatformChannelSpecifics
  );
  await flip.show(0, 'GeeksforGeeks',
    'Your are one step away to connect with GeeksforGeeks',
    platformChannelSpecifics, payload: 'Default_Sound'
  );
}
  
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Geeks Demo',
      theme: ThemeData(
          
        // This is the theme
        // of your application.
        primarySwatch: Colors.green,
      ),
      home: HomePage(title: "GeeksforGeeks"),
    );
  }
}
  
class HomePage extends StatefulWidget {
  HomePage({Key key, this.title}) : super(key: key);
  // This widget is the home page of your application.
  // It is stateful, meaning
  // that it has a State object (defined below)
  // that contains fields that affect
  // how it looks.
  
  // This class is the configuration for the state.
  // It holds the values (in this
  // case the title) provided by the parent
  // (in this case the App widget) and
  // used by the build method of the State.
  // Fields in a Widget subclass are
  // always marked "final".
  
  final String title;
  
  @override
  _HomePageState createState() => _HomePageState();
}
  
class _HomePageState extends State {
  @override
  Widget build(BuildContext context) {
      
    // This method is rerun every time setState is called.
    // The Flutter framework has been optimized
    // to make rerunning build methods
    // fast, so that you can just rebuild
    // anything that needs updating rather
    // than having to individually change 
    //instances of widgets.
    return Scaffold(
      appBar: AppBar(
          
        // Here we take the value from
        // the MyHomePage object that was created by
        // the App.build method, and use it
        // to set our appbar title.
        title: Text(widget.title),
      ),
      body: new Container(),
    );
  }
}


最后,通过单击中间顶部的第一个绿色图标来运行项目以查看输出,您的工作就完成了。

输出:

参考:

  • https://pub.dev/packages/flutter_local_notifications/example
  • https://pub.dev/packages/workmanager/example