Solve the problem that android photos are not displayed in the system album.

Source: Internet
Author: User

We may all know that when we save the album to the Android mobile phone, we can open the system image library and cannot find the image we want, because the picture we inserted has not been updated yet, let's first explain how to insert a system image library. It's very simple. A code can be implemented.

 

MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "", "");

The above code can be inserted into the system image library. In this case, we cannot specify the name of the inserted photo. Instead, the system gives us the name of the number of milliseconds in the current time, I have been depressed for a long time. I should paste the insertimage source code first.

 

 

 /**             * Insert an image and create a thumbnail for it.             *             * @param cr The content resolver to use             * @param source The stream to use for the image             * @param title The name of the image             * @param description The description of the image             * @return The URL to the newly created image, or <code>null</code> if the image failed to be stored             *              for any reason.             */            public static final String insertImage(ContentResolver cr, Bitmap source,                                                   String title, String description) {                ContentValues values = new ContentValues();                values.put(Images.Media.TITLE, title);                values.put(Images.Media.DESCRIPTION, description);                values.put(Images.Media.MIME_TYPE, "image/jpeg");                Uri url = null;                String stringUrl = null;    /* value to be returned */                try {                    url = cr.insert(EXTERNAL_CONTENT_URI, values);                    if (source != null) {                        OutputStream imageOut = cr.openOutputStream(url);                        try {                            source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);                        } finally {                            imageOut.close();                        }                        long id = ContentUris.parseId(url);                        // Wait until MINI_KIND thumbnail is generated.                        Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id,                                Images.Thumbnails.MINI_KIND, null);                        // This is for backward compatibility.                        Bitmap microThumb = StoreThumbnail(cr, miniThumb, id, 50F, 50F,                                Images.Thumbnails.MICRO_KIND);                    } else {                        Log.e(TAG, "Failed to create thumbnail, removing original");                        cr.delete(url, null, null);                        url = null;                    }                } catch (Exception e) {                    Log.e(TAG, "Failed to insert image", e);                    if (url != null) {                        cr.delete(url, null, null);                        url = null;                    }                }                if (url != null) {                    stringUrl = url.toString();                }                return stringUrl;            }

There is a title in the above method. I thought it was possible to set the name Of the image. It turned out that it was not. It was depressing. Which of the Experts knows what the title field is for? Tell the younger brother, thank you!

 

Of course, Android also provides a method to insert a system album. You can specify the name of the image to be saved. I will post the source code.

 

   /**             * Insert an image and create a thumbnail for it.             *             * @param cr The content resolver to use             * @param imagePath The path to the image to insert             * @param name The name of the image             * @param description The description of the image             * @return The URL to the newly created image             * @throws FileNotFoundException             */            public static final String insertImage(ContentResolver cr, String imagePath,                    String name, String description) throws FileNotFoundException {                // Check if file exists with a FileInputStream                FileInputStream stream = new FileInputStream(imagePath);                try {                    Bitmap bm = BitmapFactory.decodeFile(imagePath);                    String ret = insertImage(cr, bm, name, description);                    bm.recycle();                    return ret;                } finally {                    try {                        stream.close();                    } catch (IOException e) {                    }                }            }

Ah, I found out after I pasted the source code that this method called the first method. This name is the title of the above method. This is even more depressing. Anyway, I set the title to no effect, ask the experts to answer questions for the younger brother. Let's continue.

 

After the above Code is inserted into the system album, a clockwork broadcast is required.

 

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));  

The above broadcast scans the whole SD card broadcast. If there are many things in your SD card that will be scanned for a long time, we cannot access the SD card during the scan, so this is a poor user experience, our friends once know that saving images to the system album does not scan the entire SD card, so we use the following method:

 

 

Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);    Uri uri = Uri.fromFile(new File("/sdcard/image.jpg"));    intent.setData(uri);    mContext.sendBroadcast(intent);  

Or use mediascannerconnection

 

 

final MediaScannerConnection msc = new MediaScannerConnection(mContext, new MediaScannerConnectionClient() {     public void onMediaScannerConnected() {      msc.scanFile("/sdcard/image.jpg", "image/jpeg");     }     public void onScanCompleted(String path, Uri uri) {      Log.v(TAG, "scan completed");      msc.disconnect();     }    });   

You can also ask me how to get the path of the picture we just inserted? Haha, this method is used to obtain the insertimage (contentresolver Cr, bitmap source, String title, string description). This method returns the URI of the inserted image, based on this URI, we can obtain the absolute path of the image.

 

 

private  String getFilePathByContentResolver(Context context, Uri uri) {if (null == uri) {return null;}        Cursor c = context.getContentResolver().query(uri, null, null, null, null);        String filePath  = null;        if (null == c) {            throw new IllegalArgumentException(                    "Query on " + uri + " returns null result.");        }        try {            if ((c.getCount() != 1) || !c.moveToFirst()) {            } else {            filePath = c.getString(            c.getColumnIndexOrThrow(MediaColumns.DATA));            }        } finally {            c.close();        }        return filePath;    }

According to the above method, the absolute path of the image is obtained, so we don't need to send a broadcast that scans the entire SD card, I hope you will take a look at it and hope it will help you!

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.