Skip to content
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

BackgroundFetch.registerHeadlessTask Issues #454

Closed
s1tony opened this issue Jun 23, 2023 · 29 comments
Closed

BackgroundFetch.registerHeadlessTask Issues #454

s1tony opened this issue Jun 23, 2023 · 29 comments
Labels

Comments

@s1tony
Copy link

s1tony commented Jun 23, 2023

For my React Native Application, I am attempting to use the BackgroundFetch.registerHeadlessTask capability. I setup my code per the example, and while the callback for BackgroundFetch.configure fires during my testing, the Headless Task never does.

Your Environment

  • Plugin version: Latest (re-installed an hour ago)
  • Android
  • OS version: 13
  • Device manufacturer / model: Samsung S22+
  • React Native version (react-native -v): 0.71.3
  • Plugin config

Expected Behavior

When my application is in the background or terminated, the method passed to BackgroundFetch.registerHeadlessTask should run.

Actual Behavior

When my application is in the background or terminated, the method passed to BackgroundFetch.registerHeadlessTask never fires.

Steps to Reproduce

  1. Add code to configure BackgroundFetch and then Register Headless task
  2. Start app via Metro
  3. Put app in background
  4. Wait 20 or more minutes

App.tsx (snippet)

`const initBackgroundFetch = async () => {
const status: number = await BackgroundFetch.configure({
minimumFetchInterval: 15, // <-- minutes (15 is minimum allowed)
stopOnTerminate: false,
enableHeadless: true,
//startOnBoot: true,
// Android options
forceAlarmManager: false, // <-- Set true to bypass JobScheduler.
requiredNetworkType: BackgroundFetch.NETWORK_TYPE_NONE, // Default
requiresCharging: false, // Default
requiresDeviceIdle: false, // Default
requiresBatteryNotLow: false, // Default
requiresStorageNotLow: false, // Default
}, async (taskId:string) => {
console.log('[BackgroundFetch] taskId', taskId);
BackgroundFetch.finish(taskId);
}, (taskId:string) => {
// Oh No! Our task took too long to complete and the OS has signalled
// that this task must be finished immediately.
console.log('[Fetch] TIMEOUT taskId:', taskId);
BackgroundFetch.finish(taskId);
})};

const App = () => {
const appId = RealmInfo.appId;
const realmApp = createRealmApp(appId);
Realm.App.Sync.setLogLevel(realmApp, 'error');
Realm.App.Sync.setLogger(realmApp, console.log);

useEffect(() => {
initBackgroundFetch();

const unsubscribe = notifee.onForegroundEvent(({ type, detail }) => {
  switch (type) {
    case EventType.DISMISSED:
      console.log('User dismissed notification', detail.notification);

      break;
    case EventType.PRESS:
      console.log('User pressed notification', detail.notification);

      break;
  }
});

return () => {
  unsubscribe();
};

}, []);`

index.js (snippet)

`messaging().setBackgroundMessageHandler(onMessageReceived);
AppRegistry.registerComponent(appName, () => App);

const onCheckForExpiredLists = async (event) => {
const taskId = event.taskId;
const isTimeout = event.timeout;

if (isTimeout) {
console.log('[BackgroundFetch] Headless TIMEOUT:', taskId);
BackgroundFetch.finish(taskId);
return;
}

console.log('[BackgroundFetch HeadlessTask] start: ', taskId);
BackgroundFetch.finish(taskId);
};`

BackgroundFetch.registerHeadlessTask(onCheckForExpiredLists);

Context

I am attempting to have a notification (notifee) be displayed once a day, depending on condition

Debug logs

  • 06-23 15:36:21.176 2442 2442 D TSBackgroundFetch: - Background Fetch event received: react-native-background-fetch
    06-23 15:36:21.178 2442 2442 D TSBackgroundFetch: ☯ onCreate
    06-23 15:36:21.178 2442 2442 D TSBackgroundFetch: ☯️ onStart
    06-23 15:36:21.178 2442 2442 D TSBackgroundFetch: ☯️ onResume
    06-23 15:36:24.967 2442 2442 D TSBackgroundFetch: ☯️ onPause
    06-23 15:36:24.968 2442 2442 D TSBackgroundFetch: ☯️ onStop
    06-23 15:37:11.955 5492 5492 D TSBackgroundFetch: ☯️ onCreate
    06-23 15:37:11.956 5492 5492 D TSBackgroundFetch: ☯️ onStart
    06-23 15:37:11.956 5492 5492 D TSBackgroundFetch: ☯️ onResume
    06-23 15:37:11.956 5492 5597 D TSBackgroundFetch: - configure
    06-23 15:37:11.956 5492 5597 D TSBackgroundFetch: - start
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: - registerTask: react-native-background-fetch (jobId: 999)
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: {
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: "taskId": "react-native-background-fetch",
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: "isFetchTask": true,
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: "minimumFetchInterval": 15,
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: "stopOnTerminate": false,
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: "requiredNetworkType": 0,
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: "requiresBatteryNotLow": false,
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: "requiresCharging": false,
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: "requiresDeviceIdle": false,
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: "requiresStorageNotLow": false,
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: "startOnBoot": false,
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: "jobService": "com.transistorsoft.rnbackgroundfetch.HeadlessTask",
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: "forceAlarmManager": false,
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: "periodic": true,
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: "delay": -1
    06-23 15:37:11.961 5492 5597 D TSBackgroundFetch: }
    06-23 15:37:19.431 5492 5492 D TSBackgroundFetch: ☯️ onPause
    06-23 15:37:19.432 5492 5492 D TSBackgroundFetch: ☯️ onStop
    06-23 15:39:01.638 5492 5492 D TSBackgroundFetch: ☯️ onStart
    06-23 15:39:01.650 5492 5492 D TSBackgroundFetch: ☯️ onResume
    06-23 15:39:51.911 5492 5492 D TSBackgroundFetch: ☯️ onPause
    06-23 15:39:51.911 5492 5492 D TSBackgroundFetch: ☯️ onStop
    06-23 15:55:41.006 5492 5492 D TSBackgroundFetch: ☯️ onStart
    06-23 15:55:41.028 5492 5492 D TSBackgroundFetch: ☯️ onResume
    06-23 15:55:41.131 5492 5492 D TSBackgroundFetch: - Background Fetch event received: react-native-background-fetch
    06-23 15:55:41.243 5492 5597 D TSBackgroundFetch: - finish: react-native-background-fetch
    06-23 15:55:41.243 5492 5597 D TSBackgroundFetch: - jobFinished
    06-23 15:55:44.408 5492 5492 D TSBackgroundFetch: ☯️ onPause
    06-23 15:55:44.408 5492 5492 D TSBackgroundFetch: ☯️ onStop
@christocracy
Copy link
Member

"headless" = terminated.

@christocracy
Copy link
Member

Your logs do not show your app operating in the "headless" (terminated) state.

@s1tony
Copy link
Author

s1tony commented Jun 23, 2023

OK, thank you - I will adjust and test some more.

@s1tony
Copy link
Author

s1tony commented Jun 24, 2023 via email

@christocracy
Copy link
Member

If I asked you to terminate the Twitter app (for example), what would you do?

@s1tony
Copy link
Author

s1tony commented Jun 25, 2023 via email

@christocracy
Copy link
Member

Are you simulating events?

@yedi97
Copy link

yedi97 commented Jun 28, 2023

@christocracy Hi chris, please tell me, on IOS platform when I close the app, when I reopen the app, will the background task event be fired again? Or do I have to start over?

@christocracy
Copy link
Member

will the background task event be fired

what background task event are you referring?

@yedi97
Copy link

yedi97 commented Jun 28, 2023

what background task event are you referring?

i'm creating a schedule task with name com.transistorsoft.fetchNewData, run every 4 hours, it works fine on IOS if the user doesn't close the app, but I wonder when the user closes the app and reopens it Will my task com.transistorsoft.fetchNewData be reactivated automatically?

@christocracy
Copy link
Member

I really don’t know if you have to reschedule it.

why don’t you terminate then try simulating the task to see if it runs?

@yedi97
Copy link

yedi97 commented Jun 28, 2023

I really don’t know if you have to reschedule it.

why don’t you terminate then try simulating the task to see if it runs?

yes, thank you, i just want to check if it has such a mechanism, i will check it myself

@AdnanAshraf-gol
Copy link

AdnanAshraf-gol commented Oct 2, 2023

@christocracy is there any example for headless task ? or can i get some help ?

am calling the BackgroundFetch.start() on a specific notification
here is my index.js


import "react-native-gesture-handler";
import React from 'react';
import ReduxThunk from 'redux-thunk'
import { createStore, applyMiddleware } from 'redux';
import reducers from './src/reducers';
import { Provider } from 'react-redux'
import App from './App';
import { AppRegistry, LogBox, } from "react-native";
import { name as appName } from './app.json';
const store = createStore(reducers, {}, applyMiddleware(ReduxThunk))
LogBox.ignoreLogs(['Warning: ...']);
LogBox.ignoreAllLogs();
import BackgroundFetch from 'react-native-background-fetch';

import axios from "axios";
let MyHeadlessTask = async (event) => {
    // Get task id from event {}:
    let taskId = event.taskId;
    let isTimeout = event.timeout;  // <-- true when your background-time has expired.
    if (isTimeout) {
        // This task has exceeded its allowed running-time.
        // You must stop what you're doing immediately finish(taskId)
        console.log('[BackgroundFetch] Headless TIMEOUT:', taskId);
        BackgroundFetch.finish(taskId);
        return;
    }
    console.log('[BackgroundFetch HeadlessTask] start: ', taskId);
    // Perform an example HTTP request.
    // Important:  await asychronous tasks when using HeadlessJS.
    let response = await fetch('https://reactnative.dev/movies.json');
    let responseJson = await response.json();
    console.log('[BackgroundFetch HeadlessTask] response: ', responseJson);

    // Required:  Signal to native code that your task is complete.
    // If you don't do this, your app could be terminated and/or assigned
    // battery-blame for consuming too much time in background.
    BackgroundFetch.finish(taskId);
}
// Configure background fetch
BackgroundFetch.configure(
    {
        enableHeadless: true,
        forceAlarmManager: true,
        requiredNetworkType: BackgroundFetch.NETWORK_TYPE_ANY,
        // minimumFetchInterval: 15, // Minimum interval in minutes
        stopOnTerminate: true,   // Keep running in the background
    },
    async (taskId) => {
        console.log('taskId Background fetch executed', taskId)
        // Perform background tasks her
        console.log('Background fetch executed start');
        const data = await axios.get("https://random-data-api.com/api/v2/users");
        console.log('data Background fetch executed', data)
        BackgroundFetch.finish(BackgroundFetch.FETCH_RESULT_NEW_DATA);
        console.log('Background fetch executed end');

    },
    (error) => {
        console.log('[js] Background fetch failed to start', error);
    }
);
BackgroundFetch.registerHeadlessTask(MyHeadlessTask);
const Root = () => (
    <Provider store={store}>
        <App />
    </Provider>
)
AppRegistry.registerComponent(appName, () => Root)

@christocracy
Copy link
Member

@AdnanAshraf-gol
Copy link

AdnanAshraf-gol commented Oct 2, 2023

Learn to Syntax Highlight Multiline Code-blocks

my bad ! i have updated the comment

@christocracy
Copy link
Member

BackgroundFetch.configure must not be placed into index.js. It must be place WITHIN your App code.

@AdnanAshraf-gol
Copy link

i have moved the BackgroundFetch.configure to live cycle method of one of my component and restarted the project .
still nothing ... it doesnt even console anything related to BackgroundFetch in logcat.

@christocracy
Copy link
Member

christocracy commented Oct 2, 2023

Are you simulating events? See the readme to learn how.

Are you observing $ adb logcat?

@AdnanAshraf-gol
Copy link

yes i observing the $ adb logcat ... but i dont see any logs there related to BackgroundFetch.

@christocracy
Copy link
Member

Are you simulating events?

@AdnanAshraf-gol
Copy link

Screenshot 2023-10-03 at 10 01 31 AM

This?

@christocracy
Copy link
Member

"This" what?

I asked you "are you simulating tasks?".

Or just sitting there at your desk wasting time under an umbrella waiting for it to rain?

@AdnanAshraf-gol
Copy link

AdnanAshraf-gol commented Oct 3, 2023

i dont know what do you mean by "simulating tasks" . But i am following the steps mentioned here and the above screenshot is from the adb logcat *:S ReactNative:V ReactNativeJS:V TSBackgroundFetch:V

@christocracy
Copy link
Member

Go read the readme and learn how to simulate events..

You don't test this plug-in by staring quietly at your logs waiting for something to happen.

@christocracy
Copy link
Member

Read api docs enableHeadless

@AdnanAshraf-gol
Copy link

AdnanAshraf-gol commented Oct 3, 2023

i have enabled enableHeadless to true

BackgroundFetch.configure({
      stopOnTerminate: false,
      enableHeadless: true,
      startOnBoot: true,
      // Android options
      forceAlarmManager: false,      // <-- Set true to bypass JobScheduler.
      requiredNetworkType: BackgroundFetch.NETWORK_TYPE_ANY, // Default
      requiresCharging: false,       // Default
      requiresDeviceIdle: false,     // Default
      requiresBatteryNotLow: false,  // Default
      requiresStorageNotLow: false,
    }, async (taskId: string) => {
      console.log('[BackgroundFetch] taskId', taskId);
      MyHeadlessTask(taskId)
      BackgroundFetch.finish(taskId);
    }, (taskId: string) => {
      console.log('[Fetch] TIMEOUT taskId:', taskId);
      BackgroundFetch.finish(taskId);
    });

but now am getting this error registerTask failed to find BackgroundFetchConfig for taskId react-native-background-fetch
Screenshot 2023-10-03 at 4 57 52 PM

@christocracy
Copy link
Member

christocracy commented Oct 3, 2023

Yea, fine, and did you Read the api docs about it?! There's far more involved than just setting it true.

Copy link

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

@github-actions github-actions bot added the stale label Apr 17, 2024
Copy link

github-actions bot commented May 1, 2024

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

@github-actions github-actions bot closed this as completed May 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants