内容提供者——获取媒体库里面的图片

Posted 春招进大厂的梦想家

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了内容提供者——获取媒体库里面的图片相关的知识,希望对你有一定的参考价值。

内容提供者——获取媒体库里面的图片


——写在前面

对于媒体内容提供者的应用场景有哪些呢?

比如说你的上传头像,比如说你做行车记录的,抓拍图片功能用户查看预览,比如说你的微信,QQ发动态,比如说你淘宝购物,要从图片中扫描二维码。这些都从图库里拿这个图片。

一、获取到图片内容

1.URI

URI的常量
  • 图片URI

    MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    
  • 视频的Url

    MediaStore.Video.Media.EXTERNAL_CONTENT_URI
    
  • 音频的

    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
    

2.权限

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

检查权限

    private void checkPermission() {
        int readExternalStoragePermissionResult = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
        if(readExternalStoragePermissionResult != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},PERMISSION_REQUEST_CODE);
        }
    }

3.获取数据表字段

 ContentResolver contentResolver = getContentResolver();
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        Cursor query = contentResolver.query(uri,null,null,null,null,null);
        String[] columnNames = query.getColumnNames();
        while(query.moveToNext()) {
            Log.d(TAG,"----------------------------");
            for(String columnName : columnNames) {
                Log.d(TAG,columnName + " ==== " + query.getString(query.getColumnIndex(columnName)));
            }
            Log.d(TAG,"----------------------------");
        }
        query.close();

20191118_222232.png

4准备一个封装数据bean类

public class PhotoItem {

    private String path;
    private String name;
    private long createDate;
    private boolean isSelected = false;


    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public long getCreateDate() {
        return createDate;
    }

    public void setCreateDate(long createDate) {
        this.createDate = createDate;
    }
}

5.将获取到的图片数据封装起来并且显示

public class ImagePickerActivity extends AppCompatActivity {

    private static final String TAG = "ImagePickerActivity";
    private RecyclerView mPicListView;
    private List<PhotoItem> mPics = new ArrayList<>();
    private PicListAdapter mPicListAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_picker);
        initView();
        initData();
    }

    private void initData() {
        //这些事情其实不能在主线程做,我们稍后修改
        ContentResolver contentResolver = getContentResolver();
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        Cursor query = contentResolver.query(uri,new String[]{
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media._ID},null,null,null,null);
        while(query.moveToNext()) {
            PhotoItem photoItem = new PhotoItem();
            photoItem.setPath(query.getString(0));
            //这里的下标跟上面的query第一个参数对应,时间是第2个,所以下标为1
            photoItem.setCreateDate(query.getLong(1));
            photoItem.setName(query.getString(2));
            mPics.add(photoItem);
        }
        query.close();
        mPicListAdapter.setData(mPics);
    }


    private void initView() {
        mPicListView = this.findViewById(R.id.pic_list);
        mPicListView.setLayoutManager(new GridLayoutManager(this,3));
        mPicListAdapter = new PicListAdapter();
        mPicListView.setAdapter(mPicListAdapter);
    }


}

6.为RecycleView准备适配器

public class PicListAdapter extends RecyclerView.Adapter<PicListAdapter.InnerHolder> {

    private List<PhotoItem> mData = new ArrayList<>();

    @NonNull
    @Override
    public InnerHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {
        ImageView iv = new ImageView(parent.getContext());
        iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
        Point point = new Point();
        ((WindowManager) parent.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(point);
        RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(point.x / 3,point.x / 3);
        iv.setLayoutParams(layoutParams);
        return new InnerHolder(iv);
    }

    @Override
    public void onBindViewHolder(@NonNull InnerHolder holder,int position) {
        if(holder.itemView instanceof ImageView) {
            Glide.with(holder.itemView.getContext()).load(mData.get(position).getPath()).into((ImageView) holder.itemView);
        }
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public void setData(List<PhotoItem> pics) {
        mData.clear();
        mData.addAll(pics);
        notifyDataSetChanged();
    }

    public class InnerHolder extends RecyclerView.ViewHolder {
        public InnerHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
}

二、使用LoaderManager来加载

前面我们直接在onCreate的地方加载数据,如果数据量大的话,会导致主线程阻塞出现ANR异常。如果数据量小,会影响页面的打开速度。

所以我们要么自己创建子线程去获取,或者可以通过LoaderManager去获取。

public class MediaContentPickerActivity extends AppCompatActivity {

    private static final int LOADER_ALL = 0;         // 获取所有图片
    private static final String TAG = "ContentPickerActivity";
    private List<PhotoItem> photoInfoList = new ArrayList<>();      // 本地图片信息List


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_picker);
        initLoader();
    }

    private void initLoader() {
        LoaderManager loaderManager = LoaderManager.getInstance(this);
        loaderManager.initLoader(LOADER_ALL,null,new LoaderManager.LoaderCallbacks<Cursor>() {
            private final String[] IMAGE_PROJECTION = {
                    MediaStore.Images.Media.DATA,
                    MediaStore.Images.Media.DISPLAY_NAME,
                    MediaStore.Images.Media.DATE_ADDED,
                    MediaStore.Images.Media._ID,
            };

            @NonNull
            @Override
            public Loader<Cursor> onCreateLoader(int id,@Nullable Bundle args) {
                if(id == LOADER_ALL) {
                    return new CursorLoader(MediaContentPickerActivity.this,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,IMAGE_PROJECTION,
                            null,null,IMAGE_PROJECTION[2] + " DESC");
                }
                return null;
            }

            @Override
            public void onLoadFinished(@NonNull Loader<Cursor> loader,Cursor data) {
                if(data != null) {
                    int count = data.getCount();
                    if(count > 0) {
                        List<PhotoItem> tempPhotoList = new ArrayList<>();
                        data.moveToFirst();
                        do {
                            String path = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                            String name = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
                            long dateTime = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                            PhotoItem photoItem = new PhotoItem();
                            photoItem.setName(name);
                            photoItem.setPath(path);
                            photoItem.setCreateDate(dateTime);
                            tempPhotoList.add(photoItem);
                        } while(data.moveToNext());
                        photoInfoList.clear();
                        photoInfoList.addAll(tempPhotoList);
                    }
                    //输出结果
                    for(PhotoItem photoItem : photoInfoList) {
                        Log.d(TAG,"photoItem -- > " + photoItem);
                    }
                }
            }

            @Override
            public void onLoaderReset(@NonNull Loader<Cursor> loader) {

            }
        });
    }

}

以上是关于内容提供者——获取媒体库里面的图片的主要内容,如果未能解决你的问题,请参考以下文章

WPF中使用datagrid显示数据库里面的内容

SVN提交成功,但是版本库里面的内容没有更新--解决方案

片段中的媒体控制器

php获取mysql数据库里面的所有数据表信息

安卓获取视频语音文件时间长度

Swift新async/await并发中利用Task防止指定代码片段执行的数据竞争(Data Race)问题