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