Glide:获取位图以显示通知
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Glide:获取位图以显示通知相关的知识,希望对你有一定的参考价值。
我试图运行下面的代码来获取封面图像,如果没有找到封面方法返回默认drawable(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$1.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:获取位图以显示通知的主要内容,如果未能解决你的问题,请参考以下文章