Skip to content

[Bug]: #400

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
2 of 3 tasks
ProgramTechBro opened this issue May 21, 2025 · 1 comment
Open
2 of 3 tasks

[Bug]: #400

ProgramTechBro opened this issue May 21, 2025 · 1 comment
Labels
bug Something isn't working

Comments

@ProgramTechBro
Copy link

Required Reading

  • Confirmed

Plugin Version

background_fetch 1.3.8

Flutter Doctor

[√] Flutter (Channel stable, 3.29.3, on Microsoft Windows [Version 10.0.26100.4061], locale en-US) [755ms]
    • Flutter version 3.29.3 on channel stable at C:\src\flutter\flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision ea121f8859 (6 weeks ago), 2025-04-11 19:10:07 +0000
    • Engine revision cf56914b32
    • Dart version 3.7.2
    • DevTools version 2.42.3

[√] Windows Version (Windows 11 or higher, 24H2, 2009) [3.8s]

[√] Android toolchain - develop for Android devices (Android SDK version 35.0.0) [5.2s]
    • Android SDK at C:\Users\VICTUS\AppData\Local\Android\sdk
    • Platform android-35, build-tools 35.0.0
    • Java binary at: C:\Program Files\Android\Android Studio\jbr\bin\java
      This is the JDK bundled with the latest Android Studio installation on this machine.
      To manually set the JDK path, use: `flutter config --jdk-dir="path/to/jdk"`.
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-b2043.56-9586694)
    • All Android licenses accepted.

[√] Chrome - develop for the web [414ms]
    • Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[!] Visual Studio - develop Windows apps (Visual Studio Professional 2019 16.11.26) [412ms]
    • Visual Studio at C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional
    • Visual Studio Professional 2019 version 16.11.33529.622
    X Visual Studio is missing necessary components. Please re-run the Visual Studio installer for the "Desktop development with C++" workload, and include
      these components:
        MSVC v142 - VS 2019 C++ x64/x86 build tools
         - If there are multiple build tool versions available, install the latest
        C++ CMake tools for Windows
        Windows 10 SDK

[√] Android Studio (version 2022.2) [25ms]
    • 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 17.0.6+0-b2043.56-9586694)

[√] VS Code (version 1.96.4) [24ms]
    • VS Code at C:\Users\VICTUS\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.110.0

[√] Connected device (3 available) [281ms]
    • Windows (desktop) • windows • windows-x64    • Microsoft Windows [Version 10.0.26100.4061]
    • Chrome (web)      • chrome  • web-javascript • Google Chrome 135.0.7049.96
    • Edge (web)        • edge    • web-javascript • Microsoft Edge 136.0.3240.76

[√] Network resources [1,011ms]
    • All expected network resources are available.

! Doctor found issues in 1 category.

Mobile operating-system(s)

  • iOS
  • Android

Device Manufacturer(s) and Model(s)

Vivo Y100

Device operating-systems(s)

Android 14

What happened?

Background Fetch not working when in release mode

Plugin Code and/or Config

import 'dart:math';
import 'package:android_intent_plus/android_intent.dart';
import 'package:background_fetch/background_fetch.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:home_widget/home_widget.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'app/routes/app_routes.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await _requestIgnoreBatteryOptimization();
  await HomeWidget.setAppGroupId('home_widget_example');

  // Start Background Fetch
  BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
  await BackgroundFetch.configure(
    BackgroundFetchConfig(
      minimumFetchInterval: 15, // minutes
      stopOnTerminate: false,
      enableHeadless: true,
      requiresBatteryNotLow: false,
      requiresCharging: false,
      requiresStorageNotLow: false,
      requiresDeviceIdle: false,
      requiredNetworkType: NetworkType.NONE,
      startOnBoot: true,
      //forceAlarmManager: true,
    ),
    _onBackgroundFetch,
    _onBackgroundFetchTimeout,
  );

  // Trigger first update after 5 seconds
  // Future.delayed(const Duration(seconds: 5), () async {
  //   print('⏱️ Initial widget update after 5 seconds');
  //   await updateWidgetWithRandomQuote();
  // });

  runApp(const MyApp());
}
Future<void> _requestIgnoreBatteryOptimization() async {
  final deviceInfo = DeviceInfoPlugin();
  final androidInfo = await deviceInfo.androidInfo;

  if (androidInfo.version.sdkInt >= 23) {
    const intent = AndroidIntent(
      action: 'android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS',
      data: 'package:com.example.quranic_qoutes',
    );
    await intent.launch();
  }
}
@pragma('vm:entry-point')
Future<void> _onBackgroundFetch(String taskId) async {
  print('[BackgroundFetch] Event received: $taskId');
  await Future.delayed(const Duration(seconds: 3));
  await updateWidgetWithRandomQuote();
  BackgroundFetch.finish(taskId);
}
@pragma('vm:entry-point')
void _onBackgroundFetchTimeout(String taskId) {
  print('[BackgroundFetch] TIMEOUT: $taskId');
  BackgroundFetch.finish(taskId);
}

@pragma('vm:entry-point')
void backgroundFetchHeadlessTask(HeadlessTask task) async {
  String taskId = task.taskId;
  bool isTimeout = task.timeout;
  if (isTimeout) {
    print('[BackgroundFetch] Headless TIMEOUT: $taskId');
    BackgroundFetch.finish(taskId);
    return;
  }
  print('[BackgroundFetch] Headless event received: $taskId');
  await updateWidgetWithRandomQuote();
  BackgroundFetch.finish(taskId);
}

@pragma('vm:entry-point')
Future<void> updateWidgetWithRandomQuote() async {
  print('--- Updating widget quote ---');
  try {
    List<Map<String, String>> quotes = [
      {
        "quote": "The only limit to our realization of tomorrow is our doubts of today.",
        "author": "F. D. Roosevelt"
      },
      {
        "quote": "Life is what happens when you're busy making other plans.",
        "author": "John Lennon"
      },
      {
        "quote": "What you get by achieving your goals is not as important as what you become by achieving your goals.",
        "author": "Zig Ziglar"
      },
      {
        "quote": "Do not watch the clock. Keep going.",
        "author": "Sam Levenson"
      },
      {
        "quote": "Success is not final, failure is not fatal: It is the courage to continue that counts.",
        "author": "Winston Churchill"
      },
      {
        "quote": "Believe you can and you're halfway there.",
        "author": "Theodore Roosevelt"
      },
      {
        "quote": "Your time is limited, so don’t waste it living someone else’s life.",
        "author": "Steve Jobs"
      },
      {
        "quote": "It does not matter how slowly you go as long as you do not stop.",
        "author": "Confucius"
      },
      {
        "quote": "Hardships often prepare ordinary people for an extraordinary destiny.",
        "author": "C.S. Lewis"
      },
      {
        "quote": "Don’t watch the clock; do what it does. Keep going.",
        "author": "Sam Levenson"
      },
    ];


    // final random = Random();
    // final randomQuote = quotes[random.nextInt(quotes.length)];
    final prefs = await SharedPreferences.getInstance();
    int lastIndex = prefs.getInt('last_quote_index') ?? -1;
    int newIndex;
    do {
      newIndex = Random().nextInt(quotes.length);
    } while (newIndex == lastIndex && quotes.length > 1);
    final randomQuote = quotes[newIndex];
    prefs.setInt('last_quote_index', newIndex);


    await HomeWidget.saveWidgetData<String>('quote', randomQuote['quote'] ?? '');
    await HomeWidget.saveWidgetData<String>('author', randomQuote['author'] ?? '');

    await HomeWidget.updateWidget(
      name: 'HomeScreenWidget',
      androidName: 'HomeScreenWidget',
    );

    print('✅ Widget updated successfully');
  } catch (e) {
    print('❌ Widget update error: $e');
  }
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      initialRoute: AppRoutes.SPLASH,
      getPages: AppRoutes.routes,
    );
  }
}

Relevant log output

@ProgramTechBro ProgramTechBro added the bug Something isn't working label May 21, 2025
@christocracy
Copy link
Member

See readme to learn how to simulate tasks. When simulated tasks work, your job is done.

See https://dontkillmyapp.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants