Android 获取手机中的图片信息的两种方法

来源:互联网 发布:现在做淘宝还有前途吗 编辑:程序博客网 时间:2024/04/28 06:13
1,  

Android 使用ContentProvider扫描手机中的图片


// 必须在查找前进行全盘的扫描,否则新加入的图片是无法得到显示的(加入对sd卡操作的权限)//todo 仅限于android4.2.2(API 17)以下(不包括17)可以正常使用。。。。public static void allScanBeforeSearchRes(Context context) {    if (Build.VERSION.SDK_INT >= 17) { // 判断SDK版本是不是4.2.2或者高于4.2.2.//todo useless...        String[] paths = new String[]{Environment.getExternalStorageDirectory().toString()};        MediaScannerConnection.scanFile(context, paths, null, null);    } else {        Intent intent;        intent = new Intent(Intent.ACTION_MEDIA_MOUNTED);        intent.setClassName("com.android.providers.media", "com.android.providers.media.MediaScannerReceiver");        intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));        context.sendBroadcast(intent);    }}
private void getAllPicturesInTheDevice() {    CommonUtil.allScanBeforeSearchRes(this);//对android 4.4 以下有用。。。    String[] projection = {            MediaStore.Images.Media.DATA,            MediaStore.Images.Media.DATE_TAKEN,    };    //全部图片    String where = MediaStore.Images.Media.MIME_TYPE + "=? or "            + MediaStore.Images.Media.MIME_TYPE + "=?";    String[] whereArgs = {"image/jpeg", "image/png"};    Cursor cursor = getContentResolver().query(            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection,            where, whereArgs, MediaStore.Images.Media.DATE_MODIFIED + " desc");       while (cursor.moveToNext()) {        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));        Long takeDate = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN));
......    }    cursor.close();}

2, 通过遍历找到所有的图片格式的文件。强烈推荐使用第二种方法,准确。
private static List<File> fileList = new ArrayList<File>();private static String[] img = new String[]{".jpg", ".png", ".gif", ".bmp"};

/** * 遍历sdcard 找到某找类型的file放到list中。 * 比较耗时 建议放在线程中做 * @param file */private static void checkFile(File file) {// 遍历文件,在这里是遍历sdcard    if (file.isDirectory()) {// 判断是否是文件夹        File[] files = file.listFiles();// 以该文件夹的子文件或文件夹生成一个数组        if (files != null) {// 如果文件夹不为空            for (int i = 0; i < files.length; i++) {                File f = files[i];                checkFile(f);// 递归调用            }        }    } else if (file.isFile()) {// 判断是否是文件        int dot = file.getName().lastIndexOf(".");        if (dot > -1 && dot < file.getName().length()) {            String extriName = file.getName().substring(dot,                    file.getName().length());// 得到文件的扩展名            if (extriName.equals(img[0]) || extriName.equals(img[1])                    || extriName.equals(img[2]) || extriName.equals(img[3])) {// 判断是否是图片文件 www.it165.net                fileList.add(file);            }        }    }}

相关链接:
http://blog.csdn.net/xiaanming/article/details/18730223
http://www.it165.net/pro/html/201304/5483.html

1 0
原创粉丝点击