2013-04-17 31 views
12

我从服务器下载一个图像作为位图并将其转换为drawable,现在我想将此drawable用作通知图标。但我无法做到这一点。这里是我的代码:将Drawable或Bitmap设置为Android中的通知图标

Notification notification = new NotificationCompat.Builder(context) 

    .setContentTitle(title) 

    .setContentText(message) 

    .setContentIntent(intent) 

    .setSmallIcon(bitmap) 

    .setWhen(when) 

    .build(); 

但图标是一个资源的int值,所以当我使用它会给出错误。任何帮助

编辑:

现在更新我的代码和我现在所做的那样:

  Notification notification = new NotificationCompat.Builder(context) 

     .setContentTitle(title) 

     .setContentText(message) 

     .setContentIntent(intent) 

     .setSmallIcon(icon) 

     .setLargeIcon(bitmap) 

     .setWhen(when) 

     .build(); 

,但它给出了左侧的小图标右侧的大图标。我不希望这所以为了这个,我删除setSmallIcon线和运行我的代码,但它不显示我的通知

+1

http://stackoverflow.com/a/16051724/931982 ...我在这里回答 – stinepike

+0

谢谢@StinePike看到我编辑的问题 – User42590

+0

哈哈由于某种原因,我不知道为什么..在右侧的小图标称为大图标..只有在那里你可以设置位图。在更高的api中,您可以使用自定义布局 – stinepike

回答

21

如果你读特定Notification.Builder开发文档,你会看到setSmallIcon(int icon)需要在一个资源ID应用程序的可绘制包使用

下载图像,转换为位图,然后将其设置为setSmallIcon()仍然会给你一个错误。

即使你要转换BitmapDrawable这样的,例如:

Drawable d = new BitmapDrawable(getResources(), bmpFinal); 

它仍然想给你一个错误,因为那Drawable不是在你的应用程序包存在

唯一可能的解决方案是使用package中存在的Drawable资源,并将其设置为setSmallIcon()方法。典型用法:

builder.setSmallIcon(R.drawable.ic_launcher); 

或者,setLargeIcon (Bitmap icon)需要一个位图实例。无需对当前代码进行任何其他更改(因为您已有Bitmap),如果它符合您的要求,则可以使用它。

如果不是,则几乎必须使用Drawable资源,该资源已存在于drawable文件夹之一中。

+5

'setLargeIcon(位图)'不适合我btw。 – m0skit0

6

有关于这个问题,主要是与API 23+相关的,如果你只在setSmallIcon感兴趣的一些点,到2楼和第三个主题。

1:

您可以从一个绘制对象(而不是资源ID)设置LargeIcon,像下面

Drawable drawable= ContextCompat.getDrawable(this,R.drawable.your_drawable); 

      Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap(); 

      NotificationCompat.Builder mBuilder = 
        new NotificationCompat.Builder(context) 
          .setLargeIcon(bitmap) 
          .setContentTitle("hahah") 
          .setContentText("Tap to stop") 
          .setOngoing(true); 

第二:

如果您需要在API设置SmallIcon低于23,您需要设置一个资源ID,如R.drawable.your_resource。 NotificationCompat.Builder不允许您使用Drawable s or Bitmaps in setSmallIcon()`。

3:

幸运的是,支持已经在23+版本扩大到Icon类型上setSmallIcon(),使用Notification.Builder,像以下:

Drawable drawable = ContextCompat.getDrawable(this,R.drawable.your_drawable); 

      Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap(); 

      Notification.Builder mBuilder = 
        new Notification.Builder(context) 
          .setSmallIcon(Icon.createWithBitmap(bitmap)) 
          .setLargeIcon(bitmap) 
          .setContentTitle("hahah") 
          .setContentText("Tap to stop") 
          .setOngoing(true); 
+1

感谢您的最后一个,即使仍然没有旧版本的解决方案..好好知道反正 – Jenix

1

更好的选择,让应用程序图标

Drawable drawable=getApplicationInfo().loadIcon(getPackageManager()); 
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap(); 



.setSmallIcon(getApplicationInfo().icon) 
.setLargeIcon(bitmap)