Summary of data update methods for Android media library

Summary of data update methods for Android media library

In the project, we often create our own directory to store some pictures and files. For example, I just created a folder a in the SD card and put photos B in it. At this time, I immediately go to the gallery to view the photos in this directory. Then, I can't see them.

What is the reason?

Because the Android system will start mediascannerservice to scan the multimedia files on the system when it is started, and then add the information of these multimedia files to the multimedia database. The application needs to obtain these multimedia information from the multimedia database, not from the SD card. In other words, if some multimedia is added or deleted after startup, the multimedia database will not be refreshed automatically.

Solution: 1. Start and restart; 2. Update media library data information;

For method 1, it is impossible to add a file to restart the phone, so this pass.

For method 2:

The common method on the Internet is to send a message to the system through broadcasting to make the system automatically update the media library. The code is as follows:

Here, we can send two messages: intent. Action_ MEDIA_ Mounted is a full scan of the media library;

Intent.ACTION_ MEDIA_ SCANNER_ SCAN_ File scans a file;

After testing, this method has no problem with versions below Android 4.4, but the following exceptions will occur when using this method from Android 4.4:

Permission Denial: not allowed to send broadcast android.intent.action.MEDIA_ MOUNTED

This problem will cause app to crash directly.

After checking the SDK development documents, we find that the above methods are no longer allowed since Android 4.4. The development document points out that since 4.4, non system applications are no longer allowed to send system messages, but intent.action_ MEDIA_ Mounted is a system message. Therefore, in order to solve the compatibility problem of different versions, we cannot continue to use the above method.

How to solve this problem?

As we just said, the Android system will start mediascannerservice to scan the multimedia files on the system when it is started. Then, if we scan the multimedia files once before viewing the gallery, wouldn't it be solved?

Direct code:

With this function, when we add an image file, we can directly call this function to scan the added image file. In this way, we only scan the file we added, not the entire media library file. Therefore, the efficiency is the highest. After testing, the above method can perfectly solve the problem of media library update!

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>