我正在使用Android WorkManager创建一个React Native后台同步任务。WorkManager类中的doWork方法被正确地定期调用。我面临的问题是如何从doWork方法中调用React Native函数。
在我目前的实现中,JavaScript函数没有被调用。
React Native中的无头任务
// index.js
AppRegistry.registerHeadlessTask('SyncHeadlessTask', () => SyncHeadlessTask);
// SyncHeadlessTask.js
module.exports = async (taskData) => {
console.log('task running');
};
我的Java无界面任务
public class SyncHeadlessTaskService extends HeadlessJsTaskService {
@Override
protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
return new HeadlessJsTaskConfig(
"SyncHeadlessTask",
Arguments.fromBundle(extras),
10000, // timeout for the task
true // optional: defines whether or not the task is allowed in foreground. Default is false
);
}
return null;
}
}
我的工作者
public class SyncWorker extends Worker {
private static final String TAG = "SyncWorker";
public SyncWorker(@Nonnull Context context, @Nonnull WorkerParameters workerParams) {
super(context, workerParams);
}
@Nonnull
@Override
public Result doWork() {
return Result.success();
}
}
我的模块
public class SyncModule extends ReactContextBaseJavaModule {
private static final String MODULE_NAME = "SyncManager";
private Context mContext;
private PeriodicWorkRequest workRequest;
private static final String TAG = "SyncModule";
SyncModule(@Nonnull ReactApplicationContext reactContext) {
super(reactContext);
mContext = reactContext;
workRequest = new PeriodicWorkRequest.Builder(SyncWorker.class, 15, TimeUnit.MINUTES).build();
}
@ReactMethod
public void startSync() {
WorkManager.getInstance().enqueueUniquePeriodicWork("SyncWork", ExistingPeriodicWorkPolicy.KEEP, workRequest);
}
@ReactMethod
public void stopSync() {
WorkManager.getInstance().cancelUniqueWork("SyncWork");
}
@Nonnull
@Override
public String getName() {
return MODULE_NAME;
}
}
我的套餐
public class SyncPackage implements ReactPackage {
@Nonnull
@Override
public List<NativeModule> createNativeModules(@Nonnull ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new SyncModule(reactContext));
return modules;
}
@Nonnull
@Override
public List<ViewManager> createViewManagers(@Nonnull ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}