Android--通过ContentResolver取得com.android.providers.media下的media信息

java文件:

package cn.mrzhu.media;

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.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;

/**
 * 通过ContentResolver取得com.android.providers.media下的media信息
 * @author ZLQ
 *
 */
public class TestMedia extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.media);
	}

	/**
	 * show按钮,点击按钮打印输出文件的标题,演唱者和专辑
	 * @param v
	 */
	public void show(View v) {
		//指定到com.android.providers.media下的external_XXXdb,即存储卡数据库
		Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
		//audio_meta表的里_id,即文件的id
		String _ID = MediaStore.Audio.Media._ID;
		//audio_meta表的里title,即文件的标题
		String TITLE = MediaStore.Audio.Media.TITLE;
		//artist表的里artist_id,即演唱者的id
		String ARTIST_ID = MediaStore.Audio.Media.ARTIST_ID;
		//artist表的里artist_id,即演唱者的信息
		String ARTIST = MediaStore.Audio.Media.ARTIST;
		//album表的里album_id,即专辑的id
		String ALBUM_ID = MediaStore.Audio.Media.ALBUM_ID;
		//album表的里album_id,即专辑的信息
		String ALBUM = MediaStore.Audio.Media.ALBUM;
		//取得内容解析对象
		ContentResolver cr = getContentResolver();
		//调用query开始解析数据,返回一个Cursor结果集
		Cursor cs = cr.query(uri, null, null, null, null);
		while (cs.moveToNext()) {
			//取得audio_meta表的里_id
			String meta_id = cs.getString(cs.getColumnIndex(_ID));
			//取得audio_meta表的里title
			String title = cs.getString(cs.getColumnIndex(TITLE));
			//用条件ARTIST_ID + "=" + meta_id + " and " + ALBUM_ID + "=" + meta_id
			//从artist表和album表中找到与audio_meta表_id相对应的信息
			Cursor c = cr.query(uri, null, ARTIST_ID + "=" + meta_id + " and " + ALBUM_ID + "=" + meta_id, null, null);
			while(c.moveToNext()){
				//打印输出文件的标题,演唱者和专辑
				Log.i("System.out","title    " + title + "   artist  " + c.getString(c.getColumnIndex(ARTIST))
					+ "   album   " + c.getString(c.getColumnIndex(ALBUM)));
			}
		}
	}

	/**
	 * scan按钮,点击按钮给系统发送广播,搜索sdcard卡下的所有音乐文件并更新数据库
	 * @param v
	 */
	public void scan(View v) {
		Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED,
				Uri.parse("file://"
						+ Environment.getExternalStorageDirectory()
						.getAbsolutePath()));
		sendBroadcast(intent);
	}
}


 

media.xml文件:




    

    


 

 

你可能感兴趣的:(Android)