【问题标题】:Display notification when app is closed flutter应用关闭时显示通知
【发布时间】:2021-03-19 07:22:40
【问题描述】:

我尝试在 Flutter 应用程序中显示通知 1)当应用程序打开时,通知会显示,但 2)当 Flutter 应用程序关闭但它不工作或通知不显示时 我已共享我的 AndroidManifest.xml 文件,请检查它并帮助我,我是 Flutter 的新手

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tv_dashboard">
<!-- Internet Connection -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Display Notifications -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE" /> 
  <!-- io.flutter.app.FlutterApplication is an android.app.Application that
     calls FlutterMain.startInitialization(this); in its onCreate method.
     In most cases you can leave this as-is, but you if you want to provide
     additional functionality it is fine to subclass or reimplement
     FlutterApplication and put your custom class here. -->
<application
    android:name="io.flutter.app.FlutterApplication"
    android:label="Leads"
    android:usesCleartextTraffic="true"
    android:icon="@mipmap/ic_launcher">
    <activity
        android:name=".MainActivity"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:hardwareAccelerated="true"
        android:windowSoftInputMode="adjustResize"
        android:showWhenLocked="true"
        android:turnScreenOn="true">
        <!-- Specifies an Android theme to apply to this Activity as soon as
             the Android process has started. This theme is visible to the user
             while the Flutter UI initializes. After that, this theme continues
             to determine the Window background behind the Flutter UI. -->
        <meta-data
          android:name="io.flutter.embedding.android.NormalTheme"
          android:resource="@style/NormalTheme"
          />
        <!-- Displays an Android View that continues showing the launch screen
             Drawable until Flutter paints its first frame, then this splash
             screen fades out. A splash screen is useful to avoid any visual
             gap between the end of Android's launch screen and the painting of
             Flutter's first frame. -->
        <meta-data
          android:name="io.flutter.embedding.android.SplashScreenDrawable"
          android:resource="@drawable/launch_background"
          />
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
        </intent-filter>
    </receiver>
    <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />
    <!-- Don't delete the meta-data below.
         This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
    <meta-data
        android:name="flutterEmbedding"
        android:value="2" />
</application>

【问题讨论】:

    标签: flutter


    【解决方案1】:

    你可以用这个来做-

    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 _HomePageState extends State<HomePage> {
    @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(),
        );
      }
      } 
    

    依赖项

        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
    

        <!-- Add below permission inside 'manifest' tag -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <!-- Add below permission inside 'application' tag -->
    <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
    <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED"/>
    <action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
    </intent-filter>
    </receiver>
    
    • 并使用更多

    flutter_local_notifications

    谢谢

    【讨论】:

    • 您好先生,此代码在应用程序运行时有效,但当应用程序关闭时,此代码无效
    • 先生已经用过 FlutterLocalNotificationsPlugin
    猜你喜欢
    • 2018-12-22
    • 1970-01-01
    • 2021-09-23
    • 2020-08-25
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多