从startActivityForResult中获取结果
下面我们写一个简单的图片选择器来实践一下。这个图片选择器会把pickImage方法暴露给 JavaScript,而这个方法在调用时就会把图片的路径返回到 JS 端。
public class ImagePickerModule extends ReactContextBaseJavaModule{
private static final int IMAGE_PICKER_REQUEST = 467081;
private static final String E_ACTIVITY_DOES_NOT_EXIST = "E_ACTIVITY_DOES_NOT_EXIST";
private static final String E_PICKER_CANCELLED = "E_PICKER_CANCELLED";
private static final String E_FAILED_TO_SHOW_PICKER = "E_FAILED_TO_SHOW_PICKER";
private static final String E_NO_IMAGE_DATA_FOUND = "E_NO_IMAGE_DATA_FOUND";
private Promise mPickerPromise;
private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() {
@Override publicvoidonActivityResult(Activity activity,intrequestCode,intresultCode, Intent intent){
if (requestCode == IMAGE_PICKER_REQUEST) {
if (mPickerPromise != null) {
if (resultCode == Activity.RESULT_CANCELED) {
mPickerPromise.reject(E_PICKER_CANCELLED, "Image picker was cancelled");
} else if (resultCode == Activity.RESULT_OK) {
Uri uri = intent.getData();
if (uri == null) {
mPickerPromise.reject(E_NO_IMAGE_DATA_FOUND, "No image data found");
} else {
mPickerPromise.resolve(uri.toString());
}
}
mPickerPromise = null;
}
}
}
};
publicImagePickerModule(ReactApplicationContext reactContext){
super(reactContext);
// Add the listener for `onActivityResult` reactContext.addActivityEventListener(mActivityEventListener);
}
@Override publicStringgetName(){
return "ImagePickerModule";
}
@ReactMethod publicvoidpickImage(finalPromise promise){
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");
return;
}
// Store the promise to resolve/reject when picker returns data mPickerPromise = promise;
try {
final Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Pick an image");
currentActivity.startActivityForResult(chooserIntent, IMAGE_PICKER_REQUEST);
} catch (Exception e) {
mPickerPromise.reject(E_FAILED_TO_SHOW_PICKER, e);
mPickerPromise = null;
}
}
}
但是这样是不够的,需要复写activity中的
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
mReactInstanceManager.onActivityResult(this, requestCode, resultCode, data );
}
mReactInstanceManager 调用ImagePickerModule注册的onActivityResult方法
解决办法来自