Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 安卓系統媒體庫

安卓系統媒體庫

編輯:關於Android編程

Android系統的媒體文件管理方式:
掃描存儲設備上的公有媒體文件,並使用SQLite數據庫記錄下相關的信息:
一般情況下,系統開機時會發出媒體掃描的廣播,通知掃描程序進行掃描;
開發者開發的應用程序也可以調用掃描器實時掃描;
掃描到的媒體除了會在數據庫中記錄媒體文件的路徑意外,還會記錄下其他的相關信息,例如入庫的時間、修改時間、圖片詳情、歌曲時長等;
Android系統使用的ContentProvider以使得設備上的其他應用程序可以隨時訪問這些媒體數據。
訪問媒體庫:系統中包名為com.android.providers.media的應用程序提供了媒體庫的ContentProvider;
如何訪問媒體庫中的圖片信息

方法:

 

public class MainActivity extends Activity {
    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		ContentResolver cr = getContentResolver();
		Uri uri = Media.EXTERNAL_CONTENT_URI;
		Cursor cursor  = cr.query(uri, null, null, null, null);
		for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
			String path,display;
			long date;
			int size,width,height;
			path = cursor.getString(cursor.getColumnIndex(Media.DATA));
			display = cursor.getString(cursor.getColumnIndex(Media.DISPLAY_NAME));
			date = cursor.getLong(cursor.getColumnIndex(Media.DATE_TAKEN));
			size = cursor.getInt(cursor.getColumnIndex(Media.SIZE));
			width = cursor.getInt(cursor.getColumnIndex("width"));
			
			height = cursor.getInt(cursor.getColumnIndex("height"));
			System.out.println("--------------------------");
			System.out.println("path = " + path);
			System.out.println("display = " + display);
			System.out.println("date = " + new Date(date));
			System.out.println("size = " + size);
			System.out.println("width = " + width);
			System.out.println("height = " + height);
		}
    }
}

顯示媒體庫中的圖片
在顯示媒體庫中的圖片時,容易因為圖片大小不一致而引發一下OOM的錯誤


OOM解決方案
在一次性加載(無視是在主線程或子線程)大量數據時容易導致OOM(Out if Memory Error);
在加載圖片時出現OOM,可以試著使用以下的解決方法:
在使用BitmapFactory類decode圖片時,設置Options參數,將圖片縮小顯示;
使用Thumbnails生成縮略圖的Bitmap對象在顯示;
核心代碼:

 

Image:

 

	      public class Image {
	private String path;
	private String display;
	private long date;
	private int size;
	private int width;
	private int height;
	private long id;
	
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public String getDisplay() {
		return display;
	}
	public void setDisplay(String display) {
		this.display = display;
	}
	public long getDate() {
		return date;
	}
	public void setDate(long date) {
		this.date = date;
	}
	public int getSize() {
		return size;
	}
	public void setSize(int size) {
		this.size = size;
	}
	public int getWidth() {
		return width;
	}
	public void setWidth(int width) {
		this.width = width;
	}
	public int getHeight() {
		return height;
	}
	public void setHeight(int height) {
		this.height = height;
	}
	
}

ImageAdapter:

 

 

         public class ImageAdapter extends BaseAdapter {
	private List
images; public ImageAdapter(List images) { setImages(images); } private void setImages(List images) { if (images == null) { images = new ArrayList(); } this.images = images; } @Override public int getCount() { // TODO Auto-generated method stub return images.size(); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null){ holder = new ViewHolder(); convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.lv_item, null); holder.image = (ImageView)convertView.findViewById(R.id.iv_image); holder.path = (TextView)convertView.findViewById(R.id.tv_item_path); holder.display = (TextView)convertView.findViewById(R.id.tv_item_name); holder.px = (TextView)convertView.findViewById(R.id.tv_item_px); holder.size = (TextView)convertView.findViewById(R.id.tv_item_size); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } Image img = images.get(position); //容易導致OOM問題,Bitmap對象太大 //Bitmap bm = BitmapFactory.decodeFile(img.getPath()); Bitmap bm; // 方法一:自定義方法獲取Bitmap // bm = decodeFile(img); // 方法二:使用Thumbnails bm = Thumbnails.getThumbnail(parent.getContext().getContentResolver(), img.getId(), Thumbnails.MICRO_KIND, null); holder.display.setText(img.getDisplay()); holder.size.setText(img.getSize() / 1024+ "KB"); holder.path.setText(img.getPath()); holder.px.setText(img.getWidth() + " x " + img.getHeight() + "px"); holder.image.setImageBitmap(bm); return convertView; } static final int MAX_WIDTH = 80; static final int MAX_HEIGHT = 80; private Bitmap decodeFile(Image img){ Bitmap bm = null; Options opts = new Options(); int rate; // 未知圖片的寬與高時的做法: opts.inJustDecodeBounds = true; bm = BitmapFactory.decodeFile(img.getPath(),opts); int width = opts.outWidth; int height = opts.outHeight; if(width >height){ rate = height / MAX_HEIGHT - 1; }else{ rate = width / MAX_WIDTH - 1; } opts.inJustDecodeBounds = false; // 當已知圖片的寬與高時,可以使用以下的方法 // if(img.getWidth() > img.getHeight()){ // rate = img.getWidth() / MAX_WIDTH - 1; // }else{ // rate = img.getHeight() / MAX_HEIGHT - 1; // } opts.inSampleSize = rate; bm = BitmapFactory.decodeFile(img.getPath(),opts); return bm; } private class ViewHolder { ImageView image; TextView path, display, px, size; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } }
MainActivity:

 

 

   public class MainActivity extends Activity {
	
	private List
images = new ArrayList(); private ListView listView; private ImageAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); loadImages(); listView = (ListView) findViewById(R.id.lv_images); adapter = new ImageAdapter(images); listView.setAdapter(adapter); } private void loadImages(){ ContentResolver cr = getContentResolver(); Uri uri = Media.EXTERNAL_CONTENT_URI; Cursor cursor = cr.query(uri, null, null, null, null); // Image image = new Image(); for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){ Image image = new Image(); image.setId(cursor.getLong(cursor.getColumnIndex(Media._ID))); image.setPath(cursor.getString(cursor.getColumnIndex(Media.DATA))); image.setDisplay(cursor.getString(cursor.getColumnIndex(Media.DISPLAY_NAME))); image.setDate(cursor.getLong(cursor.getColumnIndex(Media.DATE_TAKEN))); image.setSize(cursor.getInt(cursor.getColumnIndex(Media.SIZE))); image.setWidth(cursor.getInt(cursor.getColumnIndex("width"))); image.setHeight(cursor.getInt(cursor.getColumnIndex("height"))); images.add(image); } cursor.close(); } }
布局:
activity_main:

 

 

         

    

item布局:

 

 



    
    
    
    
        
        
        
        
            
        
    


訪問媒體庫中的音頻 代碼:

 

 

package com.example.lianxi;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Audio.Media;
import android.widget.ListView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// 媒體庫中的音頻所具有的部分字段:
		// _id _data titile_size duration album_artist album album_key
		// ContentResolver Uri
		ContentResolver cr = getContentResolver();
		Uri uri = Media.EXTERNAL_CONTENT_URI;
		Cursor cursor = cr.query(uri, null, null, null, null);
		List musics = new ArrayList();
		Music music;
		for (cursor.moveToFirst(); cursor.isAfterLast(); cursor.moveToNext()) {
			music = new Music();
			music.setId(cursor.getLong(cursor.getColumnIndex(Media._ID)));
			music.setData(cursor.getString(cursor.getColumnIndex(Media.DATA)));
			music.setTitle(cursor.getString(cursor.getColumnIndex(Media.TITLE)));
			music.setArtist(cursor.getString(cursor
					.getColumnIndex(Media.ARTIST)));
			music.setAlbum(cursor.getString(cursor.getColumnIndex(Media.ALBUM)));
			music.setAlbumkey(cursor.getString(cursor
					.getColumnIndex(Media.ALBUM_KEY)));
			music.setSize(cursor.getInt(cursor.getColumnIndex(Media.SIZE)));
			music.setDuration(cursor.getInt(cursor
					.getColumnIndex(Media.DURATION)));
			musics.add(music);
			System.out.println(music.toString());

		}
		cursor.close();
	}
}

測試結果:

 

01-01 13:41:27.514: I/System.out(11445): Music [id=15, data=/storage/emulated/0/Music/Groove Coverage - She.mp3, title=Groove Coverage - She, size=3664535, duration=229033, artist=, album=Music]
01-01 13:41:27.518: I/System.out(11445): Music [id=16, data=/storage/emulated/0/Music/number2.mp3, title=number2, size=3664535, duration=229033, artist=, album=Music]
01-01 13:41:27.530: I/System.out(11445): Music [id=17, data=/storage/emulated/0/Music/number3.mp3, title=Can't Get You Out Of My Head, size=3681031, duration=230016, artist=Kylie Minogue, album=Can't Get You Out of My Head [UK CD]]
01-01 13:41:27.530: I/System.out(11445): Music [id=18, data=/storage/emulated/0/Music/number1.mp3, title=number1, size=4727537, duration=295471, artist=, album=Music]

使用媒體庫做出的獲取音樂信息

與獲取圖片類似

MusicAdapter:

 

public class MusicAdapter extends BaseAdapter{

	private List musics;
	public MusicAdapter(List musics){
		setMusics(musics);
	}
	public void setMusics(List musics){
		if(musics == null){
			musics = new ArrayList();
		}
		this.musics = musics;
	}
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return musics.size();
	}

	private class ViewHolder{
		ImageView image;
		TextView title,duration,artist,album;
	}
	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ViewHolder holder;
		if(convertView == null){
			convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.lv_item, null);
			holder = new ViewHolder();
			holder.image = (ImageView) convertView.findViewById(R.id.iv_image);
			holder.title = (TextView) convertView.findViewById(R.id.tv_item_title);
			holder.duration = (TextView) convertView.findViewById(R.id.tv_item_time);
			holder.artist = (TextView) convertView.findViewById(R.id.tv_item_artist);
			holder.album = (TextView) convertView.findViewById(R.id.tv_item_name);
		    convertView.setTag(holder);
		}else{
			holder = (ViewHolder) convertView.getTag();
		}
		Music music = musics.get(position);
		
		holder.title.setText(music.getTitle());
		holder.duration.setText(formatDuration(music.getDuration()));
		holder.artist.setText(music.getArtist());
		holder.album.setText(music.getAlbum());
		
		if(music.getImagePath() == null){
			
		}else{
			holder.image.setImageBitmap(BitmapFactory.decodeFile(music.getImagePath()));
		}
		
		return convertView;
	}
	private String formatDuration(int duration){
		return new SimpleDateFormat("mm:ss",Locale.CHINA).format(new Date(duration));
	}

}

 

Music:

 

public class Music {
      private long id;
      private String data;
      private String title;
      private int size;
      private int duration;
      private String artist;
      private String album;
      private String albumkey;
      private String imagePath;
      
	public String getImagePath() {
		return imagePath;
	}
	public void setImagePath(String imagePath) {
		this.imagePath = imagePath;
	}
	public String getArtist() {
		return artist;
	}
	public void setArtist(String artist) {
		this.artist = artist;
	}
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getData() {
		return data;
	}
	public void setData(String data) {
		this.data = data;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public int getSize() {
		return size;
	}
	public void setSize(int size) {
		this.size = size;
	}
	public int getDuration() {
		return duration;
	}
	public void setDuration(int duration) {
		this.duration = duration;
	}
	public String getAlbum() {
		return album;
	}
	public void setAlbum(String album) {
		this.album = album;
	}
	public String getAlbumkey() {
		return albumkey;
	}
	public void setAlbumkey(String albumkey) {
		this.albumkey = albumkey;
	}
	@Override
	public String toString() {
		return "Music [id=" + id + ", data=" + data + ", title=" + title
				+ ", size=" + size + ", duration=" + duration + ", artist="
				+ artist + ", album=" + album + "]";
	}
	
      
}

MainActivity:

 

 

public class MainActivity extends Activity {
	
	private List musics;
	private ListView listView;
	private MusicAdapter adapter;
	private Uri uri;
	private Cursor cursor;
	private ContentResolver cr;
    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		loadMusic();
		listView = (ListView) findViewById(R.id.lv_images);
		adapter = new MusicAdapter(musics);
		listView.setAdapter(adapter);
	
    }
    private void loadMusic(){
    	cr = getContentResolver();
		uri = Media.EXTERNAL_CONTENT_URI;
		cursor = cr.query(uri, null, null, null, null);
       musics = new ArrayList();
       for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
    	   Music music = new Music();
    	   music.setId(cursor.getLong(cursor.getColumnIndex(Media._ID)));
    	   music.setData(cursor.getString(cursor.getColumnIndex(Media.DATA)));
    	   music.setTitle(cursor.getString(cursor.getColumnIndex(Media.TITLE)));
    	   music.setArtist(cursor.getString(cursor.getColumnIndex(Media.ARTIST)));
    	   music.setAlbum(cursor.getString(cursor.getColumnIndex(Media.ALBUM)));
    	   music.setAlbumkey(cursor.getString(cursor.getColumnIndex(Media.ALBUM_KEY)));
    	   music.setSize(cursor.getInt(cursor.getColumnIndex(Media.SIZE)));
    	   music.setDuration(cursor.getInt(cursor.getColumnIndex(Media.DURATION)));
    	   System.out.println(music.toString());
    	   Uri imageUri = Albums.EXTERNAL_CONTENT_URI;
    	   String[] projection = new String[] {Albums.ALBUM_ART};
		String selection = Albums.ALBUM_KEY + "=?";
		String[] selectionArgs = new String[] {music.getAlbumkey()};
		Cursor imageCursor = cr.query(imageUri, projection, selection, selectionArgs, null);
    	if(imageCursor.moveToFirst()){
    		music.setImagePath(imageCursor.getString(0));
    	}
		musics.add(music);  
    	   
       }
       cursor.close();
    }
}

布局與獲取照片信息布局類似,這裡不再貼出代碼

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved