如何在react原生android中使用活动结果API?

yhived7q  于 2023-01-18  发布在  React
关注(0)|答案(1)|浏览(136)

我正在尝试为react native创建android native module,并且正在使用Activity Results API启动另一个活动,但找不到registerForActivityResult,即使我在Gradle中列出了这两个依赖项:

implementation "androidx.activity:activity:1.2.0"
implementation "androidx.fragment:fragment:1.3.0"

这是我努力实现的目标:

ActivityResultLauncher<String> mGetContent = registerForActivityResult(new GetContent(),
    new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri uri) {
            // Handle the returned Uri
        }
    }
);
p4rjhz4m

p4rjhz4m1#

我知道我来晚了一点,但我也有同样的问题,我想我应该分享我是如何解决这个问题的,希望它能帮助其他人。
首先,我创建了一个新接口(在它自己的文件中),以便在MainActivity和React Native模块之间建立一个契约:

public interface OnActivityResultImplementation<S, T> {
    S execute(T a);
}

在我的主要活动中,我有以下内容:

public class MainActivity extends ReactActivity {
protected OnActivityResultImplementation onActivityResultImplementation = null;
protected ActivityResultLauncher<Intent> mStartForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
        result -> {
            onActivityResultImplementation.execute(result);
        });
   ...
}

然后在React原生模块中,我将其设置为:

public class RCTPushProvisioningModule extends ReactContextBaseJavaModule {

@ReactMethod
public void callNativeApiMethod(final Promise promise) {
    MainActivity activity = (MainActivity) this.getReactApplicationContext().getCurrentActivity();
    activity.onActivityResultImplementation = result -> {
        ActivityResult activityResult = (ActivityResult) result;
        switch (activityResult.getResultCode()) {
            case Activity.RESULT_OK:
                promise.resolve(OK);
                break;
            case Activity.RESULT_CANCELED:
                promise.resolve(CANCELED);
                break;
            default:
                promise.reject(ERROR_CODE, "FAILED");
                break;
        }
        return null;
    };

    // Use the ActivityResultLauncher<Intent> from MainActivity to wire the whole thing up.
    fictiveNativeApi.callMethodThatRequiresActivityResultLauncher(activity.mStartForResult);
  }
}

相关问题