从android相册获取所有图片的路径

在做从系统选择图片并获取到它们的路径时发现有些图片的uri.getScheme是“file”,有些图片的uri.getScheme是“content” 所有导致用uri.getPath并不能获取所有图片的路径,用如下代码解决:


@SuppressLint("NewApi")
	 public static String getPath(Activity activity, Uri uri) {
		L.i("hui", "处理前的路径:" + uri);
		if (null == uri) {
			return null;
		}
		String path = null;
		String scheme = uri.getScheme();
		if (scheme == null) {
			path = uri.getPath();
		} else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
			path = uri.getPath();
		} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
			Cursor cursor = null;
			if(VERSION.SDK_INT>=19&&DocumentsContract.isDocumentUri(activity, uri)){ //兼容andoid4.4版本
				String wholeID = DocumentsContract.getDocumentId(uri);
				String id = wholeID.split(":")[1];
				String[] column = { MediaStore.Images.Media.DATA };
				String sel = MediaStore.Images.Media._ID + "=?";
				 cursor = activity.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column,
				sel, new String[] { id }, null);
				int columnIndex = cursor.getColumnIndex(column[0]);
				if (cursor.moveToFirst()) {
					path = cursor.getString(columnIndex);
				}
				cursor.close();
				}else{
				String[] projection = { MediaStore.Images.Media.DATA };
				 cursor = activity.getContentResolver().query(uri, projection, null, null, null);
				int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				path = cursor.getString(column_index);
				}
			if(cursor!=null&&!cursor.isClosed()){
				cursor.close();
			}
		}
		return path;
	}





你可能感兴趣的:(从android相册获取所有图片的路径)