NotificationAssistantService.java revision 0122f651d1a1de8ccfe6e2789e150507977189c7
1/*
2 * Copyright (C) 2015 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.SdkConstant;
20import android.annotation.SystemApi;
21import android.app.INotificationManager;
22import android.app.Notification;
23import android.content.ComponentName;
24import android.content.Context;
25import android.content.Intent;
26import android.net.Uri;
27import android.os.IBinder;
28import android.os.Parcel;
29import android.os.Parcelable;
30import android.os.RemoteException;
31import android.os.ServiceManager;
32import android.util.Log;
33
34/**
35 * A service that helps the user manage notifications by modifying the
36 * relative importance of notifications.
37 * <p>To extend this class, you must declare the service in your manifest file with
38 * the {@link android.Manifest.permission#BIND_NOTIFICATION_ASSISTANT_SERVICE} permission
39 * and include an intent filter with the {@link #SERVICE_INTERFACE} action. For example:</p>
40 * <pre>
41 * &lt;service android:name=".NotificationAssistant"
42 *          android:label="&#64;string/service_name"
43 *          android:permission="android.permission.BIND_NOTIFICATION_ASSISTANT_SERVICE">
44 *     &lt;intent-filter>
45 *         &lt;action android:name="android.service.notification.NotificationAssistantService" />
46 *     &lt;/intent-filter>
47 * &lt;/service></pre>
48 */
49public abstract class NotificationAssistantService extends NotificationListenerService {
50    private static final String TAG = "NotificationAssistant";
51
52    /**
53     * The {@link Intent} that must be declared as handled by the service.
54     */
55    @SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION)
56    public static final String SERVICE_INTERFACE
57            = "android.service.notification.NotificationAssistantService";
58
59    /** Notification was canceled by the status bar reporting a click. */
60    public static final int REASON_DELEGATE_CLICK = 1;
61
62    /** Notification was canceled by the status bar reporting a user dismissal. */
63    public static final int REASON_DELEGATE_CANCEL = 2;
64
65    /** Notification was canceled by the status bar reporting a user dismiss all. */
66    public static final int REASON_DELEGATE_CANCEL_ALL = 3;
67
68    /** Notification was canceled by the status bar reporting an inflation error. */
69    public static final int REASON_DELEGATE_ERROR = 4;
70
71    /** Notification was canceled by the package manager modifying the package. */
72    public static final int REASON_PACKAGE_CHANGED = 5;
73
74    /** Notification was canceled by the owning user context being stopped. */
75    public static final int REASON_USER_STOPPED = 6;
76
77    /** Notification was canceled by the user banning the package. */
78    public static final int REASON_PACKAGE_BANNED = 7;
79
80    /** Notification was canceled by the app canceling this specific notification. */
81    public static final int REASON_APP_CANCEL = 8;
82
83    /** Notification was canceled by the app cancelling all its notifications. */
84    public static final int REASON_APP_CANCEL_ALL = 9;
85
86    /** Notification was canceled by a listener reporting a user dismissal. */
87    public static final int REASON_LISTENER_CANCEL = 10;
88
89    /** Notification was canceled by a listener reporting a user dismiss all. */
90    public static final int REASON_LISTENER_CANCEL_ALL = 11;
91
92    /** Notification was canceled because it was a member of a canceled group. */
93    public static final int REASON_GROUP_SUMMARY_CANCELED = 12;
94
95    /** Notification was canceled because it was an invisible member of a group. */
96    public static final int REASON_GROUP_OPTIMIZATION = 13;
97
98    /** Notification was canceled by the user banning the topic. */
99    public static final int REASON_TOPIC_BANNED = 14;
100
101    /** Notification was canceled by the device administrator suspending the package. */
102    public static final int REASON_PACKAGE_SUSPENDED = 15;
103
104    public class Adjustment {
105        int mImportance;
106        CharSequence mExplanation;
107        Uri mReference;
108
109        /**
110         * Create a notification importance adjustment.
111         *
112         * @param importance The final importance of the notification.
113         * @param explanation A human-readable justification for the adjustment.
114         * @param reference A reference to an external object that augments the
115         *                  explanation, such as a
116         *                  {@link android.provider.ContactsContract.Contacts#CONTENT_LOOKUP_URI},
117         *                  or null.
118         */
119        public Adjustment(int importance, CharSequence explanation, Uri reference) {
120            mImportance = importance;
121            mExplanation = explanation;
122            mReference = reference;
123        }
124    }
125
126    @Override
127    public IBinder onBind(Intent intent) {
128        if (mWrapper == null) {
129            mWrapper = new NotificationAssistantWrapper();
130        }
131        return mWrapper;
132    }
133
134    /**
135     * A notification was posted by an app. Called before alert.
136     *
137     * @param sbn the new notification
138     * @param importance the initial importance of the notification.
139     * @param user true if the initial importance reflects an explicit user preference.
140     * @return an adjustment or null to take no action, within 100ms.
141     */
142    abstract public Adjustment onNotificationEnqueued(StatusBarNotification sbn,
143          int importance, boolean user);
144
145    /**
146     * The visibility of a notification has changed.
147     *
148     * @param key the notification key
149     * @param time milliseconds since midnight, January 1, 1970 UTC.
150     * @param visible true if the notification became visible, false if hidden.
151     */
152    public void onNotificationVisibilityChanged(String key, long time, boolean visible)
153    {
154        // Do nothing, Override this to collect visibility statistics.
155    }
156
157    /**
158     * The user clicked on a notification.
159     *
160     * @param key the notification key
161     * @param time milliseconds since midnight, January 1, 1970 UTC.
162     */
163    public void onNotificationClick(String key, long time)
164    {
165        // Do nothing, Override this to collect click statistics
166    }
167
168    /**
169     * The user clicked on a notification action.
170     *
171     * @param key the notification key
172     * @param time milliseconds since midnight, January 1, 1970 UTC.
173     * @param actionIndex the index of the action button that was pressed.
174     */
175    public void onNotificationActionClick(String key, long time, int actionIndex)
176    {
177        // Do nothing, Override this to collect action button click statistics
178    }
179
180    /**
181     * A notification was removed.
182
183     * @param key the notification key
184     * @param time milliseconds since midnight, January 1, 1970 UTC.
185     * @param reason see {@link #REASON_LISTENER_CANCEL}, etc.
186     */
187    public void onNotificationRemoved(String key, long time, int reason) {
188        // Do nothing, Override this to collect dismissal statistics
189    }
190
191    /**
192     * Change the importance of an existing notification.  N.B. this won’t cause
193     * an existing notification to alert, but might allow a future update to
194     * this notification to alert.
195     *
196     * @param key the notification key
197     * @param adjustment the new importance with an explanation
198     */
199    public final void adjustImportance(String key, Adjustment adjustment)
200    {
201        if (!isBound()) return;
202        try {
203            getNotificationInterface().setImportanceFromAssistant(mWrapper, key,
204                    adjustment.mImportance, adjustment.mExplanation);
205        } catch (android.os.RemoteException ex) {
206            Log.v(TAG, "Unable to contact notification manager", ex);
207        }
208    }
209
210    /**
211     * Add an annotation to a an existing notification. The delete intent will
212     * be fired when the host notification is deleted, or when this annotation
213     * is removed or replaced.
214     *
215     * @param key the key of the notification to be annotated
216     * @param annotation the new annotation object
217     */
218    public final void setAnnotation(String key, Notification annotation)
219    {
220        // TODO: pack up the annotation and send it to the NotificationManager.
221    }
222
223    /**
224     * Remove the annotation from a notification.
225     *
226     * @param key the key of the notification to be cleansed of annotatons
227     */
228    public final void clearAnnotation(String key)
229    {
230        // TODO: ask the NotificationManager to clear the annotation.
231    }
232
233    private class NotificationAssistantWrapper extends NotificationListenerWrapper {
234        @Override
235        public void onNotificationEnqueued(IStatusBarNotificationHolder sbnHolder,
236                                           int importance, boolean user) throws RemoteException {
237            StatusBarNotification sbn;
238            try {
239                sbn = sbnHolder.get();
240            } catch (RemoteException e) {
241                Log.w(TAG, "onNotificationEnqueued: Error receiving StatusBarNotification", e);
242                return;
243            }
244
245            try {
246                Adjustment adjustment =
247                    NotificationAssistantService.this.onNotificationEnqueued(sbn, importance, user);
248                if (adjustment != null) {
249                    adjustImportance(sbn.getKey(), adjustment);
250                }
251            } catch (Throwable t) {
252                Log.w(TAG, "Error running onNotificationEnqueued", t);
253            }
254        }
255
256        @Override
257        public void onNotificationVisibilityChanged(String key, long time, boolean visible)
258                throws RemoteException {
259            try {
260                NotificationAssistantService.this.onNotificationVisibilityChanged(key, time,
261                        visible);
262            } catch (Throwable t) {
263                Log.w(TAG, "Error running onNotificationVisibilityChanged", t);
264            }
265        }
266
267        @Override
268        public void onNotificationClick(String key, long time) throws RemoteException {
269            try {
270                NotificationAssistantService.this.onNotificationClick(key, time);
271            } catch (Throwable t) {
272                Log.w(TAG, "Error running onNotificationClick", t);
273            }
274        }
275
276        @Override
277        public void onNotificationActionClick(String key, long time, int actionIndex)
278                throws RemoteException {
279            try {
280                NotificationAssistantService.this.onNotificationActionClick(key, time, actionIndex);
281            } catch (Throwable t) {
282                Log.w(TAG, "Error running onNotificationActionClick", t);
283            }
284        }
285
286        @Override
287        public void onNotificationRemovedReason(String key, long time, int reason)
288                throws RemoteException {
289            try {
290                NotificationAssistantService.this.onNotificationRemoved(key, time, reason);
291            } catch (Throwable t) {
292                Log.w(TAG, "Error running onNotificationRemoved", t);
293            }
294        }
295    }
296}
297