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