Android實現獲取手機相冊裏面的所有圖片

獲取手機相冊裏所有會顯示的圖片,並不是手機所有的圖片

   		String selection = MediaStore.Images.Media.BUCKET_ID + " = ?";
        String bucketId = String.valueOf(id);
        String sort = MediaStore.Images.Media._ID + " DESC";
        String[] selectionArgs = {bucketId};

        Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        Cursor c;
        if (!bucketId.equals("0")) {
            c = resolver.query(images, null, selection, selectionArgs, sort);	//查詢帶條件
        } else {
            c = resolver.query(images, null, null, null, sort);//查詢所有
        }
        ArrayList<Uri> imageUris = new ArrayList<>();
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                //c.getString(c.getColumnIndex(MediaStore.Images.Media.DATA) 完整路徑名
                //c.getString(c.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME) 文件名
                    setPathDir(c.getString(c.getColumnIndex(MediaStore.Images.Media.DATA)),
                            c.getString(c.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)));
                    do {
                        String mimeType = c.getString(c.getColumnIndex(MediaStore.Images.Media.MIME_TYPE));
                        //獲取文件夾名  (DCIM,Camera)  不是完整路徑 
                        String folderName = c.getString(c.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME));
                        if (isExceptMemeType(exceptMimeTypeList, mimeType)
                                || isNotContainsSpecifyFolderList(specifyFolderList, folderName)) continue;

                        int imgId = c.getInt(c.getColumnIndex(MediaStore.MediaColumns._ID));
                        //獲取 uri
                        Uri path = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imgId);
                        imageUris.add(path);

                    } while (c.moveToNext());
                }
                c.close();
            } catch (Exception e) {
                if (!c.isClosed()) c.close();
            }
        }
        return imageUris;
private void setPathDir(String path, String fileName) {
        pathDir = path.replace("/" + fileName, "");	//獲取文件路徑
    }




























相冊顯示的圖片 需要加入以下代碼
String path = "你圖片的完整路徑";
   // 其次把文件插入到系統圖庫
//                        try {
//                            MediaStore.Images.Media.insertImage(getContext().getContentResolver(), path, path.substring(path.lastIndexOf("/")+1), null);
//                        } catch (FileNotFoundException e) {
//                            e.printStackTrace();
//                        }
                    //需要通知相冊更新了
                        getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章