Android media library

Source: Internet
Author: User

Android media library
Media File Management in Android:
Scan the public media files on the storage device and use the SQLite database to record related information:
Generally, when the system is turned on, a media scan broadcast is sent to notify the scanner to scan;
Applications developed by developers can also call scanners for real-time scanning;
In addition to recording the path of the media file in the database, the scanned media file records other related information, for example, warehouse receiving time, modification time, image details, and song duration;
The ContentProvider used by the Android system allows other applications on the device to access the media data at any time.
Access the media Repository: The application named com. android. providers. media in the system provides the ContentProvider of the media repository;
How to access image information in the library

Method:

 

public class MainActivity extends Activity {    @Overrideprotected 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);}    }}

Show images in the media Repository
When displaying images in a media library, OOM errors are easily caused by inconsistent image sizes.


OOM Solution
OOM (Out if Memory Error) is easily caused when a large amount of data is loaded at a time (ignoring the large amount of data in the main thread or sub-thread );
If OOM occurs when an image is loaded, try the following solution:
When BitmapFactory decode image is used, set the Options parameter to narrow down the image display;
The Bitmap object that uses Thumbnails to generate Thumbnails is displayed;
Core code:

 

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); // It is easy to cause OOM problems. The Bitmap object is too large. // Bitmap bm = BitmapFactory. decodeFile (img. getPath (); Bitmap bm; // Method 1: Customize the method to obtain Bitmap // bm = decodeFile (img); // Method 2: Use 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; // when the width and height of an unknown image are high: 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; // when the width and height of an image are known, you can use the following method // 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; 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); // 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 ();}}
Layout:
Activity_main:

 

 

         
     
  
 

Item layout:

 

 

 
         
          
           
            
             
       
        
       
      
     
    
   
  
 

Access the audio code in the media Repository:

 

 

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 {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // audio fields in the Media library: // _ id _ data titile_size duration album_artist album album_key // ContentResolver implements cr = getContentResolver (); Uri uri = Media. EXTERNAL_CONTENT_URI; Cursor cursor = cr. query (uri, 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 ();}}
  
 

Test results:

 

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]

Obtain music information from a media Repository

Similar to Image Retrieval

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;}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn musics.size();}private class ViewHolder{ImageView image;TextView title,duration,artist,album;}@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn null;}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn 0;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {// TODO Auto-generated method stubViewHolder 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;}@Overridepublic 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;    @Overrideprotected 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();    }}
  
 

The layout is similar to the layout for obtaining photo information. No code is provided here.

 

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.