"Android Development experience" How to get all the audio file information in the library and update the Media Library when the file is deleted or removed

Source: Internet
Author: User

Reprint Please specify Source: http://blog.csdn.net/zhaokaiqiang1992

Today, an open blog, found a friend sent me a private message, ask the following questions, so close this article, for its doubts.



from this friend's question, we need to understand the following questions, in order to give him a good answer:

(1) How can I get information about all the songs in my phone?

(2) When the song file changes, such as adding and deleting operations, how to update the Media Library in a timely manner to obtain the latest song information?

(3) After the 4.4 version, scan the SD card, update the Media Library operation has changed?


Below, I will answer the above three questions.


(1) How can I get information about all the songs in my phone?

If we want to solve this problem, we must first know how to manage the song information in the Android system.

In Android, the system establishes a database (SQLite database) for multimedia types of files (compared to slices, audio, video, etc.), thus completing the maintenance of multimedia data. Of course we can not use the database of these systems, for example, if we want to get all the songs, we can scan all the files on the SD folder, and then according to the file suffix, we can take the MP3, WMA files and so on. However, this kind of operation is very inefficient, so it is not feasible.

Android system for us to build a multimedia database, then the multimedia commonly used information, such as song name, file size, play length, album, singer and other commonly used information stored in the database, we can directly use the data in the multimedia library to complete this demand. Although we need to use the multimedia library, but we can not directly operate. Android has created ContentProvider for these commonly used data that needs to be shared (multimedia and contacts, etc.), so if we want to get this information, we need to use ContentProvider.

Before you begin, give the entity class of the song you need to use first

/** * * @ClassName: Com.example.mediastore.Song * @Description: Song entity class * @author Zhaokaiqiang * @date 2014-12-4 11:49:59 * */public class Song {private string filename;private string title;private int duration;private string Singer;private S Tring album;private String Year;private string type;private string size;private string Fileurl;public string GetFileName ( {return fileName;} public void Setfilename (String fileName) {this.filename = FileName;} Public String GetTitle () {return title;} public void Settitle (String title) {this.title = title;} public int getduration () {return duration;} public void setduration (int duration) {this.duration = duration;} Public String Getsinger () {return singer;} public void Setsinger (String singer) {this.singer = singer;} Public String Getalbum () {return album;} public void Setalbum (String album) {this.album = album;} Public String GetYear () {return year;} public void Setyear (String year) {this.year = year;} Public String GetType () {return type;} public void SettyPE (String type) {this.type = type;} Public String GetSize () {return size;} public void SetSize (String size) {this.size = size;} Public String Getfileurl () {return fileUrl;} public void Setfileurl (String fileUrl) {this.fileurl = FILEURL;} Public Song () {super ();} Public Song (String fileName, string title, Int. Duration, String singer,string Album, string year, String type, string size , String FileUrl) {super (); this.filename = Filename;this.title = Title;this.duration = Duration;this.singer = Singer;this . album = Album;this.year = Year;this.type = Type;this.size = Size;this.fileurl = FileUrl;}  @Overridepublic String toString () {return "Song [filename=" + FileName + ", title=" + title+ ", duration=" + Duration + ", Singer= "+ singer +", album= "+ album +", year= "+ year +", type= "+ Type +", size= "+ size +", "fileurl=" + FileUrl + "]";}}

with this information above, we can make a player completely!

With the entity class, I encapsulated a class that was specifically used to get the song information, and here's the implementation code

/** * * @ClassName: Com.example.mediastore.AudioUtils * @Description: Audio file Help class * @author Zhaokaiqiang * @date 2014-12-4 morning 11:39:45 * */public class Audioutils {/** * get all music files for SD card * * @return * @throws Exception */public static Arraylist<so Ng> getallsongs (context context) {arraylist<song> songs = null; cursor cursor = context.getcontentresolver (). Query (Mediastore.audio.media.external_content_uri,new string[] { Mediastore.audio.media._id,mediastore.audio.media.display_name,mediastore.audio.media.title, Mediastore.audio.media.duration,mediastore.audio.media.artist,mediastore.audio.media.album, Mediastore.audio.media.year,mediastore.audio.media.mime_type,mediastore.audio.media.size, MediaStore.Audio.Media.DATA},mediastore.audio.media.mime_type + "=? or "+ MediaStore.Audio.Media.MIME_TYPE +" =? ", new string[] {" Audio/mpeg "," audio/x-ms-wma "}, null); songs = new ArrayList <Song> (); if (Cursor.movetofirst ()) {Song song = null;do {song = new song ();//filename song.setfilename (cursor.GetString (1));//Song Name Song.settitle (cursor.getstring (2));//Duration Song.setduration (Cursor.getint (3));// Singer Name Song.setsinger (cursor.getstring (4));//Album Name Song.setalbum (Cursor.getstring (5));//Age if (cursor.getstring (6)! = NULL) {Song.setyear (cursor.getstring (6));} else {song.setyear ("Unknown");} The song format if ("Audio/mpeg". Equals (Cursor.getstring (7). Trim ())) {Song.settype ("MP3");} else if ("audio/x-ms-wma". Equals ( Cursor.getstring (7). Trim ())) {Song.settype ("WMA");} File size if (cursor.getstring (8) = null) {Float size = Cursor.getint (8)/1024f/1024f;song.setsize ((Size + ""). Substring ( 0, 4) + "M");} else {song.setsize ("Unknown");} File path if (cursor.getstring (9)! = null) {Song.setfileurl (cursor.getstring (9));} Songs.add (song);} while (Cursor.movetonext ()); Cursor.close ();} return songs;}}

the idea of the code is simple, we need to get a cursor based on contentresover, and then iterate through all of the song's information based on this cursor. In the above code, we have found a total of 10 data including song name, path, file size, etc., which is sufficient for the general application. After querying, we convert the information into entity classes, which makes it easier to operate.

If you want to use this tool class, remember to add permissions <uses-permission android:name= "Android.permission.READ_EXTERNAL_STORAGE"/>

(2) How to update the Media Library in time

When the Android system refreshes the data of the Media Library, it is at the time of boot, that is, when the phone is switched on, the system will rescan the SD card and update the multimedia database. If a user deletes an audio file and does not reboot, the data in the database is not updated. So, if we want users to open the software, forcing the update of the multimedia database, what should be done?

Before the 4.4 release, we can force the Media Library to be refreshed by sending a broadcast

Intentfilter intentfilter = new Intentfilter (intent.action_media_scanner_started); Intentfilter.addaction ( intent.action_media_scanner_finished); Intentfilter.adddatascheme ("file"); Sendbroadcast (New Intent (Intent.ACTION _media_mounted,uri.parse ("file://" + environment.getexternalstoragedirectory (). GetAbsolutePath ()));
after you send the broadcast, you also need to register a broadcast recipient to accept and process the scan start and end events
Private class Scanreceiver extends Broadcastreceiver {public void OnReceive (context context, Intent Intent) {String action = Intent.getaction (); When the system starts to scan the SD card, for the user experience, you can add a wait box if (Intent.ACTION_MEDIA_SCANNER_STARTED.equals (ACTION)) {}// When the system scan is complete, stop displaying the wait box and requery Contentproviderif (Intent.ACTION_MEDIA_SCANNER_FINISHED.equals (ACTION)) {}}}

in this way, we can force the Media Library to be updated.

However, after 4.4, Android has increased permissions on some operations, and if you use this method on a 4.4 system, the following error will occur

caused By:java.lang.SecurityException:Permission Denial:not allowed to send broadcast android.intent.action.MEDIA_ Mounted from pid=22360, uid=10163

this is because after 4.4, this broadcast can only be issued by the system application, so we can't use this method, we could use the following code to achieve the same function:

Mediascannerconnection.scanfile (this, new string[] {environment.getexternalstoragedirectory (). GetAbsolutePath ()}, NULL, NULL);

Using Mediascannerconnection's Scanfile method, we can force scan the file path we need to update, and then the media database will be updated synchronously, so that there will be no file deletion, in the Media Library can search for the situation, can also solve the new song that the friend raised the information acquisition problem.

"Android Development experience" How to get all the audio file information in the library and update the Media Library when the file is deleted or removed

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.