Detailed information about music files in Android [Android source code analysis 2]

Source: Internet
Author: User
Tags file url sqlite database

Some time ago, I processed Android music file information. I checked online and found that the Android system provided mediascanner, mediaprovider, mediastore, and other interfaces and provided a set of database tables, share content to users through content provider. Description: [Android data is private] data can be shared through the content provider method. I have introduced this content provider in general, and the contentprovider introduction in Android [Android Evolution ]. When a mobile phone is turned on or has SD card plugging or removal, the system will automatically scan the media files on the SD card and mobile phone memory, such
Audio, video, and images are stored in the defined database table. If the phone memory card is not plugged in, if the corresponding music files are deleted or moved to another folder, the system will not automatically scan the phone memory card. The queried cursor object exists, but cursor. the value of getcount () is 0. In this program, we do not need to worry about how to scan files in the mobile phone, as long as we know how to query and use this information. Mediastore defines a series of data tables. (This data table is created by the Android system. We don't have to worry about how to create it. We just need to know how to use it !) Through the query interface provided by contentresolver, we can obtain various required information.

First, let's take a look at the contentresolver query interface, which is the same as the SQLite database query method.

Query (URI Uri, string [] projection, string selection, string [] selectionargs, string sortorder); to obtain a cursor object, the cursor object contains information about the music corresponding to the database field:

Uri: specify the name of the database to be queried and the name of the table. From mediastore, we can find the parameters for the corresponding information. For details, refer to the development documentation.
Projection: Specifies the columns in the database table to be queried. The returned cursor contains the corresponding information. Null returns all information.
Selection: Specify query Conditions
Selectionargs: Which of the following are in the selection parameter? This symbol is used to replace the question mark with the actual value. If selection does not exist? Then, the string array can be null.
Sortorder: Specify the order of query results
The following command returns information about all music files on the external memory card:

First obtain a contentresolver object: contentresolver Cr = This. getcontentresolver ();

Cursor cursor = Cr. Query (mediastore. Audio. Media. external_content_uri, null,
Null, null, mediastore. Audio. Media. default_sort_order); after obtaining the cursor, we can call the specific music information of the cursor method:


Song ID: mediastore. Audio. Media. _ id
Int id = cursor. getint (cursor. getcolumnindexorthrow (mediastore. Audio. Media. _ id ));

Song name: mediastore. Audio. Media. Title
String tilte = cursor. getstring (cursor. getcolumnindexorthrow (mediastore. Audio. Media. Title ));

Album name: mediastore. Audio. Media. Album
String album = cursor. getstring (cursor. getcolumnindexorthrow (mediastore. Audio. Media. album ));

Artist name: mediastore. Audio. Media. Artist
String artist = cursor. getstring (cursor. getcolumnindexorthrow (mediastore. Audio. Media. Artist ));

Path of the song file: mediastore. Audio. Media. Data
String dataurl = cursor. getstring (cursor. getcolumnindexorthrow (mediastore. Audio. Media. Data ));

Total playback duration of a song: mediastore. Audio. Media. Duration
Int duration = cursor. getint (cursor. getcolumnindexorthrow (mediastore. Audio. Media. duration ));

Size of the song file: mediastore. Audio. Media. Size
Long size = cursor. getlong (cursor. getcolumnindexorthrow (mediastore. Audio. Media. Size ));

The following shows the small program I wrote:

 


Program start interface: click the button interface:

 

Click the UI after selecting a track: Click the interface after the love song:

 

The code below: Under the icationicationactivity Project

The notificationactivity. Java code under the com.cn. Daming package:

package com.cn.daming;import android.app.Activity;import android.content.ContentResolver;import android.content.Intent;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.provider.MediaStore;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class NotificationActivity extends Activity {private  Button mButton2;private TextView textview3;private static final int MUSIC_PICKED = 3;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        textview3 = (TextView)findViewById(R.id.textview3);        mButton2 = (Button)findViewById(R.id.button2);        mButton2.setOnClickListener(new OnClickListener(){public void onClick(View v) {Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT);        innerIntent.setType("audio/*");//        innerIntent.setType("audio/mp3");//        innerIntent.setType("audio/midi");        Intent wrapperIntent = Intent.createChooser(innerIntent, null);        startActivityForResult(wrapperIntent, MUSIC_PICKED);}        });    }@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (resultCode != RESULT_OK) {              return;          } else {              String mCustomRingtone = null;        if(requestCode == MUSIC_PICKED){        Uri pickedUri = data.getData();               if (pickedUri != null)               {               mCustomRingtone = pickedUri.toString();               ContentResolver cr = this.getContentResolver();               Cursor cursor = cr.query(pickedUri, null, null, null, null);                cursor.moveToFirst();               String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));                String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));               String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));               int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));                 long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));               textview3.setText("mCustomRingtone:"+mCustomRingtone+               "\n\n pickedUri.getPath()=" +pickedUri.getPath() +                "\n\n file url ="+url+               "\n\n file title="+title+               "\n\n file singer = "+artist+               "\n\n music duration="+duration+               "\n\n file size="+size);               }else{               textview3.setText("null:");               }       }        }}}

 

Code in Main. XML in the layout package:

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent"> <textview Android: id = "@ + ID/textview" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: gravity = "center_horizontal" Android: layout_margintop = "20dip" Android: TEXT = "@ string/Hello"/> <button Android: Id = "@ + ID/button2" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: layout_margintop = "20dip" Android: text = "call Memory Card ringtones"/> <textview Android: Id = "@ + ID/textview3" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: layout_margintop = "20dip"/> </linearlayout>

 

Code in string. xml under Res:

<? XML version = "1.0" encoding = "UTF-8"?> <Resources> <string name = "hello"> Daming original, music Information </string> <string name = "app_name"> icationicationapp </string> </resources>
If you have any questions, please leave a message. You are welcome to comment to correct the mistakes!

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.