Android NotificationListenerService get EXTRA_SMALL_ICON始终返回null

时间:2016-11-19 10:09:03

标签: android android-notifications android-drawable android-bitmap

我正在开发一款应用来阅读Android的有效通知。到目前为止,我一直很成功,直到我得到了EXTRA_SMALL_ICON。我使用以下代码来检索应用程序图标和大图标,它们都可以正常工作。

//工作正常

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

是的,我试图获得的通知设置了一个小图标。我做错了什么或者有没有其他方法来GT SMALL_ICON?我无法弄清楚原因。

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试将其更改为此

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();  
    }
相关问题