一、获取手机中的值
1.首先在使用读写sd卡权限
2.获取手机中的所有图片:
注意代码中的getGalleryPhotos(getContentResolver()) 方法获取所有地址
获取所有图片地址后使用recycleview 组件构建自定义相册,recycleview的使用方式我就不多说了自己百度
private void initAbbreviation() {//if语句 没有读写SD卡的权限,就申请权限if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);} else {//获取所有图片存入list集合 getGalleryPhotos方法allPath = new ArrayList<>();allPath = getGalleryPhotos(getContentResolver());Log.d("tgw所有图片地址", "initAbbreviation: " + allPath.toString());//取出首张图片if (allPath != null && !allPath.isEmpty()) {picturePath = allPath.get(0);}}}
//获取所有图片存入list集合返回,MediaStore.Images.Media.DATA中的Imagespublic static ArrayList<String> getGalleryPhotos(ContentResolver resolver) {ArrayList<String> galleryList = new ArrayList<String>();try {//获取所在相册和相册idfinal String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};//按照id排序final String orderBy = MediaStore.Images.Media._ID;//相当于sql语句默认升序排序orderBy,如果降序则最后一位参数是是orderBy+" desc "Cursor imagecursor =resolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,null, orderBy);//从数据库中取出图存入list集合中if (imagecursor != null && imagecursor.getCount() > 0) {while (imagecursor.moveToNext()) {int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
// Log.d("tgw7", "getGalleryPhotos: " + dataColumnIndex);String path = "file://" + imagecursor.getString(dataColumnIndex);Log.d("tgw5", "getGalleryPhotos: " + path);galleryList.add(path);}}} catch (Exception e) {e.printStackTrace();}// 进行反转集合Collections.reverse(galleryList);return galleryList;}
二、获取系统相册中选中图片的值
1.首先开启系统相册---SELECT_PHOTO是一个请求值 用于onActivityResult 方法中判断由谁发出请求
//2.0 开启系统相册 //浏览照片---看 onActivityResult 的返回方法Intent intent = new Intent("android.intent.action.GET_CONTENT");intent.setType("image/*");startActivityForResult(intent, SELECT_PHOTO);
2.onActivityResult 获取选中的图片返回值,关注下面的getRealPathFromUri(this, data.getData()); 方法它是获取选中图片的关键
//先判断图片类型在 获取指定的图片序号,在根据指定的id序号使用Cursor查询得到图片地址@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {super.onActivityResult(requestCode, resultCode, data);//外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口ContentResolver resolver = getContentResolver();switch (requestCode) {case SELECT_PHOTO:if (resultCode == RESULT_OK) {//先判断图片类型在 获取指定的图片序号,在根据指定的id序号使用Cursor查询得到图片地址if (data != null) {selectPicturePath = getRealPathFromUri(this, data.getData());Log.d("tgw", "onActivityResult: " + selectPicturePath + "--" + data.getData());imageLoader.displayImage(selectPicturePath,ivLoad3,options);} else {Toast.makeText(this, "图片损坏,请重新选择", Toast.LENGTH_SHORT).show();}// //打开系统相册,但是返回值为空
// try {
// Uri imageUri = data.getData(); //获得图片的uri
// picturePathBitmap = MediaStore.Images.Media.getBitmap(resolver, imageUri);
// String[] proj = {MediaStore.Images.Media.DATA};
//
// //好像是android多媒体数据库的封装接口,具体的看Android文档
// Cursor cursor = managedQuery(imageUri, proj, null, null, null);
//
// //按我个人理解 这个是获得用户选择的图片的索引值
// int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//
// //将光标移至开头 ,这个很重要,不小心很容易引起越界
// cursor.moveToFirst();
//
// //最后根据索引值获取图片路径
// picturePath = cursor.getString(column_index);
// Log.d("tgw3", "onActivityResult: " + picturePath);
//
// } catch (IOException e) {
// e.printStackTrace();
// }
// Log.d("tgw3", "onActivityResult: " + requestCode + "---" + resultCode);
//
// } else {
// Log.d("tgw4", "onActivityResult: " + requestCode + "---" + resultCode);}break;default:break;}}
3.getRealPathFromUri(this, data.getData());方法如下所示
其中值得我们注意的是API的大小
API>19 我们需要根据图片类型进行不同的查询
API<19 关注getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) 方法
//获取选择的图片地址private String getRealPathFromUri(MainActivity mAct, Uri uri) {Log.d("tgw", "getRealPathFromUri:uri.getScheme() " + uri.getScheme());if (Build.VERSION.SDK_INT >= 19) { // api >= 19 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回nullString filePath = null;//判断该Uri是否是document封装过的DocumentsContract.isDocumentUri(mAct, uri)if (DocumentsContract.isDocumentUri(mAct, uri)) {// 如果是document类型的 uri, 则通过document id来进行处理String documentId = DocumentsContract.getDocumentId(uri);if ("com.android.providers.media.documents".equals(uri.getAuthority())) { // MediaProvider// 使用':'分割用split('.')方法将字符串以"."开割形成一个字符串数组,// 然后再通过索引[1]取出所得数组中的第二个元素的值。String id = documentId.split(":")[1];Log.d("tgw1", "getRealPathFromUri: " + documentId + "--" + id);String selection = MediaStore.Images.Media._ID + "=?";String[] selectionArgs = {id};//如果要查询图片,地址:MediaStore.Images.Media.EXTERNAL_CONTENT_URIfilePath = getDataColumn(mAct, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);Log.d("tgwdocuments", "getRealPathFromUri: " + filePath + "==" + selectionArgs);} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) { // DownloadsProvider//这个方法负责把id和contentUri连接成一个新的Uri=: content://downloads/public_downloads/documentIdUri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));filePath = getDataColumn(mAct, contentUri, null, null);Log.d("tgwcontentUri", "getRealPathFromUri: " + filePath);}} else if ("content".equalsIgnoreCase(uri.getScheme())) {// 如果是 content 类型的 Uri// 返回文件头 uri.getScheme() 如:content file 等等filePath = getDataColumn(mAct, uri, null, null);Log.d("tgwcontent", "getRealPathFromUri: " + filePath);} else if ("file".equals(uri.getScheme())) {// 如果是 file 类型的 Uri,直接获取图片对应的路径filePath = uri.getPath();Log.d("tgwfile", "getRealPathFromUri: " + filePath);}return filePath;} else { // api < 19return getDataColumn(mAct, uri, null, null);}}
4.获取选到图片数据的地址:
getDataColumn 方法:
private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {String path = null;String[] projection = new String[]{MediaStore.Images.Media.DATA};Cursor cursor = null;try {//uri提供内容的地址,projection查询要返回的列,// selection :查询where字句, selectionArgs : 查询条件属性值 ,sortOrder :结果排序规则cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);if (cursor != null && cursor.moveToFirst()) {//getColumnIndexOrThrow 从零开始返回指定列名称,如果不存在将抛出IllegalArgumentException 异常。int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);path = cursor.getString(columnIndex);Log.d("tgwgetDataColumn", "getDataColumn: " + path);}} catch (Exception e) {if (cursor != null) {cursor.close();}}// "file://" 图片地址要加上file头return "file://" + path;}
Android获取手机中的所有音乐地址:
https://blog.csdn.net/TGWhuli/article/details/97760172