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