javascript - 在android上关闭应用程序时反应本机运行作业
问题描述
尝试了 react-native-background-fetch 和 react-native-background-job 两个库在应用程序关闭时都没有运行代码,清楚地遵循了文档
react-native-background-fetch 作业在使用当应用程序处于前台时创建自定义事件时运行 adb shell cmd jobscheduler run -f com.bg_fetch 999 ,15 分钟后也不会触发周期性事件(如配置中给出的)
对于 react-native-background-job 作业即使在后台也不会运行
在 android-9 上测试
componentDidMount() {
// Configure it.
BackgroundFetch.configure({
minimumFetchInterval: 15, // <-- minutes (15 is minimum allowed)
// Android options
stopOnTerminate: false,
startOnBoot: true,
requiredNetworkType: BackgroundFetch.NETWORK_TYPE_ANY, // Default
requiresCharging: false, // Default
requiresDeviceIdle: false, // Default
requiresBatteryNotLow: false, // Default
requiresStorageNotLow: false, // Default
enableHeadless:true,
}, async() => {
console.log('[BackgroundFetch HeadlessTask] start');
let response = await fetch('http://431c21b5.ngrok.io/');
let responseJson = await response.json();
console.log('[BackgroundFetch HeadlessTask] response: ', responseJson);
BackgroundFetch.finish(BackgroundFetch.FETCH_RESULT_NEW_DATA);
}, (error) => {
console.log("[js] RNBackgroundFetch failed to start");
});
// Optional: Query the authorization status.
BackgroundFetch.status((status) => {
switch(status) {
case BackgroundFetch.STATUS_RESTRICTED:
console.log("BackgroundFetch restricted");
break;
case BackgroundFetch.STATUS_DENIED:
console.log("BackgroundFetch denied");
break;
case BackgroundFetch.STATUS_AVAILABLE:
console.log("BackgroundFetch is enabled");
break;
}
});
}
作业应该在应用程序处于后台或关闭时运行,无头作业在我关闭应用程序后被杀死,
解决方案
你需要在你的 index.js 文件中放入你的 headlessTask
https://github.com/transistorsoft/react-native-background-fetch#config-boolean-enableheadless-false