Android NotificationListenerService 获取 EXTRA_SMALL_ICON 总是返回 null

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

我正在开发一个应用程序来读取 Android 的 Activity 通知。到目前为止,我一直很成功,直到我无法获得 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

是的,我尝试获取的通知有一个小图标集。我做错什么了吗?还有其他方法可以获取 SMALL_ICON 吗?我不明白为什么。

谢谢!

最佳答案

试试改成这样

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();  
    }

关于Android NotificationListenerService 获取 EXTRA_SMALL_ICON 总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40691584/

相关文章:

java - 在 Java 中将 JSON 解析为字符串时遇到问题

android - 按下 .addAction() 时 BroadcastReceiver 未收到

android - 使用 XML 可绘制的垂直线

android - Chrome 自定义标签更改默认关闭按钮不起作用

java - Android ListView.notifyDataSetChanged 导致不正确的行

android - 禁用库的通知功能

Android 进度条设置级别

android - 如何从可绘制文件夹中的图像获取路径并设置为 ImageView 、位图?

android - 如何使用 Camera 2 API Android 提高拍摄图像的质量?

java - 未收到从通知服务器发送的 GCM 通知