如何在扩展Application或ReactContextBaseJavaModule的类中获取Activity?

时间:2017-01-29 21:39:39

标签: android react-native react-native-android

如何在MainApplication中获取并注入活动?我有一个外部库,要求我将活动作为参数传递。这个answer建议我在需要当前活动的部分中使用getCurrentActivity()方法,但它已从ReactContextBaseJavaModule类中删除。有没有其他方法可以做到这一点?如何在下面的代码中传递使用'this'关键字的活动?感谢..

package com.bluetoothioexample;

import android.app.Application;
import android.util.Log;

import com.facebook.react.bridge.ReactContextBaseJavaModule;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;

import java.util.Arrays;
import java.util.List;

import com.subsite.bluetoothio.BluetoothIOPackage;
import com.oblador.vectoricons.VectorIconsPackage;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    protected boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new BluetoothIOPackage(this), //<- How pass the activity
                                        // from ReactApplication ?
          new VectorIconsPackage()
      );
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
      return mReactNativeHost;
  }
}

1 个答案:

答案 0 :(得分:3)

我没有进入React-Native,但有一个简单的技巧

 public class MainApplication extends Application implements Application.ActivityLifecycleCallbacks{


    @Override
    public void onCreate() {
        super.onCreate();
        registerActivityLifecycleCallbacks(this);
    }


    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
        @Override
        protected boolean getUseDeveloperSupport() {
            return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
            return Arrays.<ReactPackage>asList(
                    new MainReactPackage(),
                    new BluetoothIOPackage(mCurrentActivity), //
                    // from ReactApplication ?
                    new VectorIconsPackage()
            );
        }
    };
    private Activity mCurrentActivity;

    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        mCurrentActivity = activity;
    }

您需要实现Application.ActivityLifecycleCallbacks并注册生命周期回调registerActivityLifecycleCallbacks(this);并等待创建活动以获取当前引用。