Problem Background:
The reference link allows you to browse images, scan gallery photos with ContentResolver, and display the photos in the listview in strict chronological order. As shown in:
The problem is that 4.2 of mobile phones can be normally displayed, but with the addition of photos, this scan remains unchanged. It's really annoying. Another serious problem is that one image cannot run on 4.4 of mobile phones. Grandpa, it's really a pitfall. It took me several hours to waste, and then I almost gave up. I accidentally browsed my previous blog and found that the real reason was that I lost one permission.
You must have the following two permissions to play a role when sending broadcast updates. In particular, the second permission. If you do not have this permission, you can browse on 4.2 of your mobile phones, but it will not be updated. You cannot scan images at 4.4. But it is strange that no exception is reported in both cases.
The key query statements are as follows:
Uri mImageUri = MediaStore. images. media. EXTERNAL_CONTENT_URI; Log. I ("yanguoqi", "mImageUri =" + mImageUri. getPath (); ContentResolver mContentResolver = MainActivity. this. getContentResolver (); // only query jpeg image Cursor mCursor = mContentResolver. query (mImageUri, null, MediaStore. images. media. MIME_TYPE + "=? ", New String [] {" image/jpeg "}, MediaStore. images. media. DATE_TAKEN); mCursor. moveToLast (); int num = mCursor. getCount (); do {// obtain the image path String path = mCursor. getString (mCursor. getColumnIndex (MediaStore. images. media. DATA); if (path. contains ("/DCIM/Camera") {imgPaths. add (path) ;}while (mCursor. moveToPrevious (); mCursor. close ();
1. mContentResolver. query (mImageUri ...) This uri can only be Uri mImageUri = MediaStore. Images. Media. EXTERNAL_CONTENT_URI; constructed URI. Rather than writing a path to construct a URI, this is really strange;
2. to filter files, you can only filter the files in the Image Library by using the if (path. contains ("/DCIM/Camera") statement;
3. to strictly sort the photos by time, write MediaStore in the query. images. media. DATE_TAKEN is not yet in progress. The first cursor found in this writing is indeed the latest, but it is obtained through List. add operation. Instead, the first operation is arranged to the end. Therefore, I first move the cursor, and the reason why do is in front of while is not to miss the first image.
4. Before each query, you should send a broadcast update:
private void updateGallery(){Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); //, MediaStore.Images.Media.EXTERNAL_CONTENT_URIString path = Environment.getExternalStorageDirectory() + "/DCIM/Camera"; Uri uri = Uri.fromFile(new File(path)); intent.setData(uri); this.sendBroadcast(intent); }
In the broadcast area, you can specify the uri of the path.
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
.