Android Media Scan需要太长时间

时间:2016-07-06 09:36:32

标签: java android media android-mediascanner

我将以下代码用于设备上的scan all media/mp3文件,但设备上有大量音乐时需要很长时间。

我想知道是否有更快的方式来获取和展示所有音乐?

注意:代码不会导致崩溃或挂断或任何其他事情......

class GetLocals extends AsyncTask<Void,Void,Void> {

  @Override
  protected void onPreExecute() {
    super.onPreExecute();
    SongCover_lc.clear();
    SongID_lc.clear();
    Singer_lc.clear();
    Path_lc.clear();
    AlbumName_lc.clear();
    SongName_lc.clear(); 
  }

  @Override
  protected Void doInBackground(Void... voids) {

    try {
      String[] STAR = {"*"};
      Cursor cursor;
      Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
      String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

      cursor = context.getContentResolver().query(uri, STAR, selection, null, null);

      if (cursor != null) {
        if (cursor.moveToFirst()) {
          do {
            String songName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            String albumName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
            String singer = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            String songid = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));

            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            mmr.setDataSource(path);
            byte[] artBytes = mmr.getEmbeddedPicture();
            if (artBytes != null) {
              InputStream is = new ByteArrayInputStream(mmr.getEmbeddedPicture());
              Bitmap bm = BitmapFactory.decodeStream(is);
              SongCover_lc.add(bm);
            } else {
              SongCover_lc.add(BitmapFactory.decodeResource(getResources(), R.color.white));
            }

            SongName_lc.add(songName);
            AlbumName_lc.add(albumName);
            Path_lc.add(path);
            Singer_lc.add(singer);
            SongID_lc.add(songid);

          } while (cursor.moveToNext());
        }
      }
    } catch (Exception e){
      System.out.println("CAAAAAAAAAAATCH");
    }
    return null;
  }

  @Override
  protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    lazyAdapter_localSongs = new LazyAdapter_LocalSongs(activity,SongName_lc,Singer_lc,SongCover_lc,AlbumName_lc,Path_lc);
    listviewloclas.setAdapter(lazyAdapter_localSongs);
  }
}

1 个答案:

答案 0 :(得分:0)

> I was wondering if there is a faster way to get 
> and show all musics ...

将基于数组的适配器替换为CursorAdapter,以便按需加载歌曲。

因此,在列表视图/网格变为可用之前,不要将1000首歌曲预先加载到数组中,而只需加载一次可见的10首歌曲。