Accedere alle notifiche postate e rimosse nella barra delle notifiche chiedendo i permessi dinamicamente
A partire dall’API Level 18, Android consente di accedere alle notifiche postate nella barra superiore grazie al NotificationListenerService. Attraverso i metodi onNotificationPosted e onNotificationRemoved è possibile essere notificati ogni qualvolta viene postata una nuova notifica e quando viene rimossa. Per poter utilizzare questa funzionalità, l’utente deve necessariamente concedere manualmente i permessi. I permessi posso essere concessi manualmente all’interno delle impostazioni “Suoni e notifiche”:

Cliccando su “Accesso alle notifiche”:

Vediamo dinamicamente come fare:
Definiamo due costanti: la prima serve per verificare se il permesso è garantito; la seconda viene utilizzata per aprire la finestra in cui richiedere il permesso:
private static final String ACTION_NOTIFICATION_LISTENER =
"enabled_notification_listeners";
private static final String ACTION_NOTIFICATION_LISTENER_SETTINGS
= "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS";
Definiamo il metodo checkNotificationListenerPermission in questo modo:
private boolean checkNotificationListenerPermission() {
return Settings.Secure.getString(getActivity().getContentResolver(),
ACTION_NOTIFICATION_LISTENER).contains(
getActivity().getApplicationContext().getPackageName());
}
Il metodo appena creato consente di verificare se il permesso di accesso alla notifiche è stato concesso. In caso negativo, apriremo la finestra in cui poter concedere il permesso.
if (!checkNotificationListenerPermission()) {
// Permission is not granted
Toast.makeText(getActivity().getApplicationContext(),
R.string.notificationPermission,
Toast.LENGTH_SHORT)
.show();
Intent intent = new Intent(ACTION_NOTIFICATION_LISTENER_SETTINGS);
startActivity(intent);
} else {
// Notification access granted, do something
}
Con la notificationPermission definita nel file strings.xml in questo modo: