I'm using expo-background-fetch
to schedule a Background Fetch task. In that task I want to request geolocation, make an HTTP call to my server to retreive some data, and I also want to send a notification.
The problem is that the geolocation request, fetch, and notification schedule functions are async. When I use .then or call an async function, the main task function has already returned, so Android cuts off the Wi-Fi connection before the fetch happens. (This does not happen on Mobile Data, and therefore the Background Fetch task completes fully. The fetch fails on iOS too, but it might not be because of this, I don't know about that yet.)
Example code:
import * as TaskManager from 'expo-task-manager';import * as BackgroundFetch from 'expo-background-fetch';import * as Location from 'expo-location';import * as Notifications from 'expo-notifications';const BG_TASK_NAME = "me.mogery.dummybgf"export async function init() { TaskManager.defineTask(BG_TASK_NAME, function backgroundFetch() { console.log("[BGF] Called."); (async function() { var location = await Location.getCurrentPositionAsync({ accuracy: Location.LocationAccuracy.Balanced }); console.log("[BGF] User location:", location); var poll = await (await fetch("https://myapihere")).json(); console.log("[BGF] Poll complete."); if (poll.notify) { var res = await Notifications.scheduleNotificationAsync({ content: { title: "Test notification", body: "Yay!" }, trigger: null }); console.log("[BGF] Scheduled notification.",res); } })(); return BackgroundFetch.Result.NewData; }); await BackgroundFetch.registerTaskAsync(BG_TASK_NAME, { minimumInterval: 15*60, stopOnTerminate: false, startOnBoot: false }); var status = await BackgroundFetch.getStatusAsync(); console.log("[BGF] Status", status);}
I've tried using a while loop to wait for async before returning, but that ended up just freezing the event loop. I've also tried to use Atomics.wait
, but it was not available on Android.