我正在寻找一种使用Picasso加载通知图标(这是远程网页上的URL)的简便方法。在该应用程序的早期版本中,我正在处理此代码似乎可以正常工作:
Bitmap speakerPic = null;
try {
speakerPic = new AsyncTask<Void, Void, Bitmap>() {
@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,因为UI线程上可能不会出现 picasso (/network)。 (尽管我在这里将UI线程阻塞了1.5秒。)。
我知道 picasso 可以处理远程 View ,但是我不想使用自定义 View 进行通知。我也找不到一种方法来获取NoticifationIcon的RemoteView。
有没有一种方法可以仅使用Picasso设置我的通知图标?
最佳答案
我会自己回答问题,因为我找到了使用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, iconId, notifId, notification);
//Picasso.with(getApplicationContext()).load("http://i.stack.imgur.com/CE5lz.png").into(bigContentView, bigIconId, notifId, notification);
关于android - 在通知(图标)中使用 picasso 的最简单方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26888247/