1. 程式人生 > >Android獲取手機圖片

Android獲取手機圖片

1.概述

在Andorid系統中所有的檔案路徑都儲存在一個數據庫中,位於data/data/com.android.providers.media資料夾下的external.db

裡面的files表就有我們需要的內容,這個表包含了機器所有的檔案。接下來只要選擇合適的sql語句來獲取我們需要的內容就行了。

2.實現

資料庫結構如下圖

首先過濾出相簿資料夾,獲取所在資料夾路徑,資料夾名稱,資料夾檔案數目,檔案路徑和修改時間。構建資料夾和封面

public static Cursor getAlbumCursor(ContentResolver cr){
//開啟files這個表
        Uri uri= MediaStore.Files.getContentUri("external");
        String [] project =new String[]{
                MediaStore.Files.FileColumns.PARENT,
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
                "count(*)",
                MediaStore.Images.Media.DATA,
                "max(" + MediaStore.Images.Media.DATE_MODIFIED + ")"
        };
//用group by進行整合
        String selection = String.format("%s=? or %s=?) group by (%s",
                MediaStore.Files.FileColumns.MEDIA_TYPE,
                MediaStore.Files.FileColumns.MEDIA_TYPE,
                MediaStore.Files.FileColumns.PARENT
        ) ;
        String[] selectionArgs = new String[]{
                MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE+"",//獲取圖片檔案
                MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO+"",//獲取視訊檔案
        };
        String sortOrder = MediaStore.Images.Media.DATE_MODIFIED + " desc";
//        String sortOrder = "max(date_modified) DESC";
// 轉換成sql語句: SELECT parent, bucket_display_name, count(*), _data, max(date_modified) FROM files WHERE (media_type=? or media_type=?)
// group by (parent) HAVING (_data NOT LIKE ? ) ORDER BY max(date_modified) DESC
        return cr.query(uri,project,selection,selectionArgs,sortOrder);
    }

拿到cursor後就可以進行查詢獲取資料

 public Album(Cursor cur) {
//圖片路徑
        this(cur.getString(3),
//所在資料夾的名稱
                cur.getString(1),
//所在的父檔案
                cur.getLong(0),
//資料夾的檔案數目
                cur.getInt(2),
//修改時間
                cur.getLong(4)
        );
    }

相簿資料夾構建好了後,在來獲取資料夾裡面的所有的圖片

 public static Cursor getMediaCursor(ContentResolver cr,Album album){
        Uri uri = MediaStore.Files.getContentUri("external");
         String[] sProjection = new String[] {
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DATE_TAKEN,
                MediaStore.Images.Media.MIME_TYPE,
                MediaStore.Images.Media.SIZE,
                MediaStore.Images.Media.ORIENTATION
        };
//獲取parent一樣的檔案
         String selections = (String.format("(%s=? or %s=?) and %s=?",
                 MediaStore.Files.FileColumns.MEDIA_TYPE,
                 MediaStore.Files.FileColumns.MEDIA_TYPE,
                 MediaStore.Files.FileColumns.PARENT));
        String[] selectionArgs = new String[]{
                MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE+"",
                MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO+"",
                album.getId()+""
        };
        String sortOrder = MediaStore.Images.Media.DATE_MODIFIED + " desc";
        return  cr.query(uri,sProjection,selections,selectionArgs,sortOrder);
    }

接下來構建實體類

 public Media(Cursor cur) {
//具體路徑
        this(cur.getString(0),
                cur.getLong(1),
                cur.getString(2),
                cur.getLong(3),
                cur.getInt(4));
    }

這種方式主要是利用好了sql語句,同時結合rxjava的話可以實現查詢一張照片顯示一張照片的效果。

3.擴充套件

類似的還可以獲取特定型別的檔案

private ArrayList<LayoutElementParcelable> listImages() {
        ArrayList<LayoutElementParcelable> images = new ArrayList<>();
        final String[] projection = {MediaStore.Images.Media.DATA};
        final Cursor cursor = c.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection, null, null, null);
        if (cursor == null)
            return images;
        else if (cursor.getCount() > 0 && cursor.moveToFirst()) {
            do {
                String path = cursor.getString(cursor.getColumnIndex
                        (MediaStore.Files.FileColumns.DATA));
                HybridFileParcelable strings = RootHelper.generateBaseFile(new File(path), showHiddenFiles);
                if (strings != null) {
                    LayoutElementParcelable parcelable = createListParcelables(strings);
                    if(parcelable != null) images.add(parcelable);
                }
            } while (cursor.moveToNext());
        }
        cursor.close();
        return images;
    }

    private ArrayList<LayoutElementParcelable> listVideos() {
        ArrayList<LayoutElementParcelable> videos = new ArrayList<>();
        final String[] projection = {MediaStore.Images.Media.DATA};
        final Cursor cursor = c.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                projection, null, null, null);
        if (cursor == null)
            return videos;
        else if (cursor.getCount() > 0 && cursor.moveToFirst()) {
            do {
                String path = cursor.getString(cursor.getColumnIndex
                        (MediaStore.Files.FileColumns.DATA));
                HybridFileParcelable strings = RootHelper.generateBaseFile(new File(path), showHiddenFiles);
                if (strings != null) {
                    LayoutElementParcelable parcelable = createListParcelables(strings);
                    if(parcelable != null) videos.add(parcelable);
                }
            } while (cursor.moveToNext());
        }
        cursor.close();
        return videos;
    }

    private ArrayList<LayoutElementParcelable> listaudio() {
        String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
        String[] projection = {
                MediaStore.Audio.Media.DATA
        };

        Cursor cursor = c.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                projection,
                selection,
                null,
                null);

        ArrayList<LayoutElementParcelable> songs = new ArrayList<>();
        if (cursor == null)
            return songs;
        else if (cursor.getCount() > 0 && cursor.moveToFirst()) {
            do {
                String path = cursor.getString(cursor.getColumnIndex
                        (MediaStore.Files.FileColumns.DATA));
                HybridFileParcelable strings = RootHelper.generateBaseFile(new File(path), showHiddenFiles);
                if (strings != null) {
                    LayoutElementParcelable parcelable = createListParcelables(strings);
                    if(parcelable != null) songs.add(parcelable);
                }
            } while (cursor.moveToNext());
        }
        cursor.close();
        return songs;
    }

    private ArrayList<LayoutElementParcelable> listDocs() {
        ArrayList<LayoutElementParcelable> docs = new ArrayList<>();
        final String[] projection = {MediaStore.Files.FileColumns.DATA};
        Cursor cursor = c.getContentResolver().query(MediaStore.Files.getContentUri("external"),
                projection, null, null, null);
        String[] types = new String[]{".pdf", ".xml", ".html", ".asm", ".text/x-asm", ".def", ".in", ".rc",
                ".list", ".log", ".pl", ".prop", ".properties", ".rc",
                ".doc", ".docx", ".msg", ".odt", ".pages", ".rtf", ".txt", ".wpd", ".wps"};
        if (cursor == null)
            return docs;
        else if (cursor.getCount() > 0 && cursor.moveToFirst()) {
            do {
                String path = cursor.getString(cursor.getColumnIndex
                        (MediaStore.Files.FileColumns.DATA));
                if (path != null && Arrays.asList(types).contains(path)) {
                    HybridFileParcelable strings = RootHelper.generateBaseFile(new File(path), showHiddenFiles);
                    if (strings != null) {
                        LayoutElementParcelable parcelable = createListParcelables(strings);
                        if(parcelable != null) docs.add(parcelable);
                    }
                }
            } while (cursor.moveToNext());
        }
        cursor.close();
        Collections.sort(docs, (lhs, rhs) -> -1 * Long.valueOf(lhs.date).compareTo(rhs.date));
        if (docs.size() > 20)
            for (int i = docs.size() - 1; i > 20; i--) {
                docs.remove(i);
            }
        return docs;
    }

    private ArrayList<LayoutElementParcelable> listApks() {
        ArrayList<LayoutElementParcelable> apks = new ArrayList<>();
        final String[] projection = {MediaStore.Files.FileColumns.DATA};

        Cursor cursor = c.getContentResolver()
                .query(MediaStore.Files.getContentUri("external"), projection, null, null, null);
        if (cursor == null)
            return apks;
        else if (cursor.getCount() > 0 && cursor.moveToFirst()) {
            do {
                String path = cursor.getString(cursor.getColumnIndex
                        (MediaStore.Files.FileColumns.DATA));
                if (path != null && path.endsWith(".apk")) {
                    HybridFileParcelable strings = RootHelper.generateBaseFile(new File(path), showHiddenFiles);
                    if (strings != null) {
                        LayoutElementParcelable parcelable = createListParcelables(strings);
                        if(parcelable != null) apks.add(parcelable);
                    }
                }
            } while (cursor.moveToNext());
        }
        cursor.close();
        return apks;
    }

原始碼

相關推薦

Android獲取手機圖片

1.概述 在Andorid系統中所有的檔案路徑都儲存在一個數據庫中,位於data/data/com.android.providers.media資料夾下的external.db 裡面的files表就有我們需要的內容,這個表包含了機器所有的檔案。接下來只要選擇合適的sql

Android 獲取手機模擬器sd卡圖片及擷取圖片

需把圖片儲存到找到手機模擬器(夜神模擬器)sd卡中的圖片路徑:檔案管理器/mnt/sdcard/images(images是自己創的資料夾) java程式碼: package com.example.android_07; import android.graphics.Bitmap

Android之通過ContentResolver獲取手機圖片和視訊的路徑和生成縮圖和縮圖路徑

1 問題 獲取手機所有圖片和視訊的路徑和生成圖片和視訊的縮圖和縮圖路徑 生成縮圖我們用的系統函式 public static Bitmap getThumbnail(ContentResolver cr, long origId, int kind, Opti

Android-獲取手機上所有圖片

核心程式碼: Cursor cursor = getContentResolver() .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, nu

android獲取手機所有圖片

public ImageFilesBean returnImageFiles() { List<String> parentsPthe = new ArrayLis

Android 獲取手機本地圖片所在的位置

道友們在做需求的時候、可能會需要展示圖片的拍攝地點、 android已經有這類的方法、上程式碼、親測可用 exifInterface = new ExifInterface(photoPath1); Str

android 獲取手機信息工具類

telephony == 系統 設備 android pack devices 信息 context package com.yqy.yqy_listviewheadview; import android.content.Context; import androi

Android 獲取手機SIM卡運營商

uil track service del 手機 star tor eas on() 直接上代碼: /** * 獲取SIM卡運營商 * * @param context * @return */ public static String ge

android 獲取手機設備品牌

pos 品牌 style article rand 什麽 適配 span 簡單 在有些數據要獲取手機設備是什麽品牌,特別做一些適配的時候,好了就講下怎樣或者手機是什麽品牌: String brand =android.os.Build.BRAND; 就這麽簡

Android 獲取手機的廠商、型號、Android系統版本號、IMEI、當前系統語言等工具類

parameter toc systems star lan gets post version -h 最近在開發中,需要用到一些系統信息,這裏我把這些方法寫成一個工具類方便以後復用,該工具類有以下6個功能: 1、獲取手機制造廠商 2、獲取手機型號 3、獲取手機系統當前使用

Android 獲取指定圖片或檔案的大小

/** * 獲取指定檔案大小    */ public static long getFileSize(File file) throws Exception { long size = 0; if (file.exists()) { FileInputStrea

android獲取手機型號和手機廠商

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

android獲取手機內部儲存空間和外部儲存空間

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

Android獲取手機版本號、品牌等 相關資訊工具類

主要有,獲取手機系統版本,獲取手機品牌、獲取軟體版本資訊、獲取螢幕尺寸寬高(包含和不包含虛擬鍵)以及獲取手機ip地址 public class DeviceUtils { /** * 品牌 */ public static String getDevic

Android獲取手機唯一標識

//獲取手機唯一標識 private String getId() { StringBuilder deviceId = new StringBuilder(); // 渠道標誌 deviceId.append("a");

Android 獲取手機儲存資訊詳解(記憶體,外存等)

ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); //系統記憶體資訊 ActivityManager.MemoryInfo memInfo = new ActivityManager

webview中頁面按鈕獲取手機圖片並顯示的問題

webview中頁面按鈕獲取手機圖片並顯示的問題 10月1就這麼愉快的過去了,今天突然一個激靈想到竟然忘了總結自己遇到的問題,萬一哪天我得了老年痴呆可咋辦啊,於是想起了記一下自己遇到的小坑來為我萌新程式設計師的道路上新增些新的標記!! 30號的時候,我的同事說:’‘我顯示不了手機上的

Android 獲取手機的解析度兩種方法

  A,過時的API [2]獲取手機的解析度         WindowManager wm  = (WindowManager) getSystemService(WINDOW_SERVICE

android獲取手機型號和系統版本號

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

Android 獲取手機儲存總大小,系統佔用空間

一、Android 儲存介紹及通常查詢大小 手機儲存有兩種,內建記憶體和外接記憶體(SD),目前可擴充套件記憶體的機型正在減少,大部分是內建儲存的手機,內建128G、256G已經很常見,但如果有擴充套件功能的話,買個乞丐版+SD卡也是美滋滋,畢竟廠家增加儲存空間後手機定價也不便宜。言