首先,您应该使用没有图像或占位符的通知,然后使用AsyncTask加载位图,或者使用Picasso和Target回调函数。
将您的任务提供给第一个通知所使用的构建器,在位图加载完成后,将其添加到构建器中,然后重新通知您的通知。
如果在完全加载图像之前存在内容已更改的风险,请存储一个标识当前要显示内容的变量,以便在重新通知之前进行检查。
您可以参考Google提供的MediaNotificationManager示例,UniversalMusicPlayer项目。
在您的情况下:
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Some Title");
builder.setContentText("Some Content Text");
builder.setContentIntent(pendingIntent);
manager.notify(NOTIFICATION_ID, builder.build());
currentLoadImageTask = new LoadImageTask(manager, builder);
currentLoadImageTask.execute("https://graph.facebook.com/YOUR_USER_ID/picture?type=large");
static class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
final NotificationManager manager;
final NotificationCompat.Builder builder;
public LoadImageTask(final NotificationManager manager, final NotificationCompat.Builder builder) {
this.manager = manager;
this.builder = builder;
}
@Override
protected Bitmap doInBackground(final String... strings) {
if (strings == null || strings.length == 0) {
return null;
}
try {
final URL url = new URL(strings[0]);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
final InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(final Bitmap bitmap) {
if (bitmap == null || manager == null || builder == null) {
return;
}
builder.setLargeIcon(bitmap);
manager.notify(NOTIFICATION_ID, builder.build());
}
}
使用 Picasso:
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Some Title");
builder.setContentText("Some Content Text");
builder.setContentIntent(pendingIntent);
manager.notify(NOTIFICATION_ID, builder.build());
Picasso.with(context)
.load("https://graph.facebook.com/YOUR_USER_ID/picture?type=large")
.resize(250, 250)
.into(new Target() {
@Override
public void onBitmapLoaded(final Bitmap bitmap, final Picasso.LoadedFrom from) {
builder.setLargeIcon(bitmap);
manager.notify(NOTIFICATION_ID, builder.build());
}
@Override
public void onBitmapFailed(final Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(final Drawable placeHolderDrawable) {
}
});
如果不在UI线程中,你可以创建一个Runnable并在Looper中执行它。
final Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(new Runnable() {
@Override
public void run() {
}
});
使用缓存,Picasso更好。
我强烈建议您调整设置在通知中的每个位图的大小,因为如果不这样做,很容易引发OutOfMemoryException。