Skip to content

[Bug]: When App was killed, it is not working #391

Open
@Kimsoer

Description

@Kimsoer

Required Reading

  • Confirmed

Plugin Version

latest

Flutter Doctor

[√] Flutter (Channel stable, 3.29.0, on Microsoft Windows [Version 10.0.22631.4974], locale en-US)
[√] Windows Version (11 Pro 64-bit, 23H2, 2009)
[√] Android toolchain - develop for Android devices (Android SDK version 35.0.1)
[√] Chrome - develop for the web
[X] Visual Studio - develop Windows apps
    X Visual Studio not installed; this is necessary to develop Windows apps.
      Download at https://visualstudio.microsoft.com/downloads/.
      Please install the "Desktop development with C++" workload, including all of its default components
[√] Android Studio (version 2024.2)
[√] VS Code (version 1.98.0)
[√] Connected device (4 available)
[√] Network resources

Mobile operating-system(s)

  • iOS
  • Android

Device Manufacturer(s) and Model(s)

android vivo

Device operating-systems(s)

android 12

What happened?

Image

I got this log when i kill app.

Plugin Code and/or Config

var enabled = true.obs;
  var status = 0.obs;
  var events = <DateTime>[].obs;
  var elapsedTime = 0.obs;
  Timer? _timer;

  @override
  void onInit() {
    super.onInit();
    WidgetsBinding.instance.addObserver(this);
    initPlatformState();
    startTimer();
  }

  Future<void> initPlatformState() async {
    // Configure BackgroundFetch.
    int status = await BackgroundFetch.configure(
      BackgroundFetchConfig(
        minimumFetchInterval: 15,
        stopOnTerminate: false, // Continue running when the app is terminated.
        startOnBoot: true, // Start background fetch when the device boots.
        enableHeadless: true, // Enable headless task for Android.
        requiresBatteryNotLow: false,
        requiresCharging: false,
        requiresStorageNotLow: false,
        requiresDeviceIdle: false,
        requiredNetworkType: NetworkType.NONE,
        forceAlarmManager: true, // Use AlarmManager for better reliability.
      ),
          (String taskId) async {
        print("[BackgroundFetch] Event received $taskId");
        await updateElapsedTime();
        BackgroundFetch.finish(taskId);
      },
          (String taskId) async {
        print("[BackgroundFetch] TASK TIMEOUT taskId: $taskId");
        BackgroundFetch.finish(taskId);
      },
    );
    print('[BackgroundFetch] configure success: $status');
    this.status.value = status;
  }

  void startTimer() async {
    final prefs = await SharedPreferences.getInstance();
    final startTime = prefs.getInt('startTime') ?? DateTime.now().millisecondsSinceEpoch;
    final now = DateTime.now().millisecondsSinceEpoch;
    elapsedTime.value = (now - startTime) ~/ 1000; // Calculate elapsed time in seconds.

    _timer = Timer.periodic(Duration(seconds: 1), (timer) async {
      elapsedTime.value++;
      if (elapsedTime.value % 10 == 0) {
        // Send an event every 10 seconds.
        events.insert(0, DateTime.now());
        await sendLocationToTelegram(10, 2); // Example coordinates.
        print('[Timer] Event sent at ${DateTime.now()}');
      }
    });
  }

  Future<void> updateElapsedTime() async {
    final prefs = await SharedPreferences.getInstance();
    final startTime = prefs.getInt('startTime') ?? DateTime.now().millisecondsSinceEpoch;
    final now = DateTime.now().millisecondsSinceEpoch;
    elapsedTime.value = (now - startTime) ~/ 1000; // Update elapsed time in seconds.
  }

  void toggleEnabled(bool value) {
    enabled.value = value;
    if (value) {
      BackgroundFetch.start().then((int status) {
        print('[BackgroundFetch] start success: $status');
      }).catchError((e) {
        print('[BackgroundFetch] start FAILURE: $e');
      });
    } else {
      BackgroundFetch.stop().then((int status) {
        print('[BackgroundFetch] stop success: $status');
      });
    }
  }

  void checkStatus() async {
    int status = await BackgroundFetch.status;
    print('[BackgroundFetch] status: $status');
    this.status.value = status;
  }
  @override
  void onClose() {
    WidgetsBinding.instance.removeObserver(this); // Remove observer.
    _timer?.cancel(); // Stop the timer.
    super.onClose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused) {
      // App is sent to the background.
      _timer?.cancel(); // Stop the timer.
    } else if (state == AppLifecycleState.resumed) {
      // App is brought back to the foreground.
      startTimer(); // Restart the timer.
    }
  }

Relevant log output

I/flutter ( 7638): [Timer] Event sent at 2025-03-10 14:13:50.138851
I/GED     ( 7638): ged_boost_gpu_freq, level 100, eOrigin 2, final_idx 2, oppidx_max 2, oppidx_min 0
I/BufferQueueProducer( 7638): [SurfaceView[com.example.app_location_track/com.example.app_location_track.MainActivity]#1(BLAST Consumer)1](id:1dd600000001,api:1,p:7638,c:7638) disconnect: api 1
I/BufferQueueProducer( 7638): [SurfaceView[com.example.app_location_track/com.example.app_location_track.MainActivity]#1(BLAST Consumer)1](id:1dd600000001,api:0,p:-1,c:7638) disconnect: api -1
I/BufferQueueProducer( 7638): [ViewRootImpl[MainActivity]#0(BLAST Consumer)0](id:1dd600000000,api:1,p:7638,c:7638) disconnect: api 1
I/BLASTBufferQueue( 7638): [ViewRootImpl[MainActivity]#0] destructor()
I/BufferQueueConsumer( 7638): [ViewRootImpl[MainActivity]#0(BLAST Consumer)0](id:1dd600000000,api:0,p:-1,c:7638) disconnect
I/GED     ( 7638): ged_boost_gpu_freq, level 100, eOrigin 2, final_idx 2, oppidx_max 2, oppidx_min 0
I/GED     ( 7638): ged_boost_gpu_freq, level 100, eOrigin 2, final_idx 2, oppidx_max 2, oppidx_min 0
D/TSBackgroundFetch( 7638): ☯️  onPause
D/TSBackgroundFetch( 7638): ☯️  onStop
I/BLASTBufferQueue( 7638): releaseBufferCallbackThunk bufferId:32804960206852 framenumber:2 blastBufferQueue is dead
D/TSBackgroundFetch( 7638): ☯️  HeadlessMode? true

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions