我正在寻找一种简单的方法来使用Picasso来加载一个显示图标(这是一个远程网页上的URL).在以前版本的应用程序我正在研究这个代码似乎工作:
Bitmap speakerPic = null;
try {
speakerPic = new AsyncTask() {
@Override
protected Bitmap doInBackground(Void... params) {
try {
return Picasso.with(c).load(session.getSpeaker().getPhotoUrl()).get();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute().get(1500,TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
if (speakerPic != null) {
builder.setLargeIcon(speakerPic);
} else {
builder.setLargeIcon(BitmapFactory.decodeResource(c.getResources(),R.drawable.ic_launcher));
}
但现在我每次都得到一个TimeOutException(我回退到res文件夹中的默认图标).我必须使用这个AsyncTask,因为Picasso(/ network)可能不会在UI线程上发生. (虽然我在这里阻止了1.5秒的UI线程..).
我知道Picasso可以处理远程视图,但我不想使用自定义视图来表示我的意见.另外,我找不到一种方法来获取NoticifationIcon的RemoteView.
有没有办法只使用毕加索设置我的通知图标?
我会自己回答这个问题,因为我找到了一个不错的方法,使用Picasso和RemoteViews.经过测试并与Picasso 2.5.2一起使用:
// Default stuff; making and showing notification
final Context context = getApplicationContext();
final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
final Notification notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher) // Needed for the notification to work/show!!
.setContentTitle("Title of notification")
.setContentText("This is the description of the notification")
// Uncomment if you want to load a big picture
//.setStyle(new NotificationCompat.BigPictureStyle())
.build();
final int notifId = 1337;
notificationManager.notify(notifId,notification);
// Get RemoteView and id's needed
final RemoteViews contentView = notification.contentView;
final int iconId = android.R.id.icon;
// Uncomment for BigPictureStyle,Requires API 16!
//final RemoteViews bigContentView = notification.bigContentView;
//final int bigIconId = getResources().getIdentifier("android:id/big_picture",null,null);
// Use Picasso with RemoteViews to load image into a notification
Picasso.with(getApplicationContext()).load("http://i.stack.imgur.com/CE5lz.png").into(contentView,iconId,notifId,notification);
// Uncomment for BigPictureStyle
//Picasso.with(getApplicationContext()).load("http://i.stack.imgur.com/CE5lz.png").into(bigContentView,notification);
//Picasso.with(getApplicationContext()).load("http://i.stack.imgur.com/CE5lz.png").into(bigContentView,bigIconId,notification);