NotificationListenerService.java revision 85a384b4256121eb85b7e72bcd50f3348f365d41
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.Service;
25import android.content.ComponentName;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.ParceledListSlice;
29import android.os.IBinder;
30import android.os.Parcel;
31import android.os.Parcelable;
32import android.os.RemoteException;
33import android.os.ServiceManager;
34import android.util.ArrayMap;
35import android.util.ArraySet;
36import android.util.Log;
37
38import java.util.Collections;
39import java.util.List;
40
41/**
42 * A service that receives calls from the system when new notifications are
43 * posted or removed, or their ranking changed.
44 * <p>To extend this class, you must declare the service in your manifest file with
45 * the {@link android.Manifest.permission#BIND_NOTIFICATION_LISTENER_SERVICE} permission
46 * and include an intent filter with the {@link #SERVICE_INTERFACE} action. For example:</p>
47 * <pre>
48 * &lt;service android:name=".NotificationListener"
49 *          android:label="&#64;string/service_name"
50 *          android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
51 *     &lt;intent-filter>
52 *         &lt;action android:name="android.service.notification.NotificationListenerService" />
53 *     &lt;/intent-filter>
54 * &lt;/service></pre>
55 */
56public abstract class NotificationListenerService extends Service {
57    // TAG = "NotificationListenerService[MySubclass]"
58    private final String TAG = NotificationListenerService.class.getSimpleName()
59            + "[" + getClass().getSimpleName() + "]";
60
61    /**
62     * {@link #getCurrentInterruptionFilter() Interruption filter} constant -
63     *     Normal interruption filter.
64     */
65    public static final int INTERRUPTION_FILTER_ALL = 1;
66
67    /**
68     * {@link #getCurrentInterruptionFilter() Interruption filter} constant -
69     *     Priority interruption filter.
70     */
71    public static final int INTERRUPTION_FILTER_PRIORITY = 2;
72
73    /**
74     * {@link #getCurrentInterruptionFilter() Interruption filter} constant -
75     *     No interruptions filter.
76     */
77    public static final int INTERRUPTION_FILTER_NONE = 3;
78
79    /** {@link #getCurrentListenerHints() Listener hints} constant - the primary device UI
80     * should disable notification sound, vibrating and other visual or aural effects.
81     * This does not change the interruption filter, only the effects. **/
82    public static final int HINT_HOST_DISABLE_EFFECTS = 1;
83
84    private INotificationListenerWrapper mWrapper = null;
85    private RankingMap mRankingMap;
86
87    private INotificationManager mNoMan;
88
89    /** Only valid after a successful call to (@link registerAsService}. */
90    private int mCurrentUser;
91
92
93    // This context is required for system services since NotificationListenerService isn't
94    // started as a real Service and hence no context is available.
95    private Context mSystemContext;
96
97    /**
98     * The {@link Intent} that must be declared as handled by the service.
99     */
100    @SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION)
101    public static final String SERVICE_INTERFACE
102            = "android.service.notification.NotificationListenerService";
103
104    /**
105     * Implement this method to learn about new notifications as they are posted by apps.
106     *
107     * @param sbn A data structure encapsulating the original {@link android.app.Notification}
108     *            object as well as its identifying information (tag and id) and source
109     *            (package name).
110     */
111    public void onNotificationPosted(StatusBarNotification sbn) {
112        // optional
113    }
114
115    /**
116     * Implement this method to learn about new notifications as they are posted by apps.
117     *
118     * @param sbn A data structure encapsulating the original {@link android.app.Notification}
119     *            object as well as its identifying information (tag and id) and source
120     *            (package name).
121     * @param rankingMap The current ranking map that can be used to retrieve ranking information
122     *                   for active notifications, including the newly posted one.
123     */
124    public void onNotificationPosted(StatusBarNotification sbn, RankingMap rankingMap) {
125        onNotificationPosted(sbn);
126    }
127
128    /**
129     * Implement this method to learn when notifications are removed.
130     * <P>
131     * This might occur because the user has dismissed the notification using system UI (or another
132     * notification listener) or because the app has withdrawn the notification.
133     * <P>
134     * NOTE: The {@link StatusBarNotification} object you receive will be "light"; that is, the
135     * result from {@link StatusBarNotification#getNotification} may be missing some heavyweight
136     * fields such as {@link android.app.Notification#contentView} and
137     * {@link android.app.Notification#largeIcon}. However, all other fields on
138     * {@link StatusBarNotification}, sufficient to match this call with a prior call to
139     * {@link #onNotificationPosted(StatusBarNotification)}, will be intact.
140     *
141     * @param sbn A data structure encapsulating at least the original information (tag and id)
142     *            and source (package name) used to post the {@link android.app.Notification} that
143     *            was just removed.
144     */
145    public void onNotificationRemoved(StatusBarNotification sbn) {
146        // optional
147    }
148
149    /**
150     * Implement this method to learn when notifications are removed.
151     * <P>
152     * This might occur because the user has dismissed the notification using system UI (or another
153     * notification listener) or because the app has withdrawn the notification.
154     * <P>
155     * NOTE: The {@link StatusBarNotification} object you receive will be "light"; that is, the
156     * result from {@link StatusBarNotification#getNotification} may be missing some heavyweight
157     * fields such as {@link android.app.Notification#contentView} and
158     * {@link android.app.Notification#largeIcon}. However, all other fields on
159     * {@link StatusBarNotification}, sufficient to match this call with a prior call to
160     * {@link #onNotificationPosted(StatusBarNotification)}, will be intact.
161     *
162     * @param sbn A data structure encapsulating at least the original information (tag and id)
163     *            and source (package name) used to post the {@link android.app.Notification} that
164     *            was just removed.
165     * @param rankingMap The current ranking map that can be used to retrieve ranking information
166     *                   for active notifications.
167     *
168     */
169    public void onNotificationRemoved(StatusBarNotification sbn, RankingMap rankingMap) {
170        onNotificationRemoved(sbn);
171    }
172
173    /**
174     * Implement this method to learn about when the listener is enabled and connected to
175     * the notification manager.  You are safe to call {@link #getActiveNotifications()}
176     * at this time.
177     */
178    public void onListenerConnected() {
179        // optional
180    }
181
182    /**
183     * Implement this method to be notified when the notification ranking changes.
184     *
185     * @param rankingMap The current ranking map that can be used to retrieve ranking information
186     *                   for active notifications.
187     */
188    public void onNotificationRankingUpdate(RankingMap rankingMap) {
189        // optional
190    }
191
192    /**
193     * Implement this method to be notified when the
194     * {@link #getCurrentListenerHints() Listener hints} change.
195     *
196     * @param hints The current {@link #getCurrentListenerHints() listener hints}.
197     */
198    public void onListenerHintsChanged(int hints) {
199        // optional
200    }
201
202    /**
203     * Implement this method to be notified when the
204     * {@link #getCurrentInterruptionFilter() interruption filter} changed.
205     *
206     * @param interruptionFilter The current
207     *     {@link #getCurrentInterruptionFilter() interruption filter}.
208     */
209    public void onInterruptionFilterChanged(int interruptionFilter) {
210        // optional
211    }
212
213    private final INotificationManager getNotificationInterface() {
214        if (mNoMan == null) {
215            mNoMan = INotificationManager.Stub.asInterface(
216                    ServiceManager.getService(Context.NOTIFICATION_SERVICE));
217        }
218        return mNoMan;
219    }
220
221    /**
222     * Inform the notification manager about dismissal of a single notification.
223     * <p>
224     * Use this if your listener has a user interface that allows the user to dismiss individual
225     * notifications, similar to the behavior of Android's status bar and notification panel.
226     * It should be called after the user dismisses a single notification using your UI;
227     * upon being informed, the notification manager will actually remove the notification
228     * and you will get an {@link #onNotificationRemoved(StatusBarNotification)} callback.
229     * <P>
230     * <b>Note:</b> If your listener allows the user to fire a notification's
231     * {@link android.app.Notification#contentIntent} by tapping/clicking/etc., you should call
232     * this method at that time <i>if</i> the Notification in question has the
233     * {@link android.app.Notification#FLAG_AUTO_CANCEL} flag set.
234     *
235     * @param pkg Package of the notifying app.
236     * @param tag Tag of the notification as specified by the notifying app in
237     *     {@link android.app.NotificationManager#notify(String, int, android.app.Notification)}.
238     * @param id  ID of the notification as specified by the notifying app in
239     *     {@link android.app.NotificationManager#notify(String, int, android.app.Notification)}.
240     * <p>
241     * @deprecated Use {@link #cancelNotification(String key)}
242     * instead. Beginning with {@link android.os.Build.VERSION_CODES#L} this method will no longer
243     * cancel the notification. It will continue to cancel the notification for applications
244     * whose {@code targetSdkVersion} is earlier than {@link android.os.Build.VERSION_CODES#L}.
245     */
246    public final void cancelNotification(String pkg, String tag, int id) {
247        if (!isBound()) return;
248        try {
249            getNotificationInterface().cancelNotificationFromListener(
250                    mWrapper, pkg, tag, id);
251        } catch (android.os.RemoteException ex) {
252            Log.v(TAG, "Unable to contact notification manager", ex);
253        }
254    }
255
256    /**
257     * Inform the notification manager about dismissal of a single notification.
258     * <p>
259     * Use this if your listener has a user interface that allows the user to dismiss individual
260     * notifications, similar to the behavior of Android's status bar and notification panel.
261     * It should be called after the user dismisses a single notification using your UI;
262     * upon being informed, the notification manager will actually remove the notification
263     * and you will get an {@link #onNotificationRemoved(StatusBarNotification)} callback.
264     * <P>
265     * <b>Note:</b> If your listener allows the user to fire a notification's
266     * {@link android.app.Notification#contentIntent} by tapping/clicking/etc., you should call
267     * this method at that time <i>if</i> the Notification in question has the
268     * {@link android.app.Notification#FLAG_AUTO_CANCEL} flag set.
269     * <p>
270     * @param key Notification to dismiss from {@link StatusBarNotification#getKey()}.
271     */
272    public final void cancelNotification(String key) {
273        if (!isBound()) return;
274        try {
275            getNotificationInterface().cancelNotificationsFromListener(mWrapper,
276                    new String[] {key});
277        } catch (android.os.RemoteException ex) {
278            Log.v(TAG, "Unable to contact notification manager", ex);
279        }
280    }
281
282    /**
283     * Inform the notification manager about dismissal of all notifications.
284     * <p>
285     * Use this if your listener has a user interface that allows the user to dismiss all
286     * notifications, similar to the behavior of Android's status bar and notification panel.
287     * It should be called after the user invokes the "dismiss all" function of your UI;
288     * upon being informed, the notification manager will actually remove all active notifications
289     * and you will get multiple {@link #onNotificationRemoved(StatusBarNotification)} callbacks.
290     *
291     * {@see #cancelNotification(String, String, int)}
292     */
293    public final void cancelAllNotifications() {
294        cancelNotifications(null /*all*/);
295    }
296
297    /**
298     * Inform the notification manager about dismissal of specific notifications.
299     * <p>
300     * Use this if your listener has a user interface that allows the user to dismiss
301     * multiple notifications at once.
302     *
303     * @param keys Notifications to dismiss, or {@code null} to dismiss all.
304     *
305     * {@see #cancelNotification(String, String, int)}
306     */
307    public final void cancelNotifications(String[] keys) {
308        if (!isBound()) return;
309        try {
310            getNotificationInterface().cancelNotificationsFromListener(mWrapper, keys);
311        } catch (android.os.RemoteException ex) {
312            Log.v(TAG, "Unable to contact notification manager", ex);
313        }
314    }
315
316    /**
317     * Request the list of outstanding notifications (that is, those that are visible to the
318     * current user). Useful when you don't know what's already been posted.
319     *
320     * @return An array of active notifications, sorted in natural order.
321     */
322    public StatusBarNotification[] getActiveNotifications() {
323        return getActiveNotifications(null);
324    }
325
326    /**
327     * Request one or more notifications by key. Useful if you have been keeping track of
328     * notifications but didn't want to retain the bits, and now need to go back and extract
329     * more data out of those notifications.
330     *
331     * @return An array of notifications corresponding to the requested keys, in the
332     * same order as the key list.
333     */
334    public StatusBarNotification[] getActiveNotifications(String[] keys) {
335        if (!isBound()) return null;
336        try {
337            ParceledListSlice<StatusBarNotification> parceledList =
338                    getNotificationInterface().getActiveNotificationsFromListener(mWrapper, keys);
339            List<StatusBarNotification> list = parceledList.getList();
340
341            int N = list.size();
342            for (int i = 0; i < N; i++) {
343                Notification notification = list.get(i).getNotification();
344                Builder.rebuild(getContext(), notification);
345            }
346            return list.toArray(new StatusBarNotification[N]);
347        } catch (android.os.RemoteException ex) {
348            Log.v(TAG, "Unable to contact notification manager", ex);
349        }
350        return null;
351    }
352
353    /**
354     * Gets the set of hints representing current state.
355     *
356     * <p>
357     * The current state may differ from the requested state if the hint represents state
358     * shared across all listeners or a feature the notification host does not support or refuses
359     * to grant.
360     *
361     * @return Zero or more of the HINT_ constants.
362     */
363    public final int getCurrentListenerHints() {
364        if (!isBound()) return 0;
365        try {
366            return getNotificationInterface().getHintsFromListener(mWrapper);
367        } catch (android.os.RemoteException ex) {
368            Log.v(TAG, "Unable to contact notification manager", ex);
369            return 0;
370        }
371    }
372
373    /**
374     * Gets the current notification interruption filter active on the host.
375     *
376     * <p>
377     * The interruption filter defines which notifications are allowed to interrupt the user
378     * (e.g. via sound &amp; vibration) and is applied globally. Listeners can find out whether
379     * a specific notification matched the interruption filter via
380     * {@link Ranking#matchesInterruptionFilter()}.
381     * <p>
382     * The current filter may differ from the previously requested filter if the notification host
383     * does not support or refuses to apply the requested filter, or if another component changed
384     * the filter in the meantime.
385     * <p>
386     * Listen for updates using {@link #onInterruptionFilterChanged(int)}.
387     *
388     * @return One of the INTERRUPTION_FILTER_ constants, or 0 on errors.
389     */
390    public final int getCurrentInterruptionFilter() {
391        if (!isBound()) return 0;
392        try {
393            return getNotificationInterface().getHintsFromListener(mWrapper);
394        } catch (android.os.RemoteException ex) {
395            Log.v(TAG, "Unable to contact notification manager", ex);
396            return 0;
397        }
398    }
399
400    /**
401     * Sets the desired {@link #getCurrentListenerHints() listener hints}.
402     *
403     * <p>
404     * This is merely a request, the host may or may not choose to take action depending
405     * on other listener requests or other global state.
406     * <p>
407     * Listen for updates using {@link #onListenerHintsChanged(int)}.
408     *
409     * @param hints One or more of the HINT_ constants.
410     */
411    public final void requestListenerHints(int hints) {
412        if (!isBound()) return;
413        try {
414            getNotificationInterface().requestHintsFromListener(mWrapper, hints);
415        } catch (android.os.RemoteException ex) {
416            Log.v(TAG, "Unable to contact notification manager", ex);
417        }
418    }
419
420    /**
421     * Sets the desired {@link #getCurrentInterruptionFilter() interruption filter}.
422     *
423     * <p>
424     * This is merely a request, the host may or may not choose to apply the requested
425     * interruption filter depending on other listener requests or other global state.
426     * <p>
427     * Listen for updates using {@link #onInterruptionFilterChanged(int)}.
428     *
429     * @param interruptionFilter One of the INTERRUPTION_FILTER_ constants.
430     */
431    public final void requestInterruptionFilter(int interruptionFilter) {
432        if (!isBound()) return;
433        try {
434            getNotificationInterface()
435                    .requestInterruptionFilterFromListener(mWrapper, interruptionFilter);
436        } catch (android.os.RemoteException ex) {
437            Log.v(TAG, "Unable to contact notification manager", ex);
438        }
439    }
440
441    /**
442     * Returns current ranking information.
443     *
444     * <p>
445     * The returned object represents the current ranking snapshot and only
446     * applies for currently active notifications.
447     * <p>
448     * Generally you should use the RankingMap that is passed with events such
449     * as {@link #onNotificationPosted(StatusBarNotification, RankingMap)},
450     * {@link #onNotificationRemoved(StatusBarNotification, RankingMap)}, and
451     * so on. This method should only be used when needing access outside of
452     * such events, for example to retrieve the RankingMap right after
453     * initialization.
454     *
455     * @return A {@link RankingMap} object providing access to ranking information
456     */
457    public RankingMap getCurrentRanking() {
458        return mRankingMap;
459    }
460
461    @Override
462    public IBinder onBind(Intent intent) {
463        if (mWrapper == null) {
464            mWrapper = new INotificationListenerWrapper();
465        }
466        return mWrapper;
467    }
468
469    private boolean isBound() {
470        if (mWrapper == null) {
471            Log.w(TAG, "Notification listener service not yet bound.");
472            return false;
473        }
474        return true;
475    }
476
477    /**
478     * Directly register this service with the Notification Manager.
479     *
480     * <p>Only system services may use this call. It will fail for non-system callers.
481     * Apps should ask the user to add their listener in Settings.
482     *
483     * @param context Context required for accessing resources. Since this service isn't
484     *    launched as a real Service when using this method, a context has to be passed in.
485     * @param componentName the component that will consume the notification information
486     * @param currentUser the user to use as the stream filter
487     * @hide
488     */
489    @SystemApi
490    public void registerAsSystemService(Context context, ComponentName componentName,
491            int currentUser) throws RemoteException {
492        mSystemContext = context;
493        if (mWrapper == null) {
494            mWrapper = new INotificationListenerWrapper();
495        }
496        INotificationManager noMan = getNotificationInterface();
497        noMan.registerListener(mWrapper, componentName, currentUser);
498        mCurrentUser = currentUser;
499    }
500
501    /**
502     * Directly unregister this service from the Notification Manager.
503     *
504     * <P>This method will fail for listeners that were not registered
505     * with (@link registerAsService).
506     * @hide
507     */
508    @SystemApi
509    public void unregisterAsSystemService() throws RemoteException {
510        if (mWrapper != null) {
511            INotificationManager noMan = getNotificationInterface();
512            noMan.unregisterListener(mWrapper, mCurrentUser);
513        }
514    }
515
516    private class INotificationListenerWrapper extends INotificationListener.Stub {
517        @Override
518        public void onNotificationPosted(StatusBarNotification sbn,
519                NotificationRankingUpdate update) {
520            Notification.Builder.rebuild(getContext(), sbn.getNotification());
521
522            // protect subclass from concurrent modifications of (@link mNotificationKeys}.
523            synchronized (mWrapper) {
524                applyUpdate(update);
525                try {
526                    NotificationListenerService.this.onNotificationPosted(sbn, mRankingMap);
527                } catch (Throwable t) {
528                    Log.w(TAG, "Error running onNotificationPosted", t);
529                }
530            }
531        }
532        @Override
533        public void onNotificationRemoved(StatusBarNotification sbn,
534                NotificationRankingUpdate update) {
535            // protect subclass from concurrent modifications of (@link mNotificationKeys}.
536            synchronized (mWrapper) {
537                applyUpdate(update);
538                try {
539                    NotificationListenerService.this.onNotificationRemoved(sbn, mRankingMap);
540                } catch (Throwable t) {
541                    Log.w(TAG, "Error running onNotificationRemoved", t);
542                }
543            }
544        }
545        @Override
546        public void onListenerConnected(NotificationRankingUpdate update) {
547            // protect subclass from concurrent modifications of (@link mNotificationKeys}.
548            synchronized (mWrapper) {
549                applyUpdate(update);
550                try {
551                    NotificationListenerService.this.onListenerConnected();
552                } catch (Throwable t) {
553                    Log.w(TAG, "Error running onListenerConnected", t);
554                }
555            }
556        }
557        @Override
558        public void onNotificationRankingUpdate(NotificationRankingUpdate update)
559                throws RemoteException {
560            // protect subclass from concurrent modifications of (@link mNotificationKeys}.
561            synchronized (mWrapper) {
562                applyUpdate(update);
563                try {
564                    NotificationListenerService.this.onNotificationRankingUpdate(mRankingMap);
565                } catch (Throwable t) {
566                    Log.w(TAG, "Error running onNotificationRankingUpdate", t);
567                }
568            }
569        }
570        @Override
571        public void onListenerHintsChanged(int hints) throws RemoteException {
572            try {
573                NotificationListenerService.this.onListenerHintsChanged(hints);
574            } catch (Throwable t) {
575                Log.w(TAG, "Error running onListenerHintsChanged", t);
576            }
577        }
578
579        @Override
580        public void onInterruptionFilterChanged(int interruptionFilter) throws RemoteException {
581            try {
582                NotificationListenerService.this.onInterruptionFilterChanged(interruptionFilter);
583            } catch (Throwable t) {
584                Log.w(TAG, "Error running onInterruptionFilterChanged", t);
585            }
586        }
587    }
588
589    private void applyUpdate(NotificationRankingUpdate update) {
590        mRankingMap = new RankingMap(update);
591    }
592
593    private Context getContext() {
594        if (mSystemContext != null) {
595            return mSystemContext;
596        }
597        return this;
598    }
599
600    /**
601     * Stores ranking related information on a currently active notification.
602     *
603     * <p>
604     * Ranking objects aren't automatically updated as notification events
605     * occur. Instead, ranking information has to be retrieved again via the
606     * current {@link RankingMap}.
607     */
608    public static class Ranking {
609        private String mKey;
610        private int mRank = -1;
611        private boolean mIsAmbient;
612        private boolean mMatchesInterruptionFilter;
613
614        public Ranking() {}
615
616        /**
617         * Returns the key of the notification this Ranking applies to.
618         */
619        public String getKey() {
620            return mKey;
621        }
622
623        /**
624         * Returns the rank of the notification.
625         *
626         * @return the rank of the notification, that is the 0-based index in
627         *     the list of active notifications.
628         */
629        public int getRank() {
630            return mRank;
631        }
632
633        /**
634         * Returns whether the notification is an ambient notification, that is
635         * a notification that doesn't require the user's immediate attention.
636         */
637        public boolean isAmbient() {
638            return mIsAmbient;
639        }
640
641        /**
642         * Returns whether the notification meets the user's interruption
643         * filter.
644         *
645         * @removed
646         */
647        public boolean meetsInterruptionFilter() {
648            return mMatchesInterruptionFilter;
649        }
650
651        /**
652         * Returns whether the notification matches the user's interruption
653         * filter.
654         */
655        public boolean matchesInterruptionFilter() {
656            return mMatchesInterruptionFilter;
657        }
658
659        private void populate(String key, int rank, boolean isAmbient,
660                boolean matchesInterruptionFilter) {
661            mKey = key;
662            mRank = rank;
663            mIsAmbient = isAmbient;
664            mMatchesInterruptionFilter = matchesInterruptionFilter;
665        }
666    }
667
668    /**
669     * Provides access to ranking information on currently active
670     * notifications.
671     *
672     * <p>
673     * Note that this object represents a ranking snapshot that only applies to
674     * notifications active at the time of retrieval.
675     */
676    public static class RankingMap implements Parcelable {
677        private final NotificationRankingUpdate mRankingUpdate;
678        private ArrayMap<String,Integer> mRanks;
679        private ArraySet<Object> mIntercepted;
680
681        private RankingMap(NotificationRankingUpdate rankingUpdate) {
682            mRankingUpdate = rankingUpdate;
683        }
684
685        /**
686         * Request the list of notification keys in their current ranking
687         * order.
688         *
689         * @return An array of active notification keys, in their ranking order.
690         */
691        public String[] getOrderedKeys() {
692            return mRankingUpdate.getOrderedKeys();
693        }
694
695        /**
696         * Populates outRanking with ranking information for the notification
697         * with the given key.
698         *
699         * @return true if a valid key has been passed and outRanking has
700         *     been populated; false otherwise
701         */
702        public boolean getRanking(String key, Ranking outRanking) {
703            int rank = getRank(key);
704            outRanking.populate(key, rank, isAmbient(key), !isIntercepted(key));
705            return rank >= 0;
706        }
707
708        private int getRank(String key) {
709            synchronized (this) {
710                if (mRanks == null) {
711                    buildRanksLocked();
712                }
713            }
714            Integer rank = mRanks.get(key);
715            return rank != null ? rank : -1;
716        }
717
718        private boolean isAmbient(String key) {
719            int firstAmbientIndex = mRankingUpdate.getFirstAmbientIndex();
720            if (firstAmbientIndex < 0) {
721                return false;
722            }
723            int rank = getRank(key);
724            return rank >= 0 && rank >= firstAmbientIndex;
725        }
726
727        private boolean isIntercepted(String key) {
728            synchronized (this) {
729                if (mIntercepted == null) {
730                    buildInterceptedSetLocked();
731                }
732            }
733            return mIntercepted.contains(key);
734        }
735
736        // Locked by 'this'
737        private void buildRanksLocked() {
738            String[] orderedKeys = mRankingUpdate.getOrderedKeys();
739            mRanks = new ArrayMap<>(orderedKeys.length);
740            for (int i = 0; i < orderedKeys.length; i++) {
741                String key = orderedKeys[i];
742                mRanks.put(key, i);
743            }
744        }
745
746        // Locked by 'this'
747        private void buildInterceptedSetLocked() {
748            String[] dndInterceptedKeys = mRankingUpdate.getInterceptedKeys();
749            mIntercepted = new ArraySet<>(dndInterceptedKeys.length);
750            Collections.addAll(mIntercepted, dndInterceptedKeys);
751        }
752
753        // ----------- Parcelable
754
755        @Override
756        public int describeContents() {
757            return 0;
758        }
759
760        @Override
761        public void writeToParcel(Parcel dest, int flags) {
762            dest.writeParcelable(mRankingUpdate, flags);
763        }
764
765        public static final Creator<RankingMap> CREATOR = new Creator<RankingMap>() {
766            @Override
767            public RankingMap createFromParcel(Parcel source) {
768                NotificationRankingUpdate rankingUpdate = source.readParcelable(null);
769                return new RankingMap(rankingUpdate);
770            }
771
772            @Override
773            public RankingMap[] newArray(int size) {
774                return new RankingMap[size];
775            }
776        };
777    }
778}
779