React Native ReactContext生命周期停留在BEFORE_CREATE上

问题描述 投票:2回答:1

我正在尝试在React-Native中运行后台服务。据我所知,我需要用本机Java编写它并将其连接到react-native代码。当我尝试发出一个事件时,我收到一个错误:

Tried to access a JS module before the React instance was fully set up. Calls to should only happen once initialize() has been called on your native module.

所以我添加了一个检查以查看模块是否正在运行:

if (reactContext.getLifecycleState() == LifecycleState.RESUMED)

但它总是返回错误。生命周期停留在BEFORE_CREATE上。我该如何发布我的活动。

服务:

public class TestService extends Service {

double distance = 0.0;
ReactContext reactContext;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    reactContext = new ReactContext(getApplicationContext());
    new Timer().scheduleAtFixedRate(new TimerTask(){
        @Override
        public void run(){
            WritableMap params = Arguments.createMap();
            distance+= 0.7;
            Log.d("LOG", "Trying to send distance: "+distance+" on lifecycle: "+reactContext.getLifecycleState());
            params.putDouble("distance", distance);
            sendEvent(reactContext, "updateDistance", params);
        }
    },0,1000);
    return START_STICKY;
}

private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
    if (reactContext.getLifecycleState() == LifecycleState.RESUMED) {
        reactContext.getJSModule(DeviceEventManagerModule
                .RCTDeviceEventEmitter.class)
                .emit(eventName, params);
        Log.d("LOG", "Sent distance: "+distance);
    }
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
}

模块:

public class ServiceModule extends ReactContextBaseJavaModule {
ReactContext reactContext;

public ServiceModule(ReactApplicationContext reactContext) {
    super(reactContext);
    this.reactContext = reactContext;
    this.initialize();
}

@ReactMethod
public void startTrackingService() {
    Intent intent = new Intent(reactContext, TestService.class);
    reactContext.startService(intent);
}

@Override
public String getName() {
    return "ServiceModule";
}
}

包:

public class ServicePackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    List<NativeModule> modules = new ArrayList<>();
    modules.add(new ServiceModule(reactContext));
    return modules;
}

@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
    return Collections.emptyList();
}

@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Collections.emptyList();
}
}

我申请:

@Override
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
      new MainReactPackage(),
      new ReactNativePushNotificationPackage(),
      new ServicePackage()
  );
}
java android react-native
1个回答
3
投票

我解决了它:)在服务中我从基础上下文创建一个新的上下文,它不是同一个对象。解决方法是从服务广播数据,然后发送它们做javascript。

ServiceModule:

public class ServiceModule extends ReactContextBaseJavaModule {
public static String UPDATE = "updateDistance";
public static String DISTANCE = "distance";

private IntentFilter intentFilter;
private BroadcastReceiver receiver;

public ServiceModule(ReactApplicationContext reactContext) {
    super(reactContext);
    initializeBroadcastReceiver();
}

@ReactMethod
public void startTrackingService() {
    Intent intent = new Intent(getReactApplicationContext(), TestService.class);
    getReactApplicationContext().startService(intent);
}

@ReactMethod
public void stopTrackingService() {
    Intent intent = new Intent(getReactApplicationContext(), TestService.class);
    getReactApplicationContext().stopService(intent);
}

private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
    if (reactContext.hasActiveCatalystInstance()) {
        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
    }
}

private void initializeBroadcastReceiver() {
    intentFilter = new IntentFilter();
    intentFilter.addAction(UPDATE);
    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            WritableMap params = Arguments.createMap();
            params.putDouble(DISTANCE, intent.getDoubleExtra(DISTANCE, 0));
            sendEvent(getReactApplicationContext(), UPDATE, params);
        }
    };
    getReactApplicationContext().registerReceiver(receiver, intentFilter);
}

@Override
public String getName() {
    return "ServiceModule";
}
}

测试服务:

public class TestService extends Service {

double distance = 0.0;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    new Timer().scheduleAtFixedRate(new TimerTask(){
        @Override
        public void run(){
            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction(ServiceModule.UPDATE);
            broadcastIntent.putExtra(ServiceModule.DISTANCE, distance);
            sendBroadcast(broadcastIntent);
            distance+= 0.7;
        }
    },0,1000);
    return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
}
© www.soinside.com 2019 - 2024. All rights reserved.