【问题标题】:Getting NameNotFoundException when trying to get name of app from StatusBarNotification尝试从 StatusBarNotification 获取应用程序名称时获取 NameNotFoundException
【发布时间】:2021-10-20 17:45:47
【问题描述】:

我正在使用通知侦听器并尝试获取发送通知的应用程序的名称。我尝试使用 PackageManager 类来获取应用程序的名称,但是,每次收到通知时,我都会不断收到 NameNotFoundException。这是我的代码:

public class NotificationListener extends NotificationListenerService {
    private final ArrayList<Integer> postedIds = new ArrayList<>();

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        ArrayList<Integer> connectedThreadNotifications = new ArrayList<>();
        for (BluetoothConnectionThread bluetoothConnectionThread :
                Utils.getCurrentlyRunningThreads()) {
            connectedThreadNotifications.add(bluetoothConnectionThread.getNotificationID());
        }

        if (sbn.getId() != 800 && !connectedThreadNotifications.contains(sbn.getId())) {
            if (!postedIds.contains(sbn.getId())) {
                postedIds.add(sbn.getId());

                HashMap<String, Object> notification = new HashMap<>();
                try {
                    PackageManager packageManager = getApplicationContext().getPackageManager();
                    ApplicationInfo appInfo = packageManager.getApplicationInfo(sbn.getPackageName(), 0);
                    String appName = packageManager.getApplicationLabel(appInfo).toString();
                    notification.put("appName", appName);
                } catch (PackageManager.NameNotFoundException e) {
                    notification.put("appName", "Unknown");
                }
                notification.put("title", sbn.getNotification().extras.get("android.title"));
                notification.put("subText", sbn.getNotification().extras.get("android.subText"));
                notification.put("text", sbn.getNotification().extras.get("android.text"));
                notification.put("infoText", sbn.getNotification().extras.get("android.infoText"));

                Gson gson = new Gson();
                System.out.println(gson.toJson(notification));
            }
        }
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        if (postedIds.contains(sbn.getId())) {
            postedIds.remove((Integer) sbn.getId());
        }
    }

    public void broadcastNotification() {

    }
}

知道如何让它工作吗?

【问题讨论】:

    标签: java android notifications mobile-development


    【解决方案1】:

    刚遇到这个问题,好像Android 11改变了那些API的权限模型,见https://developer.android.com/about/versions/11/privacy/package-visibility

    不幸的是,据我所知,添加此权限是现在获取通知应用名称的唯一方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-21
      • 2014-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多