【发布时间】: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