FileDocCategorySizeDatePackage
NotificationListenerService.javaAPI DocAndroid 5.1 API36192Thu Mar 12 22:22:10 GMT 2015android.service.notification

NotificationListenerService

public abstract class NotificationListenerService extends android.app.Service
A service that receives calls from the system when new notifications are posted or removed, or their ranking changed.

To extend this class, you must declare the service in your manifest file with the {@link android.Manifest.permission#BIND_NOTIFICATION_LISTENER_SERVICE} permission and include an intent filter with the {@link #SERVICE_INTERFACE} action. For example:

<service android:name=".NotificationListener"
android:label="@string/service_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>

Fields Summary
private final String
TAG
public static final int
INTERRUPTION_FILTER_ALL
{@link #getCurrentInterruptionFilter() Interruption filter} constant - Normal interruption filter.
public static final int
INTERRUPTION_FILTER_PRIORITY
{@link #getCurrentInterruptionFilter() Interruption filter} constant - Priority interruption filter.
public static final int
INTERRUPTION_FILTER_NONE
{@link #getCurrentInterruptionFilter() Interruption filter} constant - No interruptions filter.
public static final int
HINT_HOST_DISABLE_EFFECTS
{@link #getCurrentListenerHints() Listener hints} constant - the primary device UI should disable notification sound, vibrating and other visual or aural effects. This does not change the interruption filter, only the effects.
public static final int
TRIM_FULL
The full trim of the StatusBarNotification including all its features.
public static final int
TRIM_LIGHT
A light trim of the StatusBarNotification excluding the following features:
  1. {@link Notification#tickerView tickerView}
  2. {@link Notification#contentView contentView}
  3. {@link Notification#largeIcon largeIcon}
  4. {@link Notification#bigContentView bigContentView}
  5. {@link Notification#headsUpContentView headsUpContentView}
  6. {@link Notification#EXTRA_LARGE_ICON extras[EXTRA_LARGE_ICON]}
  7. {@link Notification#EXTRA_LARGE_ICON_BIG extras[EXTRA_LARGE_ICON_BIG]}
  8. {@link Notification#EXTRA_PICTURE extras[EXTRA_PICTURE]}
  9. {@link Notification#EXTRA_BIG_TEXT extras[EXTRA_BIG_TEXT]}
private INotificationListenerWrapper
mWrapper
private RankingMap
mRankingMap
private android.app.INotificationManager
mNoMan
private int
mCurrentUser
Only valid after a successful call to (@link registerAsService}.
private android.content.Context
mSystemContext
public static final String
SERVICE_INTERFACE
The {@link Intent} that must be declared as handled by the service.
Constructors Summary
Methods Summary
private voidapplyUpdate(NotificationRankingUpdate update)

        mRankingMap = new RankingMap(update);
    
public final voidcancelAllNotifications()
Inform the notification manager about dismissal of all notifications.

Use this if your listener has a user interface that allows the user to dismiss all notifications, similar to the behavior of Android's status bar and notification panel. It should be called after the user invokes the "dismiss all" function of your UI; upon being informed, the notification manager will actually remove all active notifications and you will get multiple {@link #onNotificationRemoved(StatusBarNotification)} callbacks. {@see #cancelNotification(String, String, int)}

        cancelNotifications(null /*all*/);
    
public final voidcancelNotification(java.lang.String pkg, java.lang.String tag, int id)
Inform the notification manager about dismissal of a single notification.

Use this if your listener has a user interface that allows the user to dismiss individual notifications, similar to the behavior of Android's status bar and notification panel. It should be called after the user dismisses a single notification using your UI; upon being informed, the notification manager will actually remove the notification and you will get an {@link #onNotificationRemoved(StatusBarNotification)} callback.

Note: If your listener allows the user to fire a notification's {@link android.app.Notification#contentIntent} by tapping/clicking/etc., you should call this method at that time if the Notification in question has the {@link android.app.Notification#FLAG_AUTO_CANCEL} flag set.

param
pkg Package of the notifying app.
param
tag Tag of the notification as specified by the notifying app in {@link android.app.NotificationManager#notify(String, int, android.app.Notification)}.
param
id ID of the notification as specified by the notifying app in {@link android.app.NotificationManager#notify(String, int, android.app.Notification)}.

deprecated
Use {@link #cancelNotification(String key)} instead. Beginning with {@link android.os.Build.VERSION_CODES#LOLLIPOP} this method will no longer cancel the notification. It will continue to cancel the notification for applications whose {@code targetSdkVersion} is earlier than {@link android.os.Build.VERSION_CODES#LOLLIPOP}.

        if (!isBound()) return;
        try {
            getNotificationInterface().cancelNotificationFromListener(
                    mWrapper, pkg, tag, id);
        } catch (android.os.RemoteException ex) {
            Log.v(TAG, "Unable to contact notification manager", ex);
        }
    
public final voidcancelNotification(java.lang.String key)
Inform the notification manager about dismissal of a single notification.

Use this if your listener has a user interface that allows the user to dismiss individual notifications, similar to the behavior of Android's status bar and notification panel. It should be called after the user dismisses a single notification using your UI; upon being informed, the notification manager will actually remove the notification and you will get an {@link #onNotificationRemoved(StatusBarNotification)} callback.

Note: If your listener allows the user to fire a notification's {@link android.app.Notification#contentIntent} by tapping/clicking/etc., you should call this method at that time if the Notification in question has the {@link android.app.Notification#FLAG_AUTO_CANCEL} flag set.

param
key Notification to dismiss from {@link StatusBarNotification#getKey()}.

        if (!isBound()) return;
        try {
            getNotificationInterface().cancelNotificationsFromListener(mWrapper,
                    new String[] {key});
        } catch (android.os.RemoteException ex) {
            Log.v(TAG, "Unable to contact notification manager", ex);
        }
    
public final voidcancelNotifications(java.lang.String[] keys)
Inform the notification manager about dismissal of specific notifications.

Use this if your listener has a user interface that allows the user to dismiss multiple notifications at once.

param
keys Notifications to dismiss, or {@code null} to dismiss all. {@see #cancelNotification(String, String, int)}

        if (!isBound()) return;
        try {
            getNotificationInterface().cancelNotificationsFromListener(mWrapper, keys);
        } catch (android.os.RemoteException ex) {
            Log.v(TAG, "Unable to contact notification manager", ex);
        }
    
public StatusBarNotification[]getActiveNotifications()
Request the list of outstanding notifications (that is, those that are visible to the current user). Useful when you don't know what's already been posted.

return
An array of active notifications, sorted in natural order.

        return getActiveNotifications(null, TRIM_FULL);
    
public StatusBarNotification[]getActiveNotifications(int trim)
Request the list of outstanding notifications (that is, those that are visible to the current user). Useful when you don't know what's already been posted.

hide
param
trim trim of the notifications to be returned. See TRIM_* constants.
return
An array of active notifications, sorted in natural order.

        return getActiveNotifications(null, trim);
    
public StatusBarNotification[]getActiveNotifications(java.lang.String[] keys)
Request one or more notifications by key. Useful if you have been keeping track of notifications but didn't want to retain the bits, and now need to go back and extract more data out of those notifications.

param
keys the keys of the notifications to request
return
An array of notifications corresponding to the requested keys, in the same order as the key list.

        return getActiveNotifications(keys, TRIM_FULL);
    
public StatusBarNotification[]getActiveNotifications(java.lang.String[] keys, int trim)
Request one or more notifications by key. Useful if you have been keeping track of notifications but didn't want to retain the bits, and now need to go back and extract more data out of those notifications.

hide
param
keys the keys of the notifications to request
param
trim trim of the notifications to be returned. See TRIM_* constants.
return
An array of notifications corresponding to the requested keys, in the same order as the key list.

        if (!isBound())
            return null;
        try {
            ParceledListSlice<StatusBarNotification> parceledList = getNotificationInterface()
                    .getActiveNotificationsFromListener(mWrapper, keys, trim);
            List<StatusBarNotification> list = parceledList.getList();

            int N = list.size();
            for (int i = 0; i < N; i++) {
                Notification notification = list.get(i).getNotification();
                Builder.rebuild(getContext(), notification);
            }
            return list.toArray(new StatusBarNotification[N]);
        } catch (android.os.RemoteException ex) {
            Log.v(TAG, "Unable to contact notification manager", ex);
        }
        return null;
    
private android.content.ContextgetContext()

        if (mSystemContext != null) {
            return mSystemContext;
        }
        return this;
    
public final intgetCurrentInterruptionFilter()
Gets the current notification interruption filter active on the host.

The interruption filter defines which notifications are allowed to interrupt the user (e.g. via sound & vibration) and is applied globally. Listeners can find out whether a specific notification matched the interruption filter via {@link Ranking#matchesInterruptionFilter()}.

The current filter may differ from the previously requested filter if the notification host does not support or refuses to apply the requested filter, or if another component changed the filter in the meantime.

Listen for updates using {@link #onInterruptionFilterChanged(int)}.

return
One of the INTERRUPTION_FILTER_ constants, or 0 on errors.

        if (!isBound()) return 0;
        try {
            return getNotificationInterface().getInterruptionFilterFromListener(mWrapper);
        } catch (android.os.RemoteException ex) {
            Log.v(TAG, "Unable to contact notification manager", ex);
            return 0;
        }
    
public final intgetCurrentListenerHints()
Gets the set of hints representing current state.

The current state may differ from the requested state if the hint represents state shared across all listeners or a feature the notification host does not support or refuses to grant.

return
Zero or more of the HINT_ constants.

        if (!isBound()) return 0;
        try {
            return getNotificationInterface().getHintsFromListener(mWrapper);
        } catch (android.os.RemoteException ex) {
            Log.v(TAG, "Unable to contact notification manager", ex);
            return 0;
        }
    
public android.service.notification.NotificationListenerService$RankingMapgetCurrentRanking()
Returns current ranking information.

The returned object represents the current ranking snapshot and only applies for currently active notifications.

Generally you should use the RankingMap that is passed with events such as {@link #onNotificationPosted(StatusBarNotification, RankingMap)}, {@link #onNotificationRemoved(StatusBarNotification, RankingMap)}, and so on. This method should only be used when needing access outside of such events, for example to retrieve the RankingMap right after initialization.

return
A {@link RankingMap} object providing access to ranking information

        return mRankingMap;
    
private final android.app.INotificationManagergetNotificationInterface()

        if (mNoMan == null) {
            mNoMan = INotificationManager.Stub.asInterface(
                    ServiceManager.getService(Context.NOTIFICATION_SERVICE));
        }
        return mNoMan;
    
private booleanisBound()

        if (mWrapper == null) {
            Log.w(TAG, "Notification listener service not yet bound.");
            return false;
        }
        return true;
    
public android.os.IBinderonBind(android.content.Intent intent)

        if (mWrapper == null) {
            mWrapper = new INotificationListenerWrapper();
        }
        return mWrapper;
    
public voidonInterruptionFilterChanged(int interruptionFilter)
Implement this method to be notified when the {@link #getCurrentInterruptionFilter() interruption filter} changed.

param
interruptionFilter The current {@link #getCurrentInterruptionFilter() interruption filter}.

        // optional
    
public voidonListenerConnected()
Implement this method to learn about when the listener is enabled and connected to the notification manager. You are safe to call {@link #getActiveNotifications()} at this time.

        // optional
    
public voidonListenerHintsChanged(int hints)
Implement this method to be notified when the {@link #getCurrentListenerHints() Listener hints} change.

param
hints The current {@link #getCurrentListenerHints() listener hints}.

        // optional
    
public voidonNotificationPosted(StatusBarNotification sbn)
Implement this method to learn about new notifications as they are posted by apps.

param
sbn A data structure encapsulating the original {@link android.app.Notification} object as well as its identifying information (tag and id) and source (package name).


                                                                     
        
        // optional
    
public voidonNotificationPosted(StatusBarNotification sbn, android.service.notification.NotificationListenerService$RankingMap rankingMap)
Implement this method to learn about new notifications as they are posted by apps.

param
sbn A data structure encapsulating the original {@link android.app.Notification} object as well as its identifying information (tag and id) and source (package name).
param
rankingMap The current ranking map that can be used to retrieve ranking information for active notifications, including the newly posted one.

        onNotificationPosted(sbn);
    
public voidonNotificationRankingUpdate(android.service.notification.NotificationListenerService$RankingMap rankingMap)
Implement this method to be notified when the notification ranking changes.

param
rankingMap The current ranking map that can be used to retrieve ranking information for active notifications.

        // optional
    
public voidonNotificationRemoved(StatusBarNotification sbn)
Implement this method to learn when notifications are removed.

This might occur because the user has dismissed the notification using system UI (or another notification listener) or because the app has withdrawn the notification.

NOTE: The {@link StatusBarNotification} object you receive will be "light"; that is, the result from {@link StatusBarNotification#getNotification} may be missing some heavyweight fields such as {@link android.app.Notification#contentView} and {@link android.app.Notification#largeIcon}. However, all other fields on {@link StatusBarNotification}, sufficient to match this call with a prior call to {@link #onNotificationPosted(StatusBarNotification)}, will be intact.

param
sbn A data structure encapsulating at least the original information (tag and id) and source (package name) used to post the {@link android.app.Notification} that was just removed.

        // optional
    
public voidonNotificationRemoved(StatusBarNotification sbn, android.service.notification.NotificationListenerService$RankingMap rankingMap)
Implement this method to learn when notifications are removed.

This might occur because the user has dismissed the notification using system UI (or another notification listener) or because the app has withdrawn the notification.

NOTE: The {@link StatusBarNotification} object you receive will be "light"; that is, the result from {@link StatusBarNotification#getNotification} may be missing some heavyweight fields such as {@link android.app.Notification#contentView} and {@link android.app.Notification#largeIcon}. However, all other fields on {@link StatusBarNotification}, sufficient to match this call with a prior call to {@link #onNotificationPosted(StatusBarNotification)}, will be intact.

param
sbn A data structure encapsulating at least the original information (tag and id) and source (package name) used to post the {@link android.app.Notification} that was just removed.
param
rankingMap The current ranking map that can be used to retrieve ranking information for active notifications.

        onNotificationRemoved(sbn);
    
public voidregisterAsSystemService(android.content.Context context, android.content.ComponentName componentName, int currentUser)
Directly register this service with the Notification Manager.

Only system services may use this call. It will fail for non-system callers. Apps should ask the user to add their listener in Settings.

param
context Context required for accessing resources. Since this service isn't launched as a real Service when using this method, a context has to be passed in.
param
componentName the component that will consume the notification information
param
currentUser the user to use as the stream filter
hide

        mSystemContext = context;
        if (mWrapper == null) {
            mWrapper = new INotificationListenerWrapper();
        }
        INotificationManager noMan = getNotificationInterface();
        noMan.registerListener(mWrapper, componentName, currentUser);
        mCurrentUser = currentUser;
    
public final voidrequestInterruptionFilter(int interruptionFilter)
Sets the desired {@link #getCurrentInterruptionFilter() interruption filter}.

This is merely a request, the host may or may not choose to apply the requested interruption filter depending on other listener requests or other global state.

Listen for updates using {@link #onInterruptionFilterChanged(int)}.

param
interruptionFilter One of the INTERRUPTION_FILTER_ constants.

        if (!isBound()) return;
        try {
            getNotificationInterface()
                    .requestInterruptionFilterFromListener(mWrapper, interruptionFilter);
        } catch (android.os.RemoteException ex) {
            Log.v(TAG, "Unable to contact notification manager", ex);
        }
    
public final voidrequestListenerHints(int hints)
Sets the desired {@link #getCurrentListenerHints() listener hints}.

This is merely a request, the host may or may not choose to take action depending on other listener requests or other global state.

Listen for updates using {@link #onListenerHintsChanged(int)}.

param
hints One or more of the HINT_ constants.

        if (!isBound()) return;
        try {
            getNotificationInterface().requestHintsFromListener(mWrapper, hints);
        } catch (android.os.RemoteException ex) {
            Log.v(TAG, "Unable to contact notification manager", ex);
        }
    
public final voidsetOnNotificationPostedTrim(int trim)
Sets the notification trim that will be received via {@link #onNotificationPosted}.

Setting a trim other than {@link #TRIM_FULL} enables listeners that don't need access to the full notification features right away to reduce their memory footprint. Full notifications can be requested on-demand via {@link #getActiveNotifications(int)}.

Set to {@link #TRIM_FULL} initially.

hide
param
trim trim of the notifications to be passed via {@link #onNotificationPosted}. See TRIM_* constants.

        if (!isBound()) return;
        try {
            getNotificationInterface().setOnNotificationPostedTrimFromListener(mWrapper, trim);
        } catch (RemoteException ex) {
            Log.v(TAG, "Unable to contact notification manager", ex);
        }
    
public voidunregisterAsSystemService()
Directly unregister this service from the Notification Manager.

This method will fail for listeners that were not registered with (@link registerAsService).

hide

        if (mWrapper != null) {
            INotificationManager noMan = getNotificationInterface();
            noMan.unregisterListener(mWrapper, mCurrentUser);
        }