获取通讯录、扫码、打开相册、拍照等操作,都是一个套路,就是创建module,原生实现这些方法,前端调用是时候返回最终的结果。
下面是如何打开本地相册,并获取照片路径。
public class PickImageModule extends WXModule {
public static final int REQUEST_CODE = 10010;
public final static int CAMERA_REQUEST_CODE= 1;
protected JSCallback callback;
@JSMethod(uiThread = true)
public void choosePhoto(JSCallback callback) {
if (ContextCompat.checkSelfPermission(mWXSDKInstance.getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((WXPageActivity) mWXSDKInstance.getContext(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
CAMERA_REQUEST_CODE);
} else {
choosePhoto();
}
this.callback = callback;
}
private void choosePhoto() {
Intent intentToPickPic = new Intent(Intent.ACTION_PICK, null); intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/jpeg");
((Activity) (mWXSDKInstance.getContext())).startActivityForResult(intentToPickPic, GALLERY_REQUEST_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == WXPageActivity.RESULT_OK) {
switch (requestCode) {
case GALLERY_REQUEST_CODE: {
try {
Uri selectedImage = data.getData();
String[] filePathColumns = {MediaStore.Images.Media.DATA};
Cursor c = mWXSDKInstance.getContext().getContentResolver().query(selectedImage, filePathColumns, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePathColumns[0]);
String picturePath = c.getString(columnIndex);
c.close();
callback.invoke(picturePath);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
配置相应的权限,在WXApplication中加入
WXSDKEngine.registerModule("pickPhoto", PickImageModule.class);
然后就是前端调用
const pickPhoto = weex.requireModule('pickPhoto')
... //在方法中直接使用就行了
pickPhoto .choosePhoto(res => {
...
})
网友评论