简体   繁体   中英

Flutter local notifications package not working when scheduling a notification not in the range of a few hours

I am trying to create an app that reminds me when I have to move the car, so I need to be able to schedule notifications even 2 weeks in the future. I want to receive notifications even if I am offline, for this reason I am using this package and not Firebase. When I set manually a time in the near future, for example in the range of an hour, it all works fine, even if I close the app, but when I set the correct datetime I never receive them. I will show you what I have got so far (keep in mind that I am testing it on Android).

This is part of my AndroidManifest

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

    <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />
    <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"></action>
        </intent-filter>
    </receiver>

Then this is the file where the notifications are scheduled

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';


class InfoBottomSheet extends StatelessWidget {

  final String address;
  String dateNotification;
  final int code;
  final dio = new Dio();

  FlutterLocalNotificationsPlugin localNotificationsPlugin = FlutterLocalNotificationsPlugin();
  initializeNotifications() async {
    var initializeAndroid = AndroidInitializationSettings('icon');
    var initializeIOS = IOSInitializationSettings();
    var initSettings = InitializationSettings(initializeAndroid, initializeIOS);
    await localNotificationsPlugin.initialize(initSettings);
  }

  Future singleNotification( DateTime datetime, String message, String subtext, int hashcode) async {
    var androidChannel = AndroidNotificationDetails(
      'channel-id',
      'channel-name',
      'channel-description',
      importance: Importance.Max,
      priority: Priority.Max,
    );
    var iosChannel = IOSNotificationDetails();
    var platformChannel = NotificationDetails(androidChannel, iosChannel);
    localNotificationsPlugin.schedule(
      hashcode, message, subtext, datetime, platformChannel,
    );
  }

  void getDate() async {
    Response response = await dio.get('http://myApiCall/car-move-date?address=${address.toUpperCase()}');
    dateNotification = response.data['date'] + " " + response.data['time'] + ":00";
  }

  InfoBottomSheet(this.address, this.code);

  @override
  Widget build(BuildContext context) {
    return Container(
          child: Padding(
            padding: EdgeInsets.all(5.0),
            child: Column(
              children: <Widget>[
                Padding(
                  padding:EdgeInsets.fromLTRB(12,12,12,6),
                  child:Text(
                    address,
                  ),
                ),
                Padding(padding: EdgeInsets.fromLTRB(10,20,10,20),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            SizedBox(
                              width: 130,
                              height: 50,
                              child:RaisedButton(
                                elevation: 5.0,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(20.0),
                                ),
                                color: Colors.white,
                                onPressed: () async {
                                  await getDate();
                                  await initializeNotifications();
                                  print("Park here");
                                  var parsedDate = DateTime.parse(dateNotification);
                                  await singleNotification(
                                      parsedDate,
                                      address,
                                      "You parked here",
                                      code,
                                  );
                                  Navigator.pop(context);
                                },
                              )
                            ),
                          ],
                        )
                      ),
                    );
                  }

I deleted useless parts, therefore maybe something is wrong, like missing parenthesis or stuff like that, but I assure you that everything works fine, beside the notifications obviously. The getDate() function makes a call to my api and returns a string like this "2020-05-30 20:37", that should be the moment of the notification. Address is a string with the name of a street that is inside the database. Code is the unique code of that street. But as I said that all works just fine, so don t waste time searching for an error there.

Maybe it's a problem with your API. You don't need to make an API request, dart provides exactly this by its self.

void getDate() { return DateTime.now(); }  

The output is something like

2020-08-29 12:34:17.633

As written in the documentation , some Android phones restrict background execution to save battery power. So this might be a problem. check it from the settings and enable the background execution with no restrictions and try again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM