I am using a notification listener and trying to get the name of the app that sent the notification. I tried using the PackageManager class to get the name of the app, however, I keep getting a NameNotFoundException every time I get a notification. Here is my code:
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() {
}
}
Any idea how I can get this to work?