gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:02:45 27 4
gpt4 key购买 nike

如何在 MainApplication 中获取和注入(inject) Activity ?我有一个外部库,需要我将 Activity 作为参数传递。这answer建议我在需要当前 Activity 的部分使用 getCurrentActivity() 方法,但它已从 ReactContextBaseJavaModule 类中删除。还有其他方法吗?如何传递在以下代码中使用“this”关键字的 Activity ?谢谢..

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;
}
}

最佳答案

我不喜欢 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); 并等待创建 Activity 以获取当前引用。

关于android - 如何在扩展 Application 或 ReactContextBaseJavaModule 的类中获取 Activity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41926265/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com