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