Android NotificationListenerService获取EXTRA_SMALL_ICON总是返回null

问题描述:

我正在开发一个应用程序来读取Android的活动通知。到目前为止,我已经成功了,直到我得到EXTRA_SMALL_ICON。我使用下面的一段代码来检索应用图标和大图标,它们都工作得很好。Android NotificationListenerService获取EXTRA_SMALL_ICON总是返回null

//做工精细

Drawable appIcon = null; 
try { 
    appIcon = getPackageManager().getApplicationIcon(packageName); 
} catch (PackageManager.NameNotFoundException e) { 
    e.printStackTrace(); 
} 

//做工精细

Bitmap largeIcon = null; 
try { 
    largeIcon = (Bitmap) notification.extras.getParcelable(Notification.EXTRA_LARGE_ICON); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

//不工作

Bitmap smallIcon = null; 
    try { 
     smallIcon = (Bitmap) notification.extras.getParcelable(Notification.EXTRA_SMALL_ICON); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

获取SMALL_ICON抛出以下异常。

Key android.icon expected Parcelable but value was a java.lang.Integer. The default value <null> was returned. 
W/Bundle: Attempt to cast generated internal exception: 
java.lang.ClassCastException: java.lang.Integer cannot be cast to android.os.Parcelable 

是的,我试图得到的通知有一个小图标集。我做错了什么,或者有没有其他方法可以访问SMALL_ICON?我无法弄清楚为什么。

谢谢!

+0

小图标作为绘制资源ID不是位图通过后,将其更改为这个

Bitmap smallIcon = null; try { int id = notification.extras.getInt(Notification.EXTRA_SMALL_ICON); } catch (Exception e) { e.printStackTrace(); } 

。通知的构建方式相同。 –

尝试使用这种

String pack = sbn.getPackageName(); 
    Context remotePackageContext = null; 
    Bitmap bmp = null; 
    try { 
     remotePackageContext = getApplicationContext().createPackageContext(pack, 0); 
     Drawable icon = remotePackageContext.getResources().getDrawable(id); 
     if(icon !=null) { 
      bmp = ((BitmapDrawable) icon).getBitmap(); 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
+0

它说不能将int转换为位图。 –

+0

你可以添加你的服务代码请 –

+0

我更新了我的答案,我认为用这种方法你可以从int得到你从额外获得的位图 –