Glide:获取位图以显示通知

Glide: fetch Bitmap to show notification

我正在尝试 运行 下面的代码来获取封面图像,如果找不到封面,方法 returns 默认可绘制对象 (R.drawable.no_cover)。

private Bitmap getCoverImage(final Song song) {
    Bitmap bitmap;
    final Uri uri = ContentUris.withAppendedId(Utilities.sArtworkUri, song.getAlbumId());
        try {
            bitmap = Glide.with(service)
                .load(uri)
                .asBitmap()
                .into(256, 256)
                .get();
        } catch (InterruptedException | ExecutionException e) {
            bitmap = BitmapFactory.decodeResource(service.getResources(), R.drawable.no_cover);
        }
    return bitmap;
}

但是我收到错误消息(记录在下方)。我应该为此创建新线程吗??

07-17 08:25:30.508 21095-21095/com.example.app E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.app, PID: 21098
    java.lang.IllegalArgumentException: YOu must call this method on a background thread
        at com.bumptech.glide.util.Util.assertBackgroundThread(Util.java:144)
        at com.bumptech.glide.request.RequestFutureTarget.doGet(RequestFutureTarget.java:169)
        at com.bumptech.glide.request.RequestFutureTarget.get(RequestFutureTarget.java:100)
        at com.example.app.notification.PlayerNotification.run(PlayerNotification.java:151)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

因为您需要此 Bitmap 来显示通知,这意味着您必须先获取位图,然后再实际显示通知。

这是一个AsyncTask实现,可能对您有帮助:

public class TestActivity extends Activity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new MyAsyncTask(getApplicationContext(), "some url").execute();
    }

    private static class MyAsyncTask extends AsyncTask<Void, Void, Bitmap> {

        private Context context;
        private String url;

        MyAsyncTask(Context context, String url) {
            this.context = context;
            this.url = url;
        }

        @Override
        protected Bitmap doInBackground(Void... params) {
            try {
                return Glide.with(context)
                        .load(url)
                        .asBitmap()
                        .into(256, 256)
                        .get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);

            if (null != bitmap) {
                // show notification using bitmap
            } else {
                // couldn't fetch the bitmap
            }
        }
    }
}

Glide 的大部分 API 和方法现已弃用。下面是使用 Glide 4.9 和高达 Android 10.

由于图像是从互联网加载的,因此它应该始终处于异步调用或后台线程中。您可以使用异步任务或图像加载库,例如 Glide。

要从 url 加载图像通知,您可以使用样式 "NotificationCompat.BigPictureStyle()"。这需要一个位图(必须从图像中提取url)

显示一次图像通知,位图准备就绪。

您可以覆盖默认的错误 Glide 方法来显示 R.drawable.no_cover

// Load bitmap from image url on background thread and display image notification
    private void getBitmapAsyncAndDoWork(String imageUrl) {

        final Bitmap[] bitmap = {null};

        Glide.with(getApplicationContext())
                .asBitmap()
                .load(imageUrl)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

                        bitmap[0] = resource;
                        // TODO Do some work: pass this bitmap
                        displayImageNotification(bitmap[0]);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                    }
                });
    }