transistorsoft/react-native-background-fetch

Headless Task not working in Android

SilKeshari opened this issue · 18 comments

Your Environment

  • Plugin version:
  • Platform: Android
  • OS version: Android 13
  • Device manufacturer / model: Realme Narzo 30
  • React Native version (react-native -v): 0.72.6
  • react-native-background-fetch version: ^4.2.1
  • Plugin config

Main Component :

const MainComponent = props => {

  const initBackgroundHandler = async () => {
    const status = await BackgroundFetch.configure(
      {
        taskId: 'newTask',
        minimumFetchInterval: 15, // <-- minutes (15 is minimum allowed)
        stopOnTerminate: false,
        enableHeadless: true,
        startOnBoot: true,
      },
      async taskId => {
        console.log('get Realm data ', data);
        console.log('on Event taskId: ', taskId);
        //displayPushNotification(); // will call in headless task to show notification
      },
      taskId => {
        console.log('[Fetch] TIMEOUT taskId:', taskId);
        BackgroundFetch.finish(taskId);
      },
    );
    console.log('Background fetch status', status);
  };

  useEffect(() => {
    initBackgroundHandler();
    initPushNotifications(); // initial config to show notification
  }, []);

  return (
    <SafeAreaView>
      <View style={{padding: 10}}>
        // Some Code
      </View>
    </SafeAreaView>
  );
};

App.js :

import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import React, {useEffect} from 'react';
import EditRecord from './src/EditRecord';
import MainComponent from './src/MainComponent';
import ViewRecord from './src/ViewRecord';
import {useRealmContext} from './databases/RealmContext';
const Stack = createNativeStackNavigator();
const App = () => {
  const {RealmProvider} = useRealmContext();

  return (
    <RealmProvider>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name="Home" component={MainComponent} />
          <Stack.Screen name="ViewRecord" component={ViewRecord} />
          <Stack.Screen name="EditRecord" component={EditRecord} />
        </Stack.Navigator>
      </NavigationContainer>
    </RealmProvider>
  );
};
export default App;

Index.js:

import {AppRegistry} from 'react-native';
import BackgroundFetch from 'react-native-background-fetch';
import App from './App';
import {name as appName} from './app.json';

import {
  displayPushNotification,
  getDataFromAsync,
  sendDataToServer,
} from './src/Utils';

const MyHeadlessTask = async taskData => {
  console.log('[BackgroundFetch HeadlessTask] start: ', taskData);

  // Do something in the background.
  // For example, fetch new data or sync with the server.
  const dbData = await getDataFromAsync();
  console.log('get Realm data HeadlessTask', dbData);
  const serverResponse = await sendDataToServer(dbData);
  console.log('on HeadlessTask serverResponse', serverResponse[0].data);
  console.log('on Event taskId: HeadlessTask', taskData);
  displayPushNotification();

  console.log('[BackgroundFetch HeadlessTask] finish: ', taskData);
  BackgroundFetch.finish(taskData);
};

BackgroundFetch.registerHeadlessTask(MyHeadlessTask);
AppRegistry.registerComponent(appName, () => App);

I have gone through the docs many times not able to identify the issue, configured everything as mentioned in docs. I have attached the logs below. Running the app in real device. Please let me know if any other info is required.

Expected Behavior

Headless task should be called when app is in background or terminated.

Actual Behavior

Headless task is not getting called when app is terminated or in background only callback function gets called in when is open.

Context

I am trying to run task when app is in background or terminated after every 15mins.

Debug logs

Screenshot 2023-10-28 at 10 50 40 AM

Terminated the app at 10:23 waited till 10:50 ,nothing happened.

@christocracy kindly help with this issue.

See readme to learn how to simulate events. You don't need to "wait" for things to happen.

Simulating events is all you need to do to learn that it works. Everything else is up to the OS.

Also see https://dontkillmyapp.com

@christocracy ,
I provided the time details to highlight an issue with headless tasks not initiating upon application termination. I kindly request your assistance in reviewing the configuration I shared.
Additionally, could you verify if there is a need to include any specific permissions in the manifest file?
I intend to examine the simulation aspect and will update you accordingly. Rather than simulating, I attempted to acquire the results on my physical device.
Your prompt attention to this matter would be greatly appreciated.
Thank you

Your config is fine. Now go simulate tasks as documented in the readme. It's easy.

if there is a need to include any specific permissions in the manifest file?

Everything required to set this plug-in up is documented in the Setup Instructions linked in the readme. There is nothing left out.

Hi @christocracy I tried to simulate the events as mentioned, the following logs appeared -

user@192 BackgroundFetch % adb logcat *:S ReactNative:V ReactNativeJS:V TSBackgroundFetch:V
--------- beginning of main
12-21 15:35:26.740 29536 29905 D TSBackgroundFetch: - configure
12-21 15:35:26.741 29536 29905 D TSBackgroundFetch: Re-configured existing task
12-21 15:35:26.741 29536 29905 I TSBackgroundFetch: - cancel taskId=react-native-background-fetch, jobId=0
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: {
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: "taskId": "react-native-background-fetch",
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: "isFetchTask": true,
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: "minimumFetchInterval": 15,
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: "stopOnTerminate": false,
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: "requiredNetworkType": 0,
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: "requiresBatteryNotLow": false,
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: "requiresCharging": false,
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: "requiresDeviceIdle": false,
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: "requiresStorageNotLow": false,
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: "startOnBoot": true,
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: "jobService": "com.transistorsoft.rnbackgroundfetch.HeadlessTask",
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: "forceAlarmManager": false,
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: "periodic": true,
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: "delay": -1
12-21 15:35:26.763 29536 29905 D TSBackgroundFetch: }
12-21 15:35:26.809 29536 29904 I ReactNativeJS: 'Background fetch status', 2
12-21 15:35:33.901 29536 29536 D TSBackgroundFetch: ☯️ onPause
12-21 15:35:33.902 29536 29536 D TSBackgroundFetch: ☯️ onStop
12-21 15:36:12.823 32411 532 D TSBackgroundFetch: [RNBackgroundFetch initialize]
12-21 15:36:12.826 32411 32411 D TSBackgroundFetch: ☯️ onCreate
12-21 15:36:12.876 32411 32411 D TSBackgroundFetch: ☯️ HeadlessMode? true
12-21 15:36:14.111 32411 533 I ReactNativeJS: Running "BackgroundFetch" with {"rootTag":11}
12-21 15:36:15.152 32411 534 D TSBackgroundFetch: - configure
12-21 15:36:15.152 32411 534 D TSBackgroundFetch: - start
12-21 15:36:15.159 32411 534 D TSBackgroundFetch: - registerTask: react-native-background-fetch (jobId: 999)
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: {
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: "taskId": "react-native-background-fetch",
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: "isFetchTask": true,
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: "minimumFetchInterval": 15,
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: "stopOnTerminate": false,
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: "requiredNetworkType": 0,
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: "requiresBatteryNotLow": false,
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: "requiresCharging": false,
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: "requiresDeviceIdle": false,
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: "requiresStorageNotLow": false,
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: "startOnBoot": true,
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: "jobService": "com.transistorsoft.rnbackgroundfetch.HeadlessTask",
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: "forceAlarmManager": false,
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: "periodic": true,
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: "delay": -1
12-21 15:36:15.162 32411 534 D TSBackgroundFetch: }
12-21 15:36:15.222 32411 533 I ReactNativeJS: 'Background fetch status', 2
12-21 15:37:01.830 32411 32411 D TSBackgroundFetch: ☯️ onStart
12-21 15:37:01.834 32411 32411 D TSBackgroundFetch: ☯️ onResume
12-21 15:37:20.422 32411 32411 D TSBackgroundFetch: - Background Fetch event received: react-native-background-fetch
12-21 15:37:20.427 32411 533 I ReactNativeJS: 'on Event taskId: ', 'react-native-background-fetch'
12-21 15:38:20.426 32411 32411 D TSBackgroundFetch: [BGTask] timeout: react-native-background-fetch
12-21 15:38:20.432 32411 533 I ReactNativeJS: '[Fetch] TIMEOUT taskId:', 'react-native-background-fetch'
12-21 15:38:20.447 32411 534 D TSBackgroundFetch: - finish: react-native-background-fetch
12-21 15:38:20.447 32411 534 D TSBackgroundFetch: - jobFinished
12-21 15:38:44.333 32411 32411 D TSBackgroundFetch: - Background Fetch event received: react-native-background-fetch
12-21 15:38:44.337 32411 533 I ReactNativeJS: 'on Event taskId: ', 'react-native-background-fetch'
12-21 15:39:44.333 32411 32411 D TSBackgroundFetch: [BGTask] timeout: react-native-background-fetch
12-21 15:39:44.343 32411 533 I ReactNativeJS: '[Fetch] TIMEOUT taskId:', 'react-native-background-fetch'
12-21 15:39:44.351 32411 534 D TSBackgroundFetch: - finish: react-native-background-fetch
12-21 15:39:44.351 32411 534 D TSBackgroundFetch: - jobFinished
12-21 15:40:19.334 32411 32411 D TSBackgroundFetch: - Background Fetch event received: react-native-background-fetch
12-21 15:40:19.336 32411 533 I ReactNativeJS: 'on Event taskId: ', 'react-native-background-fetch'
12-21 15:40:36.391 32411 32411 D TSBackgroundFetch: ☯️ onPause
12-21 15:40:36.391 32411 32411 D TSBackgroundFetch: ☯️ onStop
12-21 15:41:11.614 2352 2666 W ReactNativeJS: ViewPropTypes will be removed from React Native. Migrate to ViewPropTypes exported from 'deprecated-react-native-prop-types'.
12-21 15:41:11.698 2352 2666 W ReactNativeJS: new NativeEventEmitter() was called with a non-null argument without the required addListener method.

Also I tried using this command - adb shell cmd jobscheduler run -f com.backgroundfetch 999
Running job [FORCED] -- this got only logged , I didn't understood what does it means ?

Could you please check and let me know where I went wrong.

Thanks

Why are you not calling BackgroundFetch.finish(taskId) in your fetch-callback?

Review the example in the README.

// BackgroundFetch event handler.
    const onEvent = async (taskId) => {
      console.log('[BackgroundFetch] task: ', taskId);
      // Do your background work...
      
      // IMPORTANT:  You must signal to the OS that your task is complete.
      BackgroundFetch.finish(taskId);  // <--------------------------------- YOU MUST CALL .finish(taskId)
    }

    // Timeout callback is executed when your Task has exceeded its allowed running-time.
    // You must stop what you're doing immediately BackgroundFetch.finish(taskId)
    const onTimeout = async (taskId) => {
      console.warn('[BackgroundFetch] TIMEOUT task: ', taskId);
      BackgroundFetch.finish(taskId);
    }

    // Initialize BackgroundFetch only once when component mounts.
    let status = await BackgroundFetch.configure({minimumFetchInterval: 15}, onEvent, onTimeout);

ok thanks for your response , let me check.

Hi @christocracy , I added BackgroundFetch.finish(taskId);, onEvent and checked the logs again after finishing the task nothing happened.

Screenshot 2023-12-21 at 9 50 30 PM

Don't post screenshots of logs. Post text.

BackgroundFetch % adb logcat *:S ReactNative:V ReactNativeJS:V TSBackgroundFetch:V
--------- beginning of main
12-21 20:49:29.472 20298 20675 D TSBackgroundFetch: [RNBackgroundFetch initialize]
12-21 20:49:29.474 20298 20298 D TSBackgroundFetch: ☯️ onCreate
12-21 20:49:29.475 20298 20298 D TSBackgroundFetch: ☯️ onStart
12-21 20:49:29.476 20298 20298 D TSBackgroundFetch: ☯️ onResume
12-21 20:49:29.962 20298 20676 I ReactNativeJS: Running "BackgroundFetch" with {"rootTag":11}
12-21 20:49:30.342 20298 20677 D TSBackgroundFetch: - configure
12-21 20:49:30.342 20298 20677 D TSBackgroundFetch: - start
12-21 20:49:30.347 20298 20677 D TSBackgroundFetch: - registerTask: react-native-background-fetch (jobId: 999)
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: {
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: "taskId": "react-native-background-fetch",
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: "isFetchTask": true,
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: "minimumFetchInterval": 15,
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: "stopOnTerminate": false,
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: "requiredNetworkType": 0,
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: "requiresBatteryNotLow": false,
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: "requiresCharging": false,
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: "requiresDeviceIdle": false,
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: "requiresStorageNotLow": false,
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: "startOnBoot": true,
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: "jobService": "com.transistorsoft.rnbackgroundfetch.HeadlessTask",
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: "forceAlarmManager": false,
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: "periodic": true,
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: "delay": -1
12-21 20:49:30.348 20298 20677 D TSBackgroundFetch: }
12-21 20:49:30.388 20298 20676 I ReactNativeJS: 'Background fetch status', 2
12-21 20:50:03.604 20298 20298 D TSBackgroundFetch: - Background Fetch event received: react-native-background-fetch
12-21 20:50:03.610 20298 20676 I ReactNativeJS: 'on Event taskId: ', 'react-native-background-fetch'
12-21 20:50:03.615 20298 20677 D TSBackgroundFetch: - finish: react-native-background-fetch
12-21 20:50:03.615 20298 20677 D TSBackgroundFetch: - jobFinished

Do you know what this means?


ReactNativeJS: 'on Event taskId: ', 'react-native-background-fetch'
12-21 20:50:03.615 20298 20677 D TSBackgroundFetch: - finish: react-native-background-fetch
12-21 20:50:03.615 20298 20677 D TSBackgroundFetch: - jobFinished

yes , it called the event for the first time, but after that it should be called after every 15 mins right ?

15 min is not a guarantee. Let it run for 24 hours.

15 min no es garantía. Déjalo funcionar durante 24 horas.

It is important that the cell phone is being used, or it is enough to leave it locked all the time and the task will be executed whenever it can.

Taking into account that we already know that simulated is running perfectly
@christocracy ?

or it is enough to leave it locked all the time and the task will be executed whenever it can.

Yes

This issue is stale because it has been open for 30 days with no activity.

This issue was closed because it has been inactive for 14 days since being marked as stale.