String[] mPermissionList = new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE};
public static final int REQUEST_PICK_IMAGE = 11101;
• 打开手机相册
ActivityCompat.requestPermissions(MainActivity.this, mPermissionList, 100);
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 100:
boolean writeExternalStorage = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean readExternalStorage = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (grantResults.length > 0 && writeExternalStorage && readExternalStorage) {
getImage();
} else {
Toast.makeText(this, “请设置必要权限”, Toast.LENGTH_SHORT).show();
}
break;
}
}
private void getImage() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType(“image/*”),
REQUEST_PICK_IMAGE);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType(“image/*”);
startActivityForResult(intent, REQUEST_PICK_IMAGE);
}
}
  • 获取相册返回的Uri
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case REQUEST_PICK_IMAGE:
if (data != null) {
String realPathFromUri = RealPathFromUriUtils.getRealPathFromUri(this, data.getData());
} else {
Toast.makeText(this, “图片损坏,请重新选择”, Toast.LENGTH_SHORT).show();
}
break;
}
}
}

这里的data.getData()返回的就是Uri,realPathFromUri 为真正路径

  • 获取真正路径
package com.example.richeditortest;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
public class RealPathFromUriUtils {
/**
• 根据Uri获取图片的绝对路径
• 
• @param context 上下文对象
• @param uri 图片的Uri
• @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
*/
public static String getRealPathFromUri(Context context, Uri uri) {
int sdkVersion = Build.VERSION.SDK_INT;
if (sdkVersion >= 19) { // api >= 19
return getRealPathFromUriAboveApi19(context, uri);
} else { // api < 19
return getRealPathFromUriBelowAPI19(context, uri);
}
}
/**
• 适配api19以下(不包括api19),根据uri获取图片的绝对路径
• 
• @param context 上下文对象
• @param uri 图片的Uri
• @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
*/
private static String getRealPathFromUriBelowAPI19(Context context, Uri uri) {
return getDataColumn(context, uri, null, null);
}
/**
• 适配api19及以上,根据uri获取图片的绝对路径
• 
• @param context 上下文对象
• @param uri 图片的Uri
• @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null