在Android中获取专辑封面的最强大方法

Ani*_*Ani 4 java android albumart

请注意,我已经在这里和其他网站上遇到了类似的问题和答案.我也有一个适用于某些设备的解决方案(我的G2X运行CyanogenMod 7.1,我妻子的HD2运行自定义ROM,运行Android 2.1的模拟器).然而,它并没有在我的Nook上运行CyanogenMod.

我的问题是:在所有Android设备上获取专辑封面的最强大和最通用的方法是什么?对于特定设备,版本或音乐应用程序有什么问题(我不是指第三方播放器,我的意思是Google音乐与旧音乐客户端)?我目前的代码是:

// Is this what's making my code fail on other devices?
public final Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");

// This works, and well on all devices
private int[] getAlbumIds(ContentResolver contentResolver)
{
    List<Integer> result = new ArrayList<Integer>();
    Cursor cursor = contentResolver.query(MediaStore.Audio.Media.getContentUri("external"), new String[]{MediaStore.Audio.Media.ALBUM_ID}, null, null, null);

    if (cursor.moveToFirst())
    {
        do{
            int albumId = cursor.getInt(0);
            if (!result.contains(albumId))
                result.add(albumId);
        } while (cursor.moveToNext());
    }

    int[] resultArray = new int[result.size()];
    for (int i = 0; i < result.size(); i++)
        resultArray[i] = result.get(i);

    return resultArray;
}

// This is the bit I want to make more robust, make sure that it works on all devices
private Shader getAlbumArt(ContentResolver contentResolver, int albumId, int width, int height)
{
    Uri uri = ContentUris.withAppendedId(sArtworkUri, albumId);
    InputStream input = null;
    try {
        input = contentResolver.openInputStream(uri);
        if (input == null)
            return null;

        Bitmap artwork = BitmapFactory.decodeStream(input);
        input.close();
        if (artwork == null)
            return null;

        Bitmap scaled = Bitmap.createScaledBitmap(artwork, width, height, true);
        if (scaled == null)
            return null;

        if (scaled != artwork)
            artwork.recycle();
        artwork = scaled;

        return new BitmapShader(artwork, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

在此先感谢,Ananth

Chi*_*rag 17

在这里,我可以附加一个功能,即从媒体商店返回专辑封面.在功能中我们只需要传递从Media store获得的album_id.

   public Bitmap getAlbumart(Long album_id) 
   {
        Bitmap bm = null;
        try 
        {
            final Uri sArtworkUri = Uri
                .parse("content://media/external/audio/albumart");

            Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);

            ParcelFileDescriptor pfd = context.getContentResolver()
                .openFileDescriptor(uri, "r");

            if (pfd != null) 
            {
                FileDescriptor fd = pfd.getFileDescriptor();
                bm = BitmapFactory.decodeFileDescriptor(fd);
            }
    } catch (Exception e) {
    }
    return bm;
}
Run Code Online (Sandbox Code Playgroud)