我创建了一个服务,该服务将使用React Native Headless JS
每秒钟运行一次。但是每当我打电话给java module @reactMethod
时,都会收到错误消息Invalid hook call
。
请帮助我知道我要怎么做。我想要即使在后台也能像setInterval
一样工作的服务。
TestTimerPackage.java
public class TestTimerPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(
new TestTimerModule(reactContext)
);
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
TestTimerModule.java
public class TestTimerModule extends ReactContextBaseJavaModule {
public static final String REACT_CLASS = "TestTimer";
private static ReactApplicationContext reactContext;
public TestTimerModule(@Nonnull ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
}
@Nonnull
@Override
public String getName() {
return REACT_CLASS;
}
@ReactMethod
public void startService() {
this.reactContext.startService(new Intent(this.reactContext, TestTimerService.class));
}
@ReactMethod
public void stopService() {
this.reactContext.stopService(new Intent(this.reactContext, TestTimerService.class));
}
}
TestTimerService
public class TestTimerService extends Service {
private static final int SERVICE_NOTIFICATION_ID = 12345;
private static final String CHANNEL_ID = "TEST_TIMER";
private Handler handler = new Handler();
private Runnable runnableCode = new Runnable() {
@Override
public void run() {
Context context = getApplicationContext();
Intent myIntent = new Intent(context, TestTimerEventService.class);
context.startService(myIntent);
HeadlessJsTaskService.acquireWakeLockNow(context);
handler.postDelayed(this, 1000);
}
};
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
this.handler.removeCallbacks(this.runnableCode);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.handler.post(this.runnableCode);
return super.onStartCommand(intent, flags, startId);
}
}
TestTimerEventService.js
public class TestTimerEventService extends HeadlessJsTaskService {
@Nullable
protected HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
return new HeadlessJsTaskConfig(
"TestTimer",
extras != null ? Arguments.fromBundle(extras) : Arguments.createMap(),
5000,
true);
}
}
我在AppRegistry上注册了无头服务
AppRegistry.registerHeadlessTask('TestTimer', () => TestCountDown);
完成桥梁
import { NativeModules } from 'react-native';
const { TestTimer } = NativeModules;
export default TestTimer;
当我在TestTimer.startService()
中呼叫child hook
时遇到错误Invalid hook call
。
但是每当我在TestTime.startService()
中调用Parent hook
时,都会收到错误消息TypeError: taskProvider(...) is not a function
请帮助我解决此错误