fluttercommunity / flutter_workmanager

A Flutter plugin which allows you to execute code in the background on Android and iOS.
825 stars 247 forks source link

🐞[Android, periodic task not working with the flutter pedometer plugin] #369

Open eniafou opened 2 years ago

eniafou commented 2 years ago
Technology Version
Workmanager version ^0.4.1
pedometer version ^3.0.0

Describe the error the task work fine when the app is open but when the user switch or terminate the app the task is cancelled

my code :

Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
Workmanager().registerPeriodicTask(
  "1",
  "Task",
  frequency: const Duration(minutes: 15),
);

void callbackDispatcher() {
  Workmanager().executeTask((task, inputData){
    print(
        "#####################################################################################################################################################################################################################");
    print("I am in the callbackDispatcher");
    return BackGroundWork().loadCounterValueJob();
  });
}

Future<bool> loadCounterValueJob() async {
    print(await Permission.activityRecognition.isGranted);
    Stream<StepCount> stepCountStream = Pedometer.stepCountStream;
    StepCount rawStep = await stepCountStream.first;
    DateTime timeStamp = rawStep.timeStamp;
    int rawValue = rawStep.steps;
    print(timeStamp);
    print(rawValue);
    return true;
  }

Error output:

D/PathProviderPlugin(20936): Use TaskQueues.
I/flutter (20936): #####################################################################################################################################################################################################################
I/flutter (20936): I am in the callbackDispatcher
I/flutter (20936): true
D/SensorManager(20936): registerListener :: 191, Step Counter  Non-wakeup, 0, 0, com.example.pedometer.SensorEventListenerFactoryKt$sensorEventListener$1@58cab3d
I/WM-WorkerWrapper(20936): Work [ id=a33089e0-32b3-4ed6-880e-973853052fda, tags={ be.tramckrijte.workmanager.BackgroundWorker } ] was cancelled
I/WM-WorkerWrapper(20936): java.util.concurrent.CancellationException: Task was cancelled.
I/WM-WorkerWrapper(20936):  at androidx.work.impl.utils.futures.AbstractFuture.cancellationExceptionWithCause(AbstractFuture.java:1184)
I/WM-WorkerWrapper(20936):  at androidx.work.impl.utils.futures.AbstractFuture.getDoneValue(AbstractFuture.java:514)
I/WM-WorkerWrapper(20936):  at androidx.work.impl.utils.futures.AbstractFuture.get(AbstractFuture.java:475)
I/WM-WorkerWrapper(20936):  at androidx.work.impl.WorkerWrapper$2.run(WorkerWrapper.java:298)
I/WM-WorkerWrapper(20936):  at androidx.work.impl.utils.SerialExecutor$Task.run(SerialExecutor.java:91)
I/WM-WorkerWrapper(20936):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
I/WM-WorkerWrapper(20936):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
I/WM-WorkerWrapper(20936):  at java.lang.Thread.run(Thread.java:923)

Output of flutter doctor -v

[√] Flutter (Channel stable, 2.10.3, on Microsoft Windows [version 10.0.19044.1586], locale fr-FR)
    β€’ Flutter version 2.10.3 at C:\apps\flutter
    β€’ Upstream repository https://github.com/flutter/flutter.git
    β€’ Framework revision 7e9793dee1 (3 weeks ago), 2022-03-02 11:23:12 -0600
    β€’ Engine revision bd539267b4
    β€’ Dart version 2.16.1
    β€’ DevTools version 2.9.2

[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
    β€’ Android SDK at C:\Users\21262\AppData\Local\Android\sdk
    β€’ Platform android-31, build-tools 31.0.0
    β€’ Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java      
    β€’ Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)        
    β€’ All Android licenses accepted.

[√] Chrome - develop for the web
    β€’ Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[√] Visual Studio - develop for Windows (Visual Studio Community 2019 16.10.3)      
    β€’ Visual Studio at C:\Program Files (x86)\Microsoft Visual Studio\2019\Community
    β€’ Visual Studio Community 2019 version 16.10.31424.327
    β€’ Windows 10 SDK version 10.0.19041.0

[√] Android Studio (version 2020.3)
    β€’ Android Studio at C:\Program Files\Android\Android Studio
    β€’ Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    β€’ Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    β€’ Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)

[√] VS Code (version 1.65.2)
    β€’ VS Code at C:\Users\21262\AppData\Local\Programs\Microsoft VS Code
    β€’ Flutter extension version 3.36.0

[√] Connected device (4 available)
    β€’ SM T505N (mobile) β€’ R9WN91V68YJ β€’ android-arm64  β€’ Android 11 (API 30)
    β€’ Windows (desktop) β€’ windows     β€’ windows-x64    β€’ Microsoft Windows [version 10.0.19044.1586]
    β€’ Chrome (web)      β€’ chrome      β€’ web-javascript β€’ Google Chrome 99.0.4844.74
    β€’ Edge (web)        β€’ edge        β€’ web-javascript β€’ Microsoft Edge 99.0.1150.46

[√] HTTP Host Availability
    β€’ All required HTTP hosts are available

β€’ No issues found!
ened commented 2 years ago

Try wrapping the code inside loadCounterValueJob in a try catch block. I suspect a error is thrown but uncaught which causes the task to be cancelled.

eniafou commented 2 years ago

ok, I did that :

Future<bool> loadCounterValueJob() async {
    try {
    print(await Permission.activityRecognition.isGranted);
    Stream<StepCount> stepCountStream = Pedometer.stepCountStream;
    StepCount rawStep = await stepCountStream.first;
    DateTime timeStamp = rawStep.timeStamp;
    int rawValue = rawStep.steps;
    print(timeStamp);
    print(rawValue);
    }catch (err) {
      print((err.toString()));
      throw Exception(err);
    }

    return true;
  }

Now the error output is :

D/PathProviderPlugin(29386): Use TaskQueues.
I/flutter (29386): #####################################################################################################################################################################################################################
I/flutter (29386): I am in the callbackDispatcher
I/flutter (29386): true
D/SensorManager(29386): registerListener :: 191, Step Counter  Non-wakeup, 0, 0, com.example.pedometer.SensorEventListenerFactoryKt$sensorEventListener$1@763ddad
V/NativeCrypto(29386): Read error: ssl=0xb400007894630748: I/O error during system call, Software caused connection abort
V/NativeCrypto(29386): Write error: ssl=0xb400007894630748: I/O error during system call, Broken pipe
V/NativeCrypto(29386): SSL shutdown failed: ssl=0xb400007894630748: I/O error during system call, Success
15
W/ManagedChannelImpl(29386): [{0}] Failed to resolve name. status={1}
I/WM-WorkerWrapper(29386): Work [ id=a33089e0-32b3-4ed6-880e-973853052fda, tags={ be.tramckrijte.workmanager.BackgroundWorker } ] was cancelled
I/WM-WorkerWrapper(29386): java.util.concurrent.CancellationException: Task was cancelled.
I/WM-WorkerWrapper(29386):  at androidx.work.impl.utils.futures.AbstractFuture.cancellationExceptionWithCause(AbstractFuture.java:1184)
I/WM-WorkerWrapper(29386):  at androidx.work.impl.utils.futures.AbstractFuture.getDoneValue(AbstractFuture.java:514)
I/WM-WorkerWrapper(29386):  at androidx.work.impl.utils.futures.AbstractFuture.get(AbstractFuture.java:475)
I/WM-WorkerWrapper(29386):  at androidx.work.impl.WorkerWrapper$2.run(WorkerWrapper.java:298)
I/WM-WorkerWrapper(29386):  at androidx.work.impl.utils.SerialExecutor$Task.run(SerialExecutor.java:91)
I/WM-WorkerWrapper(29386):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
I/WM-WorkerWrapper(29386):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
I/WM-WorkerWrapper(29386):  at java.lang.Thread.run(Thread.java:923)
ened commented 2 years ago

Interesting. Do you have permissions? Can you upload a small sample repo on Github so it becomes easy to debug?

eniafou commented 2 years ago

I made a simple repo to produce the issue here.

lluisclava commented 1 year ago

This will never work. By definition, Android does not allow to get steps information while your app is in background. Link: https://developer.android.com/guide/topics/sensors/sensors_overview#only-gather-sensor-data-in-the-foreground

I solved using only in Android the pluguin: https://pub.dev/packages/flutter_foreground_task combined with pedometer.

Aashish-Dahal commented 2 weeks ago

This will never work. By definition, Android does not allow to get steps information while your app is in background. Link: https://developer.android.com/guide/topics/sensors/sensors_overview#only-gather-sensor-data-in-the-foreground

I solved using only in Android the pluguin: https://pub.dev/packages/flutter_foreground_task combined with pedometer.

if possible please share your code ,repo or anything