Search code examples
androidflutterdartalarmmanagerflutter-dependencies

Doesn't support other plugins in Alarm manager? Flutter doesn't support background execution of some tasks(if we killed the app)?


I don't know this is an issue or bug. So I'm writing it. I wrote an alarm manager function to execute certain tasks periodically. it's firing periodically. But the problem is I can't use certain plugins inside that. I used the shared preference plugin to take some data from locally. But the alarm manager function returns null on that. I don't know why. It only happens inside that Alarm manager static function. I just used another plugin Get storage to do a similar thing again. But the result was similar. In my case, I am just trying to build a wallpaper App. I just wanna change the wallpaper periodically. There are numerous categories like nature, bike, car, etc. for selection. If the user selects one category. Then I just fired an alarm manager and should have to do automatically change wallpaper according to the category. Due to the static function of the alarm manager, for knowing selected categories I just wrote those to the locals. So for grabbing it in the alarm manager static function, I'm used shared preference and Get storage plugins. But both of them can't work as expected in the alarm manager. I don't know why. Is this a bug or is this due to the static function of the alarm manager? Is there any solution or is there any idea to overcome it?

my code when user taps on a button to set wallpaper for certain category:

   onPressed: () async {
      print("::::::::::::");
      await AndroidAlarmManager.initialize();
      var yes = await AndroidAlarmManager.cancel(id);
      await AndroidAlarmManager.cancel(id);
     
      categoryScheduled = searchController.text.toString();
      print(yes);

      final box = GetStorage();
      var data = {
        "category": categoryScheduled ,
      };
       await box.write("bg_image", data);

      final prefs = await SharedPreferences.getInstance();
      prefs.setString('counter', categoryScheduled);

      await AndroidAlarmManager.periodic(
        timeInterval,
        20,
        term,
      );
    },

Here suppose a user selects a category like "nature" for auto-change the wallpaper under the nature category. we just initialize the alarm manager. and also we cancel if a certain alarm is executing. After I'm trying to store that selected category locally using the Get storage plugin and after I tried with shared preference too. But I cant grab that in the alarm manager static function.

my alarm manager static function is given below:

static term() async {
    int pageNumber = 0;
   
final prefs = await SharedPreferences.getInstance();
//here we tries to grab the locally stored keyword using shared preferbnce but it return null.but its fine workin in another function.
final counter = prefs.getString('counter') ?? 0;

//next tried to grab it using another plugin to get storage. its also return null.
    final box = GetStorage();
    var readData = await box.read("bg_image");
    print(readData);
    print("this is category");

    var query = readData["category"];
    var results;

//tries to calling API with selected category. but category returning null.
    final response = await http.get(Uri.parse(
        "https://api.unsplash.com/search/photos/?client_id=7674db521921f5e47a89c6a432205d49db929dadaae45356226372c756e&page=$pageNumber&query=$query"));
    // if (response.statusCode == 200) {
    // itemCount++;
    // Scaffold.of(context).hideCurrentSnackBar();
    // If the call to the server was successful, parse the JSON
    var jsonData = json.decode(response.body);
    print(jsonData.length);
    results = jsonData["results"];
    print(results.length);

    print(results[0]["urls"]["full"]);
    var url = results[0]["urls"]["full"];
    var progressString = Wallpaper.ImageDownloadProgress(url);
    progressString.listen((data) {}, onDone: () async {
//setting walllpaper
      await Wallpaper.homeScreen();

      // scaffoldKey.currentState.showSnackBar(snackBar);
    }, onError: (error) {
      print("Some Error");
    });
  }

Solution

  • First of all thanks for the answers given by the guys.Those were very helpfull for me and got some new knowledge.As per the first answer we have to use flutter isolate.but it will not work when the app got killed. same stuffs happens in flutter local notifications plugin .To do this kind of work we can use two plugins (i got only two plugins,may there will be more)

    1.Flutter Alaram manager plus

    2.workmanager

    I had some issues with Alaram manager as described above.Anyway i found some solution for it .Current scenario was lack of plugin support ( both in alaram manager plugin and work manager plugin) in the callback function.As per some docs in the workmanager ,it says we have to register those plugins to do some stuffs in callback function.But there is no idea how to do same stuffs inside Alaram manager's callback function.So work manager may more preferable for this kind of scenario.But there was some problem(i dont know its may be bug) between currebt version(2.2.3) of flutter and workmanager plugin.so i just downgradedflutter version 2.0.3 and its workin fine for me.it will support shared preference plugin and wallpaper manager plugin inside that callback function .hence its gonna be ease for me to do that task.But still some of the plugin will not support in that callback function.For that we have to register those plugin to do that( you can search how to register a plugin in workmanager).Else you should have to use method channel to do this kind of work.Any way,in my case i just wanted those two plugins for my tasks,by god's grace its workin fine in callback function and its workin fine for me.