NotificationListenerService.java revision 3b84812271cda2386557979503c29f3c530b7f90
1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.service.notification;
18
19import android.annotation.SystemApi;
20import android.annotation.SdkConstant;
21import android.app.INotificationManager;
22import android.app.Notification;
23import android.app.Notification.Builder;
24import android.app.NotificationManager;
25import android.app.Service;
26import android.content.ComponentName;
27import android.content.Context;
28import android.content.Intent;
29import android.content.pm.ParceledListSlice;
30import android.graphics.drawable.BitmapDrawable;
31import android.graphics.drawable.Drawable;
32import android.graphics.drawable.Icon;
33import android.graphics.Bitmap;
34import android.os.Build;
35import android.os.Bundle;
36import android.os.IBinder;
37import android.os.Parcel;
38import android.os.Parcelable;
39import android.os.RemoteException;
40import android.os.ServiceManager;
41import android.util.ArrayMap;
42import android.util.ArraySet;
43import android.util.Log;
44
45import java.util.ArrayList;
46import java.util.Collections;
47import java.util.List;
48
49/**
50 * A service that receives calls from the system when new notifications are
51 * posted or removed, or their ranking changed.
52 * <p>To extend this class, you must declare the service in your manifest file with
53 * the {@link android.Manifest.permission#BIND_NOTIFICATION_LISTENER_SERVICE} permission
54 * and include an intent filter with the {@link #SERVICE_INTERFACE} action. For example:</p>
55 * <pre>
56 * &lt;service android:name=".NotificationListener"
57 *          android:label="&#64;string/service_name"
58 *          android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
59 *     &lt;intent-filter>
60 *         &lt;action android:name="android.service.notification.NotificationListenerService" />
61 *     &lt;/intent-filter>
62 * &lt;/service></pre>
63 * <p> Typically, while enabled in user settings, this service will be bound on boot or when a
64 * settings change occurs that could affect whether this service should run.  However, for some
65 * system usage modes, the you may instead specify that this service is instead bound and unbound
66 * in response to mode changes by including a category in the intent filter.  Currently
67 * supported categories are:
68 * <ul>
69 *   <li>{@link #CATEGORY_VR_NOTIFICATIONS} - this service is bound when an Activity has enabled
70 *   VR mode. {@see android.app.Activity#setVrMode(boolean)}.</li>
71 * </ul>
72 * </p>
73 */
74public abstract class NotificationListenerService extends Service {
75    // TAG = "NotificationListenerService[MySubclass]"
76    private final String TAG = NotificationListenerService.class.getSimpleName()
77            + "[" + getClass().getSimpleName() + "]";
78
79    /**
80     * {@link #getCurrentInterruptionFilter() Interruption filter} constant -
81     *     Normal interruption filter.
82     */
83    public static final int INTERRUPTION_FILTER_ALL
84            = NotificationManager.INTERRUPTION_FILTER_ALL;
85
86    /**
87     * {@link #getCurrentInterruptionFilter() Interruption filter} constant -
88     *     Priority interruption filter.
89     */
90    public static final int INTERRUPTION_FILTER_PRIORITY
91            = NotificationManager.INTERRUPTION_FILTER_PRIORITY;
92
93    /**
94     * {@link #getCurrentInterruptionFilter() Interruption filter} constant -
95     *     No interruptions filter.
96     */
97    public static final int INTERRUPTION_FILTER_NONE
98            = NotificationManager.INTERRUPTION_FILTER_NONE;
99
100    /**
101     * {@link #getCurrentInterruptionFilter() Interruption filter} constant -
102     *     Alarms only interruption filter.
103     */
104    public static final int INTERRUPTION_FILTER_ALARMS
105            = NotificationManager.INTERRUPTION_FILTER_ALARMS;
106
107    /** {@link #getCurrentInterruptionFilter() Interruption filter} constant - returned when
108     * the value is unavailable for any reason.  For example, before the notification listener
109     * is connected.
110     *
111     * {@see #onListenerConnected()}
112     */
113    public static final int INTERRUPTION_FILTER_UNKNOWN
114            = NotificationManager.INTERRUPTION_FILTER_UNKNOWN;
115
116    /** {@link #getCurrentListenerHints() Listener hints} constant - the primary device UI
117     * should disable notification sound, vibrating and other visual or aural effects.
118     * This does not change the interruption filter, only the effects. **/
119    public static final int HINT_HOST_DISABLE_EFFECTS = 1;
120
121    /**
122     * Whether notification suppressed by DND should not interruption visually when the screen is
123     * off.
124     */
125    public static final int SUPPRESSED_EFFECT_SCREEN_OFF =
126            NotificationManager.Policy.SUPPRESSED_EFFECT_SCREEN_OFF;
127    /**
128     * Whether notification suppressed by DND should not interruption visually when the screen is
129     * on.
130     */
131    public static final int SUPPRESSED_EFFECT_SCREEN_ON =
132            NotificationManager.Policy.SUPPRESSED_EFFECT_SCREEN_ON;
133
134    /**
135     * The full trim of the StatusBarNotification including all its features.
136     *
137     * @hide
138     */
139    @SystemApi
140    public static final int TRIM_FULL = 0;
141
142    /**
143     * A light trim of the StatusBarNotification excluding the following features:
144     *
145     * <ol>
146     *     <li>{@link Notification#tickerView tickerView}</li>
147     *     <li>{@link Notification#contentView contentView}</li>
148     *     <li>{@link Notification#largeIcon largeIcon}</li>
149     *     <li>{@link Notification#bigContentView bigContentView}</li>
150     *     <li>{@link Notification#headsUpContentView headsUpContentView}</li>
151     *     <li>{@link Notification#EXTRA_LARGE_ICON extras[EXTRA_LARGE_ICON]}</li>
152     *     <li>{@link Notification#EXTRA_LARGE_ICON_BIG extras[EXTRA_LARGE_ICON_BIG]}</li>
153     *     <li>{@link Notification#EXTRA_PICTURE extras[EXTRA_PICTURE]}</li>
154     *     <li>{@link Notification#EXTRA_BIG_TEXT extras[EXTRA_BIG_TEXT]}</li>
155     * </ol>
156     *
157     * @hide
158     */
159    @SystemApi
160    public static final int TRIM_LIGHT = 1;
161
162    /** @hide */
163    protected NotificationListenerWrapper mWrapper = null;
164    private RankingMap mRankingMap;
165
166    private INotificationManager mNoMan;
167
168    /** Only valid after a successful call to (@link registerAsService}. */
169    private int mCurrentUser;
170
171
172    // This context is required for system services since NotificationListenerService isn't
173    // started as a real Service and hence no context is available.
174    private Context mSystemContext;
175
176    /**
177     * The {@link Intent} that must be declared as handled by the service.
178     */
179    @SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION)
180    public static final String SERVICE_INTERFACE
181            = "android.service.notification.NotificationListenerService";
182
183    /**
184     * If this category is declared in the application manifest for a service of this type, this
185     * service will be bound when VR mode is enabled, and unbound when VR mode is disabled rather
186     * than the normal lifecycle for a notification service.
187     *
188     * {@see android.app.Activity#setVrMode(boolean)}
189     */
190    @SdkConstant(SdkConstant.SdkConstantType.INTENT_CATEGORY)
191    public static final String CATEGORY_VR_NOTIFICATIONS =
192        "android.intent.category.vr.notifications";
193
194    /**
195     * Implement this method to learn about new notifications as they are posted by apps.
196     *
197     * @param sbn A data structure encapsulating the original {@link android.app.Notification}
198     *            object as well as its identifying information (tag and id) and source
199     *            (package name).
200     */
201    public void onNotificationPosted(StatusBarNotification sbn) {
202        // optional
203    }
204
205    /**
206     * Implement this method to learn about new notifications as they are posted by apps.
207     *
208     * @param sbn A data structure encapsulating the original {@link android.app.Notification}
209     *            object as well as its identifying information (tag and id) and source
210     *            (package name).
211     * @param rankingMap The current ranking map that can be used to retrieve ranking information
212     *                   for active notifications, including the newly posted one.
213     */
214    public void onNotificationPosted(StatusBarNotification sbn, RankingMap rankingMap) {
215        onNotificationPosted(sbn);
216    }
217
218    /**
219     * Implement this method to learn when notifications are removed.
220     * <P>
221     * This might occur because the user has dismissed the notification using system UI (or another
222     * notification listener) or because the app has withdrawn the notification.
223     * <P>
224     * NOTE: The {@link StatusBarNotification} object you receive will be "light"; that is, the
225     * result from {@link StatusBarNotification#getNotification} may be missing some heavyweight
226     * fields such as {@link android.app.Notification#contentView} and
227     * {@link android.app.Notification#largeIcon}. However, all other fields on
228     * {@link StatusBarNotification}, sufficient to match this call with a prior call to
229     * {@link #onNotificationPosted(StatusBarNotification)}, will be intact.
230     *
231     * @param sbn A data structure encapsulating at least the original information (tag and id)
232     *            and source (package name) used to post the {@link android.app.Notification} that
233     *            was just removed.
234     */
235    public void onNotificationRemoved(StatusBarNotification sbn) {
236        // optional
237    }
238
239    /**
240     * Implement this method to learn when notifications are removed.
241     * <P>
242     * This might occur because the user has dismissed the notification using system UI (or another
243     * notification listener) or because the app has withdrawn the notification.
244     * <P>
245     * NOTE: The {@link StatusBarNotification} object you receive will be "light"; that is, the
246     * result from {@link StatusBarNotification#getNotification} may be missing some heavyweight
247     * fields such as {@link android.app.Notification#contentView} and
248     * {@link android.app.Notification#largeIcon}. However, all other fields on
249     * {@link StatusBarNotification}, sufficient to match this call with a prior call to
250     * {@link #onNotificationPosted(StatusBarNotification)}, will be intact.
251     *
252     * @param sbn A data structure encapsulating at least the original information (tag and id)
253     *            and source (package name) used to post the {@link android.app.Notification} that
254     *            was just removed.
255     * @param rankingMap The current ranking map that can be used to retrieve ranking information
256     *                   for active notifications.
257     *
258     */
259    public void onNotificationRemoved(StatusBarNotification sbn, RankingMap rankingMap) {
260        onNotificationRemoved(sbn);
261    }
262
263    /**
264     * Implement this method to learn about when the listener is enabled and connected to
265     * the notification manager.  You are safe to call {@link #getActiveNotifications()}
266     * at this time.
267     */
268    public void onListenerConnected() {
269        // optional
270    }
271
272    /**
273     * Implement this method to be notified when the notification ranking changes.
274     *
275     * @param rankingMap The current ranking map that can be used to retrieve ranking information
276     *                   for active notifications.
277     */
278    public void onNotificationRankingUpdate(RankingMap rankingMap) {
279        // optional
280    }
281
282    /**
283     * Implement this method to be notified when the
284     * {@link #getCurrentListenerHints() Listener hints} change.
285     *
286     * @param hints The current {@link #getCurrentListenerHints() listener hints}.
287     */
288    public void onListenerHintsChanged(int hints) {
289        // optional
290    }
291
292    /**
293     * Implement this method to be notified when the
294     * {@link #getCurrentInterruptionFilter() interruption filter} changed.
295     *
296     * @param interruptionFilter The current
297     *     {@link #getCurrentInterruptionFilter() interruption filter}.
298     */
299    public void onInterruptionFilterChanged(int interruptionFilter) {
300        // optional
301    }
302
303    /** @hide */
304    protected final INotificationManager getNotificationInterface() {
305        if (mNoMan == null) {
306            mNoMan = INotificationManager.Stub.asInterface(
307                    ServiceManager.getService(Context.NOTIFICATION_SERVICE));
308        }
309        return mNoMan;
310    }
311
312    /**
313     * Inform the notification manager about dismissal of a single notification.
314     * <p>
315     * Use this if your listener has a user interface that allows the user to dismiss individual
316     * notifications, similar to the behavior of Android's status bar and notification panel.
317     * It should be called after the user dismisses a single notification using your UI;
318     * upon being informed, the notification manager will actually remove the notification
319     * and you will get an {@link #onNotificationRemoved(StatusBarNotification)} callback.
320     * <P>
321     * <b>Note:</b> If your listener allows the user to fire a notification's
322     * {@link android.app.Notification#contentIntent} by tapping/clicking/etc., you should call
323     * this method at that time <i>if</i> the Notification in question has the
324     * {@link android.app.Notification#FLAG_AUTO_CANCEL} flag set.
325     *
326     * @param pkg Package of the notifying app.
327     * @param tag Tag of the notification as specified by the notifying app in
328     *     {@link android.app.NotificationManager#notify(String, int, android.app.Notification)}.
329     * @param id  ID of the notification as specified by the notifying app in
330     *     {@link android.app.NotificationManager#notify(String, int, android.app.Notification)}.
331     * <p>
332     * @deprecated Use {@link #cancelNotification(String key)}
333     * instead. Beginning with {@link android.os.Build.VERSION_CODES#LOLLIPOP} this method will no longer
334     * cancel the notification. It will continue to cancel the notification for applications
335     * whose {@code targetSdkVersion} is earlier than {@link android.os.Build.VERSION_CODES#LOLLIPOP}.
336     */
337    public final void cancelNotification(String pkg, String tag, int id) {
338        if (!isBound()) return;
339        try {
340            getNotificationInterface().cancelNotificationFromListener(
341                    mWrapper, pkg, tag, id);
342        } catch (android.os.RemoteException ex) {
343            Log.v(TAG, "Unable to contact notification manager", ex);
344        }
345    }
346
347    /**
348     * Inform the notification manager about dismissal of a single notification.
349     * <p>
350     * Use this if your listener has a user interface that allows the user to dismiss individual
351     * notifications, similar to the behavior of Android's status bar and notification panel.
352     * It should be called after the user dismisses a single notification using your UI;
353     * upon being informed, the notification manager will actually remove the notification
354     * and you will get an {@link #onNotificationRemoved(StatusBarNotification)} callback.
355     * <P>
356     * <b>Note:</b> If your listener allows the user to fire a notification's
357     * {@link android.app.Notification#contentIntent} by tapping/clicking/etc., you should call
358     * this method at that time <i>if</i> the Notification in question has the
359     * {@link android.app.Notification#FLAG_AUTO_CANCEL} flag set.
360     * <p>
361     * @param key Notification to dismiss from {@link StatusBarNotification#getKey()}.
362     */
363    public final void cancelNotification(String key) {
364        if (!isBound()) return;
365        try {
366            getNotificationInterface().cancelNotificationsFromListener(mWrapper,
367                    new String[] { key });
368        } catch (android.os.RemoteException ex) {
369            Log.v(TAG, "Unable to contact notification manager", ex);
370        }
371    }
372
373    /**
374     * Inform the notification manager about dismissal of all notifications.
375     * <p>
376     * Use this if your listener has a user interface that allows the user to dismiss all
377     * notifications, similar to the behavior of Android's status bar and notification panel.
378     * It should be called after the user invokes the "dismiss all" function of your UI;
379     * upon being informed, the notification manager will actually remove all active notifications
380     * and you will get multiple {@link #onNotificationRemoved(StatusBarNotification)} callbacks.
381     *
382     * {@see #cancelNotification(String, String, int)}
383     */
384    public final void cancelAllNotifications() {
385        cancelNotifications(null /*all*/);
386    }
387
388    /**
389     * Inform the notification manager about dismissal of specific notifications.
390     * <p>
391     * Use this if your listener has a user interface that allows the user to dismiss
392     * multiple notifications at once.
393     *
394     * @param keys Notifications to dismiss, or {@code null} to dismiss all.
395     *
396     * {@see #cancelNotification(String, String, int)}
397     */
398    public final void cancelNotifications(String[] keys) {
399        if (!isBound()) return;
400        try {
401            getNotificationInterface().cancelNotificationsFromListener(mWrapper, keys);
402        } catch (android.os.RemoteException ex) {
403            Log.v(TAG, "Unable to contact notification manager", ex);
404        }
405    }
406
407    /**
408     * Inform the notification manager that these notifications have been viewed by the
409     * user. This should only be called when there is sufficient confidence that the user is
410     * looking at the notifications, such as when the notifications appear on the screen due to
411     * an explicit user interaction.
412     * @param keys Notifications to mark as seen.
413     */
414    public final void setNotificationsShown(String[] keys) {
415        if (!isBound()) return;
416        try {
417            getNotificationInterface().setNotificationsShownFromListener(mWrapper, keys);
418        } catch (android.os.RemoteException ex) {
419            Log.v(TAG, "Unable to contact notification manager", ex);
420        }
421    }
422
423    /**
424     * Sets the notification trim that will be received via {@link #onNotificationPosted}.
425     *
426     * <p>
427     * Setting a trim other than {@link #TRIM_FULL} enables listeners that don't need access to the
428     * full notification features right away to reduce their memory footprint. Full notifications
429     * can be requested on-demand via {@link #getActiveNotifications(int)}.
430     *
431     * <p>
432     * Set to {@link #TRIM_FULL} initially.
433     *
434     * @hide
435     *
436     * @param trim trim of the notifications to be passed via {@link #onNotificationPosted}.
437     *             See <code>TRIM_*</code> constants.
438     */
439    @SystemApi
440    public final void setOnNotificationPostedTrim(int trim) {
441        if (!isBound()) return;
442        try {
443            getNotificationInterface().setOnNotificationPostedTrimFromListener(mWrapper, trim);
444        } catch (RemoteException ex) {
445            Log.v(TAG, "Unable to contact notification manager", ex);
446        }
447    }
448
449    /**
450     * Request the list of outstanding notifications (that is, those that are visible to the
451     * current user). Useful when you don't know what's already been posted.
452     *
453     * @return An array of active notifications, sorted in natural order.
454     */
455    public StatusBarNotification[] getActiveNotifications() {
456        return getActiveNotifications(null, TRIM_FULL);
457    }
458
459    /**
460     * Request the list of outstanding notifications (that is, those that are visible to the
461     * current user). Useful when you don't know what's already been posted.
462     *
463     * @hide
464     *
465     * @param trim trim of the notifications to be returned. See <code>TRIM_*</code> constants.
466     * @return An array of active notifications, sorted in natural order.
467     */
468    @SystemApi
469    public StatusBarNotification[] getActiveNotifications(int trim) {
470        return getActiveNotifications(null, trim);
471    }
472
473    /**
474     * Request one or more notifications by key. Useful if you have been keeping track of
475     * notifications but didn't want to retain the bits, and now need to go back and extract
476     * more data out of those notifications.
477     *
478     * @param keys the keys of the notifications to request
479     * @return An array of notifications corresponding to the requested keys, in the
480     * same order as the key list.
481     */
482    public StatusBarNotification[] getActiveNotifications(String[] keys) {
483        return getActiveNotifications(keys, TRIM_FULL);
484    }
485
486    /**
487     * Request one or more notifications by key. Useful if you have been keeping track of
488     * notifications but didn't want to retain the bits, and now need to go back and extract
489     * more data out of those notifications.
490     *
491     * @hide
492     *
493     * @param keys the keys of the notifications to request
494     * @param trim trim of the notifications to be returned. See <code>TRIM_*</code> constants.
495     * @return An array of notifications corresponding to the requested keys, in the
496     * same order as the key list.
497     */
498    @SystemApi
499    public StatusBarNotification[] getActiveNotifications(String[] keys, int trim) {
500        if (!isBound())
501            return null;
502        try {
503            ParceledListSlice<StatusBarNotification> parceledList = getNotificationInterface()
504                    .getActiveNotificationsFromListener(mWrapper, keys, trim);
505            List<StatusBarNotification> list = parceledList.getList();
506            ArrayList<StatusBarNotification> corruptNotifications = null;
507            int N = list.size();
508            for (int i = 0; i < N; i++) {
509                StatusBarNotification sbn = list.get(i);
510                Notification notification = sbn.getNotification();
511                try {
512                    // convert icon metadata to legacy format for older clients
513                    createLegacyIconExtras(notification);
514                    // populate remote views for older clients.
515                    maybePopulateRemoteViews(notification);
516                } catch (IllegalArgumentException e) {
517                    if (corruptNotifications == null) {
518                        corruptNotifications = new ArrayList<>(N);
519                    }
520                    corruptNotifications.add(sbn);
521                    Log.w(TAG, "onNotificationPosted: can't rebuild notification from " +
522                            sbn.getPackageName());
523                }
524            }
525            if (corruptNotifications != null) {
526                list.removeAll(corruptNotifications);
527            }
528            return list.toArray(new StatusBarNotification[list.size()]);
529        } catch (android.os.RemoteException ex) {
530            Log.v(TAG, "Unable to contact notification manager", ex);
531        }
532        return null;
533    }
534
535    /**
536     * Gets the set of hints representing current state.
537     *
538     * <p>
539     * The current state may differ from the requested state if the hint represents state
540     * shared across all listeners or a feature the notification host does not support or refuses
541     * to grant.
542     *
543     * @return Zero or more of the HINT_ constants.
544     */
545    public final int getCurrentListenerHints() {
546        if (!isBound()) return 0;
547        try {
548            return getNotificationInterface().getHintsFromListener(mWrapper);
549        } catch (android.os.RemoteException ex) {
550            Log.v(TAG, "Unable to contact notification manager", ex);
551            return 0;
552        }
553    }
554
555    /**
556     * Gets the current notification interruption filter active on the host.
557     *
558     * <p>
559     * The interruption filter defines which notifications are allowed to interrupt the user
560     * (e.g. via sound &amp; vibration) and is applied globally. Listeners can find out whether
561     * a specific notification matched the interruption filter via
562     * {@link Ranking#matchesInterruptionFilter()}.
563     * <p>
564     * The current filter may differ from the previously requested filter if the notification host
565     * does not support or refuses to apply the requested filter, or if another component changed
566     * the filter in the meantime.
567     * <p>
568     * Listen for updates using {@link #onInterruptionFilterChanged(int)}.
569     *
570     * @return One of the INTERRUPTION_FILTER_ constants, or INTERRUPTION_FILTER_UNKNOWN when
571     * unavailable.
572     */
573    public final int getCurrentInterruptionFilter() {
574        if (!isBound()) return INTERRUPTION_FILTER_UNKNOWN;
575        try {
576            return getNotificationInterface().getInterruptionFilterFromListener(mWrapper);
577        } catch (android.os.RemoteException ex) {
578            Log.v(TAG, "Unable to contact notification manager", ex);
579            return INTERRUPTION_FILTER_UNKNOWN;
580        }
581    }
582
583    /**
584     * Sets the desired {@link #getCurrentListenerHints() listener hints}.
585     *
586     * <p>
587     * This is merely a request, the host may or may not choose to take action depending
588     * on other listener requests or other global state.
589     * <p>
590     * Listen for updates using {@link #onListenerHintsChanged(int)}.
591     *
592     * @param hints One or more of the HINT_ constants.
593     */
594    public final void requestListenerHints(int hints) {
595        if (!isBound()) return;
596        try {
597            getNotificationInterface().requestHintsFromListener(mWrapper, hints);
598        } catch (android.os.RemoteException ex) {
599            Log.v(TAG, "Unable to contact notification manager", ex);
600        }
601    }
602
603    /**
604     * Sets the desired {@link #getCurrentInterruptionFilter() interruption filter}.
605     *
606     * <p>
607     * This is merely a request, the host may or may not choose to apply the requested
608     * interruption filter depending on other listener requests or other global state.
609     * <p>
610     * Listen for updates using {@link #onInterruptionFilterChanged(int)}.
611     *
612     * @param interruptionFilter One of the INTERRUPTION_FILTER_ constants.
613     */
614    public final void requestInterruptionFilter(int interruptionFilter) {
615        if (!isBound()) return;
616        try {
617            getNotificationInterface()
618                    .requestInterruptionFilterFromListener(mWrapper, interruptionFilter);
619        } catch (android.os.RemoteException ex) {
620            Log.v(TAG, "Unable to contact notification manager", ex);
621        }
622    }
623
624    /**
625     * Returns current ranking information.
626     *
627     * <p>
628     * The returned object represents the current ranking snapshot and only
629     * applies for currently active notifications.
630     * <p>
631     * Generally you should use the RankingMap that is passed with events such
632     * as {@link #onNotificationPosted(StatusBarNotification, RankingMap)},
633     * {@link #onNotificationRemoved(StatusBarNotification, RankingMap)}, and
634     * so on. This method should only be used when needing access outside of
635     * such events, for example to retrieve the RankingMap right after
636     * initialization.
637     *
638     * @return A {@link RankingMap} object providing access to ranking information
639     */
640    public RankingMap getCurrentRanking() {
641        return mRankingMap;
642    }
643
644    @Override
645    public IBinder onBind(Intent intent) {
646        if (mWrapper == null) {
647            mWrapper = new NotificationListenerWrapper();
648        }
649        return mWrapper;
650    }
651
652    /** @hide */
653    protected boolean isBound() {
654        if (mWrapper == null) {
655            Log.w(TAG, "Notification listener service not yet bound.");
656            return false;
657        }
658        return true;
659    }
660
661    /**
662     * Directly register this service with the Notification Manager.
663     *
664     * <p>Only system services may use this call. It will fail for non-system callers.
665     * Apps should ask the user to add their listener in Settings.
666     *
667     * @param context Context required for accessing resources. Since this service isn't
668     *    launched as a real Service when using this method, a context has to be passed in.
669     * @param componentName the component that will consume the notification information
670     * @param currentUser the user to use as the stream filter
671     * @hide
672     */
673    @SystemApi
674    public void registerAsSystemService(Context context, ComponentName componentName,
675            int currentUser) throws RemoteException {
676        mSystemContext = context;
677        if (mWrapper == null) {
678            mWrapper = new NotificationListenerWrapper();
679        }
680        INotificationManager noMan = getNotificationInterface();
681        noMan.registerListener(mWrapper, componentName, currentUser);
682        mCurrentUser = currentUser;
683    }
684
685    /**
686     * Directly unregister this service from the Notification Manager.
687     *
688     * <P>This method will fail for listeners that were not registered
689     * with (@link registerAsService).
690     * @hide
691     */
692    @SystemApi
693    public void unregisterAsSystemService() throws RemoteException {
694        if (mWrapper != null) {
695            INotificationManager noMan = getNotificationInterface();
696            noMan.unregisterListener(mWrapper, mCurrentUser);
697        }
698    }
699
700    /**
701     * Request that the listener be rebound, after a previous call to (@link requestUnbind).
702     *
703     * <P>This method will fail for listeners that have
704     * not been granted the permission by the user.
705     *
706     * <P>The service should wait for the {@link #onListenerConnected()} event
707     * before performing any operations.
708     */
709    public static final void requestRebind(ComponentName componentName)
710            throws RemoteException {
711        INotificationManager noMan = INotificationManager.Stub.asInterface(
712                ServiceManager.getService(Context.NOTIFICATION_SERVICE));
713        noMan.requestBindListener(componentName);
714    }
715
716    /**
717     * Request that the service be unbound.
718     *
719     * <P>This will no longer receive updates until
720     * {@link #requestRebind(ComponentName)} is called.
721     * The service will likely be kiled by the system after this call.
722     */
723    public final void requestUnbind() throws RemoteException {
724        if (mWrapper != null) {
725            INotificationManager noMan = getNotificationInterface();
726            noMan.requestUnbindListener(mWrapper);
727        }
728    }
729
730    /** Convert new-style Icons to legacy representations for pre-M clients. */
731    private void createLegacyIconExtras(Notification n) {
732        Icon smallIcon = n.getSmallIcon();
733        Icon largeIcon = n.getLargeIcon();
734        if (smallIcon != null && smallIcon.getType() == Icon.TYPE_RESOURCE) {
735            n.extras.putInt(Notification.EXTRA_SMALL_ICON, smallIcon.getResId());
736            n.icon = smallIcon.getResId();
737        }
738        if (largeIcon != null) {
739            Drawable d = largeIcon.loadDrawable(getContext());
740            if (d != null && d instanceof BitmapDrawable) {
741                final Bitmap largeIconBits = ((BitmapDrawable) d).getBitmap();
742                n.extras.putParcelable(Notification.EXTRA_LARGE_ICON, largeIconBits);
743                n.largeIcon = largeIconBits;
744            }
745        }
746    }
747
748    /**
749     * Populates remote views for pre-N targeting apps.
750     */
751    private void maybePopulateRemoteViews(Notification notification) {
752        if (getContext().getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N) {
753            Builder builder = Builder.recoverBuilder(getContext(), notification);
754            notification.contentView = builder.createContentView();
755            notification.bigContentView = builder.createBigContentView();
756            notification.headsUpContentView = builder.createHeadsUpContentView();
757        }
758    }
759
760    /** @hide */
761    protected class NotificationListenerWrapper extends INotificationListener.Stub {
762        @Override
763        public void onNotificationPosted(IStatusBarNotificationHolder sbnHolder,
764                NotificationRankingUpdate update) {
765            StatusBarNotification sbn;
766            try {
767                sbn = sbnHolder.get();
768            } catch (RemoteException e) {
769                Log.w(TAG, "onNotificationPosted: Error receiving StatusBarNotification", e);
770                return;
771            }
772
773            try {
774                Notification notification = sbn.getNotification();
775                // convert icon metadata to legacy format for older clients
776                createLegacyIconExtras(sbn.getNotification());
777                maybePopulateRemoteViews(sbn.getNotification());
778            } catch (IllegalArgumentException e) {
779                // warn and drop corrupt notification
780                Log.w(TAG, "onNotificationPosted: can't rebuild notification from " +
781                        sbn.getPackageName());
782                sbn = null;
783            }
784
785            // protect subclass from concurrent modifications of (@link mNotificationKeys}.
786            synchronized (mWrapper) {
787                applyUpdate(update);
788                try {
789                    if (sbn != null) {
790                        NotificationListenerService.this.onNotificationPosted(sbn, mRankingMap);
791                    } else {
792                        // still pass along the ranking map, it may contain other information
793                        NotificationListenerService.this.onNotificationRankingUpdate(mRankingMap);
794                    }
795                } catch (Throwable t) {
796                    Log.w(TAG, "Error running onNotificationPosted", t);
797                }
798            }
799        }
800        @Override
801        public void onNotificationRemoved(IStatusBarNotificationHolder sbnHolder,
802                NotificationRankingUpdate update) {
803            StatusBarNotification sbn;
804            try {
805                sbn = sbnHolder.get();
806            } catch (RemoteException e) {
807                Log.w(TAG, "onNotificationRemoved: Error receiving StatusBarNotification", e);
808                return;
809            }
810            // protect subclass from concurrent modifications of (@link mNotificationKeys}.
811            synchronized (mWrapper) {
812                applyUpdate(update);
813                try {
814                    NotificationListenerService.this.onNotificationRemoved(sbn, mRankingMap);
815                } catch (Throwable t) {
816                    Log.w(TAG, "Error running onNotificationRemoved", t);
817                }
818            }
819        }
820        @Override
821        public void onListenerConnected(NotificationRankingUpdate update) {
822            // protect subclass from concurrent modifications of (@link mNotificationKeys}.
823            synchronized (mWrapper) {
824                applyUpdate(update);
825                try {
826                    NotificationListenerService.this.onListenerConnected();
827                } catch (Throwable t) {
828                    Log.w(TAG, "Error running onListenerConnected", t);
829                }
830            }
831        }
832        @Override
833        public void onNotificationRankingUpdate(NotificationRankingUpdate update)
834                throws RemoteException {
835            // protect subclass from concurrent modifications of (@link mNotificationKeys}.
836            synchronized (mWrapper) {
837                applyUpdate(update);
838                try {
839                    NotificationListenerService.this.onNotificationRankingUpdate(mRankingMap);
840                } catch (Throwable t) {
841                    Log.w(TAG, "Error running onNotificationRankingUpdate", t);
842                }
843            }
844        }
845        @Override
846        public void onListenerHintsChanged(int hints) throws RemoteException {
847            try {
848                NotificationListenerService.this.onListenerHintsChanged(hints);
849            } catch (Throwable t) {
850                Log.w(TAG, "Error running onListenerHintsChanged", t);
851            }
852        }
853
854        @Override
855        public void onInterruptionFilterChanged(int interruptionFilter) throws RemoteException {
856            try {
857                NotificationListenerService.this.onInterruptionFilterChanged(interruptionFilter);
858            } catch (Throwable t) {
859                Log.w(TAG, "Error running onInterruptionFilterChanged", t);
860            }
861        }
862
863        @Override
864        public void onNotificationEnqueued(IStatusBarNotificationHolder notificationHolder,
865                                           int importance, boolean user) throws RemoteException {
866            // no-op in the listener
867        }
868
869        @Override
870        public void onNotificationVisibilityChanged(String key, long time, boolean visible)
871                throws RemoteException {
872            // no-op in the listener
873        }
874
875        @Override
876        public void onNotificationClick(String key, long time) throws RemoteException {
877            // no-op in the listener
878        }
879
880        @Override
881        public void onNotificationActionClick(String key, long time, int actionIndex)
882                throws RemoteException {
883            // no-op in the listener
884        }
885
886        @Override
887        public void onNotificationRemovedReason(String key, long time, int reason)
888                throws RemoteException {
889            // no-op in the listener
890        }
891    }
892
893    private void applyUpdate(NotificationRankingUpdate update) {
894        mRankingMap = new RankingMap(update);
895    }
896
897    private Context getContext() {
898        if (mSystemContext != null) {
899            return mSystemContext;
900        }
901        return this;
902    }
903
904    /**
905     * Stores ranking related information on a currently active notification.
906     *
907     * <p>
908     * Ranking objects aren't automatically updated as notification events
909     * occur. Instead, ranking information has to be retrieved again via the
910     * current {@link RankingMap}.
911     */
912    public static class Ranking {
913        /** Value signifying that the user has not expressed a per-app visibility override value.
914         * @hide */
915        public static final int VISIBILITY_NO_OVERRIDE = -1000;
916
917        /**
918         * Value signifying that the user has not expressed an importance.
919         *
920         * This value is for persisting preferences, and should never be associated with
921         * an actual notification.
922         */
923        public static final int IMPORTANCE_UNSPECIFIED = -1000;
924
925        /**
926         * A notification with no importance: shows nowhere, is blocked.
927         */
928        public static final int IMPORTANCE_NONE = 0;
929
930        /**
931         * Min notification importance: only shows in the shade, below the fold.
932         */
933        public static final int IMPORTANCE_MIN = 1;
934
935        /**
936         * Low notification importance: shows everywhere, but is not intrusive.
937         */
938        public static final int IMPORTANCE_LOW = 2;
939
940        /**
941         * Default notification importance: shows everywhere, allowed to makes noise,
942         * but does not visually intrude.
943         */
944        public static final int IMPORTANCE_DEFAULT = 3;
945
946        /**
947         * Higher notification importance: shows everywhere, allowed to makes noise and peek.
948         */
949        public static final int IMPORTANCE_HIGH = 4;
950
951        /**
952         * Highest notification importance: shows everywhere, allowed to makes noise, peek, and
953         * use full screen intents.
954         */
955        public static final int IMPORTANCE_MAX = 5;
956
957        private String mKey;
958        private int mRank = -1;
959        private boolean mIsAmbient;
960        private boolean mMatchesInterruptionFilter;
961        private int mVisibilityOverride;
962        private int mSuppressedVisualEffects;
963        private int mImportance;
964        private CharSequence mImportanceExplanation;
965
966        public Ranking() {}
967
968        /**
969         * Returns the key of the notification this Ranking applies to.
970         */
971        public String getKey() {
972            return mKey;
973        }
974
975        /**
976         * Returns the rank of the notification.
977         *
978         * @return the rank of the notification, that is the 0-based index in
979         *     the list of active notifications.
980         */
981        public int getRank() {
982            return mRank;
983        }
984
985        /**
986         * Returns whether the notification is an ambient notification, that is
987         * a notification that doesn't require the user's immediate attention.
988         */
989        public boolean isAmbient() {
990            return mIsAmbient;
991        }
992
993        /**
994         * Returns the user specificed visibility for the package that posted
995         * this notification, or
996         * {@link NotificationListenerService.Ranking#VISIBILITY_NO_OVERRIDE} if
997         * no such preference has been expressed.
998         * @hide
999         */
1000        public int getVisibilityOverride() {
1001            return mVisibilityOverride;
1002        }
1003
1004        /**
1005         * Returns the type(s) of visual effects that should be suppressed for this notification.
1006         * See {@link #SUPPRESSED_EFFECT_SCREEN_OFF}, {@link #SUPPRESSED_EFFECT_SCREEN_ON}.
1007         */
1008        public int getSuppressedVisualEffects() {
1009            return mSuppressedVisualEffects;
1010        }
1011
1012        /**
1013         * Returns whether the notification matches the user's interruption
1014         * filter.
1015         *
1016         * @return {@code true} if the notification is allowed by the filter, or
1017         * {@code false} if it is blocked.
1018         */
1019        public boolean matchesInterruptionFilter() {
1020            return mMatchesInterruptionFilter;
1021        }
1022
1023        /**
1024         * Returns the importance of the notification, which dictates its
1025         * modes of presentation, see: {@link #IMPORTANCE_DEFAULT}, etc.
1026         *
1027         * @return the rank of the notification
1028         */
1029        public int getImportance() {
1030            return mImportance;
1031        }
1032
1033        /**
1034         * If the importance has been overriden by user preference, then this will be non-null,
1035         * and should be displayed to the user.
1036         *
1037         * @return the explanation for the importance, or null if it is the natural importance
1038         */
1039        public CharSequence getImportanceExplanation() {
1040            return mImportanceExplanation;
1041        }
1042
1043        private void populate(String key, int rank, boolean matchesInterruptionFilter,
1044                int visibilityOverride, int suppressedVisualEffects, int importance,
1045                CharSequence explanation) {
1046            mKey = key;
1047            mRank = rank;
1048            mIsAmbient = importance < IMPORTANCE_LOW;
1049            mMatchesInterruptionFilter = matchesInterruptionFilter;
1050            mVisibilityOverride = visibilityOverride;
1051            mSuppressedVisualEffects = suppressedVisualEffects;
1052            mImportance = importance;
1053            mImportanceExplanation = explanation;
1054        }
1055
1056        /**
1057         * {@hide}
1058         */
1059        public static String importanceToString(int importance) {
1060            switch (importance) {
1061                case IMPORTANCE_UNSPECIFIED:
1062                    return "UNSPECIFIED";
1063                case IMPORTANCE_NONE:
1064                    return "NONE";
1065                case IMPORTANCE_MIN:
1066                    return "MIN";
1067                case IMPORTANCE_LOW:
1068                    return "LOW";
1069                case IMPORTANCE_DEFAULT:
1070                    return "DEFAULT";
1071                case IMPORTANCE_HIGH:
1072                    return "HIGH";
1073                case IMPORTANCE_MAX:
1074                    return "MAX";
1075                default:
1076                    return "UNKNOWN(" + String.valueOf(importance) + ")";
1077            }
1078        }
1079    }
1080
1081    /**
1082     * Provides access to ranking information on currently active
1083     * notifications.
1084     *
1085     * <p>
1086     * Note that this object represents a ranking snapshot that only applies to
1087     * notifications active at the time of retrieval.
1088     */
1089    public static class RankingMap implements Parcelable {
1090        private final NotificationRankingUpdate mRankingUpdate;
1091        private ArrayMap<String,Integer> mRanks;
1092        private ArraySet<Object> mIntercepted;
1093        private ArrayMap<String, Integer> mVisibilityOverrides;
1094        private ArrayMap<String, Integer> mSuppressedVisualEffects;
1095        private ArrayMap<String, Integer> mImportance;
1096        private ArrayMap<String, String> mImportanceExplanation;
1097
1098        private RankingMap(NotificationRankingUpdate rankingUpdate) {
1099            mRankingUpdate = rankingUpdate;
1100        }
1101
1102        /**
1103         * Request the list of notification keys in their current ranking
1104         * order.
1105         *
1106         * @return An array of active notification keys, in their ranking order.
1107         */
1108        public String[] getOrderedKeys() {
1109            return mRankingUpdate.getOrderedKeys();
1110        }
1111
1112        /**
1113         * Populates outRanking with ranking information for the notification
1114         * with the given key.
1115         *
1116         * @return true if a valid key has been passed and outRanking has
1117         *     been populated; false otherwise
1118         */
1119        public boolean getRanking(String key, Ranking outRanking) {
1120            int rank = getRank(key);
1121            outRanking.populate(key, rank, !isIntercepted(key),
1122                    getVisibilityOverride(key), getSuppressedVisualEffects(key),
1123                    getImportance(key), getImportanceExplanation(key));
1124            return rank >= 0;
1125        }
1126
1127        private int getRank(String key) {
1128            synchronized (this) {
1129                if (mRanks == null) {
1130                    buildRanksLocked();
1131                }
1132            }
1133            Integer rank = mRanks.get(key);
1134            return rank != null ? rank : -1;
1135        }
1136
1137        private boolean isIntercepted(String key) {
1138            synchronized (this) {
1139                if (mIntercepted == null) {
1140                    buildInterceptedSetLocked();
1141                }
1142            }
1143            return mIntercepted.contains(key);
1144        }
1145
1146        private int getVisibilityOverride(String key) {
1147            synchronized (this) {
1148                if (mVisibilityOverrides == null) {
1149                    buildVisibilityOverridesLocked();
1150                }
1151            }
1152            Integer override = mVisibilityOverrides.get(key);
1153            if (override == null) {
1154                return Ranking.VISIBILITY_NO_OVERRIDE;
1155            }
1156            return override.intValue();
1157        }
1158
1159        private int getSuppressedVisualEffects(String key) {
1160            synchronized (this) {
1161                if (mSuppressedVisualEffects == null) {
1162                    buildSuppressedVisualEffectsLocked();
1163                }
1164            }
1165            Integer suppressed = mSuppressedVisualEffects.get(key);
1166            if (suppressed == null) {
1167                return 0;
1168            }
1169            return suppressed.intValue();
1170        }
1171
1172        private int getImportance(String key) {
1173            synchronized (this) {
1174                if (mImportance == null) {
1175                    buildImportanceLocked();
1176                }
1177            }
1178            Integer importance = mImportance.get(key);
1179            if (importance == null) {
1180                return Ranking.IMPORTANCE_DEFAULT;
1181            }
1182            return importance.intValue();
1183        }
1184
1185        private String getImportanceExplanation(String key) {
1186            synchronized (this) {
1187                if (mImportanceExplanation == null) {
1188                    buildImportanceExplanationLocked();
1189                }
1190            }
1191            return mImportanceExplanation.get(key);
1192        }
1193
1194        // Locked by 'this'
1195        private void buildRanksLocked() {
1196            String[] orderedKeys = mRankingUpdate.getOrderedKeys();
1197            mRanks = new ArrayMap<>(orderedKeys.length);
1198            for (int i = 0; i < orderedKeys.length; i++) {
1199                String key = orderedKeys[i];
1200                mRanks.put(key, i);
1201            }
1202        }
1203
1204        // Locked by 'this'
1205        private void buildInterceptedSetLocked() {
1206            String[] dndInterceptedKeys = mRankingUpdate.getInterceptedKeys();
1207            mIntercepted = new ArraySet<>(dndInterceptedKeys.length);
1208            Collections.addAll(mIntercepted, dndInterceptedKeys);
1209        }
1210
1211        // Locked by 'this'
1212        private void buildVisibilityOverridesLocked() {
1213            Bundle visibilityBundle = mRankingUpdate.getVisibilityOverrides();
1214            mVisibilityOverrides = new ArrayMap<>(visibilityBundle.size());
1215            for (String key: visibilityBundle.keySet()) {
1216               mVisibilityOverrides.put(key, visibilityBundle.getInt(key));
1217            }
1218        }
1219
1220        // Locked by 'this'
1221        private void buildSuppressedVisualEffectsLocked() {
1222            Bundle suppressedBundle = mRankingUpdate.getSuppressedVisualEffects();
1223            mSuppressedVisualEffects = new ArrayMap<>(suppressedBundle.size());
1224            for (String key: suppressedBundle.keySet()) {
1225                mSuppressedVisualEffects.put(key, suppressedBundle.getInt(key));
1226            }
1227        }
1228        // Locked by 'this'
1229        private void buildImportanceLocked() {
1230            String[] orderedKeys = mRankingUpdate.getOrderedKeys();
1231            int[] importance = mRankingUpdate.getImportance();
1232            mImportance = new ArrayMap<>(orderedKeys.length);
1233            for (int i = 0; i < orderedKeys.length; i++) {
1234                String key = orderedKeys[i];
1235                mImportance.put(key, importance[i]);
1236            }
1237        }
1238
1239        // Locked by 'this'
1240        private void buildImportanceExplanationLocked() {
1241            Bundle explanationBundle = mRankingUpdate.getImportanceExplanation();
1242            mImportanceExplanation = new ArrayMap<>(explanationBundle.size());
1243            for (String key: explanationBundle.keySet()) {
1244                mImportanceExplanation.put(key, explanationBundle.getString(key));
1245            }
1246        }
1247
1248        // ----------- Parcelable
1249
1250        @Override
1251        public int describeContents() {
1252            return 0;
1253        }
1254
1255        @Override
1256        public void writeToParcel(Parcel dest, int flags) {
1257            dest.writeParcelable(mRankingUpdate, flags);
1258        }
1259
1260        public static final Creator<RankingMap> CREATOR = new Creator<RankingMap>() {
1261            @Override
1262            public RankingMap createFromParcel(Parcel source) {
1263                NotificationRankingUpdate rankingUpdate = source.readParcelable(null);
1264                return new RankingMap(rankingUpdate);
1265            }
1266
1267            @Override
1268            public RankingMap[] newArray(int size) {
1269                return new RankingMap[size];
1270            }
1271        };
1272    }
1273}
1274