NotificationAssistantService.java revision 1327d3c3fabc9b4ffeb20e589f7b2350567b681f
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.NonNull;
20import android.annotation.Nullable;
21import android.annotation.SdkConstant;
22import android.annotation.SystemApi;
23import android.annotation.TestApi;
24import android.app.NotificationChannel;
25import android.content.Context;
26import android.content.Intent;
27import android.os.Handler;
28import android.os.IBinder;
29import android.os.Looper;
30import android.os.Message;
31import android.os.RemoteException;
32import android.util.Log;
33import com.android.internal.os.SomeArgs;
34
35import java.util.ArrayList;
36import java.util.List;
37
38/**
39 * A service that helps the user manage notifications.
40 * @hide
41 */
42@SystemApi
43@TestApi
44public abstract class NotificationAssistantService extends NotificationListenerService {
45    private static final String TAG = "NotificationAssistants";
46
47    /**
48     * The {@link Intent} that must be declared as handled by the service.
49     */
50    @SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION)
51    public static final String SERVICE_INTERFACE
52            = "android.service.notification.NotificationAssistantService";
53
54    private Handler mHandler;
55
56    @Override
57    protected void attachBaseContext(Context base) {
58        super.attachBaseContext(base);
59        mHandler = new MyHandler(getContext().getMainLooper());
60    }
61
62    @Override
63    public final IBinder onBind(Intent intent) {
64        if (mWrapper == null) {
65            mWrapper = new NotificationAssistantServiceWrapper();
66        }
67        return mWrapper;
68    }
69
70    /**
71     * A notification was snoozed until a context. For use with
72     * {@link Adjustment#KEY_SNOOZE_CRITERIA}. When the device reaches the given context, the
73     * assistant should restore the notification with {@link #unsnoozeNotification(String)}.
74     *
75     * @param sbn the notification to snooze
76     * @param snoozeCriterionId the {@link SnoozeCriterion#getId()} representing a device context.
77     */
78    abstract public void onNotificationSnoozedUntilContext(StatusBarNotification sbn,
79            String snoozeCriterionId);
80
81    /**
82     * A notification was posted by an app. Called before alert.
83     *
84     * @param sbn the new notification
85     * @return an adjustment or null to take no action, within 100ms.
86     */
87    abstract public Adjustment onNotificationEnqueued(StatusBarNotification sbn);
88
89    /**
90     * Updates a notification.  N.B. this won’t cause
91     * an existing notification to alert, but might allow a future update to
92     * this notification to alert.
93     *
94     * @param adjustment the adjustment with an explanation
95     */
96    public final void adjustNotification(Adjustment adjustment) {
97        if (!isBound()) return;
98        try {
99            getNotificationInterface().applyAdjustmentFromAssistant(mWrapper, adjustment);
100        } catch (android.os.RemoteException ex) {
101            Log.v(TAG, "Unable to contact notification manager", ex);
102            throw ex.rethrowFromSystemServer();
103        }
104    }
105
106    /**
107     * Updates existing notifications. Re-ranking won't occur until all adjustments are applied.
108     * N.B. this won’t cause an existing notification to alert, but might allow a future update to
109     * these notifications to alert.
110     *
111     * @param adjustments a list of adjustments with explanations
112     */
113    public final void adjustNotifications(List<Adjustment> adjustments) {
114        if (!isBound()) return;
115        try {
116            getNotificationInterface().applyAdjustmentsFromAssistant(mWrapper, adjustments);
117        } catch (android.os.RemoteException ex) {
118            Log.v(TAG, "Unable to contact notification manager", ex);
119            throw ex.rethrowFromSystemServer();
120        }
121    }
122
123    /**
124     * Inform the notification manager about un-snoozing a specific notification.
125     * <p>
126     * This should only be used for notifications snoozed by this listener using
127     * {@link #snoozeNotification(String, String)}. Once un-snoozed, you will get a
128     * {@link #onNotificationPosted(StatusBarNotification, RankingMap)} callback for the
129     * notification.
130     * @param key The key of the notification to snooze
131     */
132    public final void unsnoozeNotification(String key) {
133        if (!isBound()) return;
134        try {
135            getNotificationInterface().unsnoozeNotificationFromAssistant(mWrapper, key);
136        } catch (android.os.RemoteException ex) {
137            Log.v(TAG, "Unable to contact notification manager", ex);
138        }
139    }
140
141    /**
142     * Creates a notification channel that notifications can be posted to for a given package.
143     *
144     * @param pkg The package to create a channel for.
145     * @param channel  the channel to attempt to create.
146     */
147    public void createNotificationChannel(@NonNull String pkg,
148            @NonNull NotificationChannel channel) {
149        if (!isBound()) return;
150        try {
151            getNotificationInterface().createNotificationChannelFromAssistant(
152                    mWrapper, pkg, channel);
153        } catch (RemoteException e) {
154            Log.v(TAG, "Unable to contact notification manager", e);
155            throw e.rethrowFromSystemServer();
156        }
157    }
158
159    /**
160     * Updates a notification channel for a given package.
161     *
162     * @param pkg The package to the channel belongs to.
163     * @param channel the channel to attempt to update.
164     */
165    public void updateNotificationChannel(@NonNull String pkg,
166            @NonNull NotificationChannel channel) {
167        if (!isBound()) return;
168        try {
169            getNotificationInterface().updateNotificationChannelFromAssistant(
170                    mWrapper, pkg, channel);
171        } catch (RemoteException e) {
172            Log.v(TAG, "Unable to contact notification manager", e);
173            throw e.rethrowFromSystemServer();
174        }
175    }
176
177    /**
178     * Returns all notification channels belonging to the given package.
179     */
180    public List<NotificationChannel> getNotificationChannels(@NonNull String pkg) {
181        if (!isBound()) return null;
182        try {
183            return getNotificationInterface().getNotificationChannelsFromAssistant(
184                    mWrapper, pkg).getList();
185        } catch (RemoteException e) {
186            Log.v(TAG, "Unable to contact notification manager", e);
187            throw e.rethrowFromSystemServer();
188        }
189    }
190
191    /**
192     * Deletes the given notification channel.
193     */
194    public void deleteNotificationChannel(@NonNull String pkg, @NonNull String channelId) {
195        if (!isBound()) return;
196        try {
197            getNotificationInterface().deleteNotificationChannelFromAssistant(
198                    mWrapper, pkg, channelId);
199        } catch (RemoteException e) {
200            throw e.rethrowFromSystemServer();
201        }
202    }
203
204
205    private class NotificationAssistantServiceWrapper extends NotificationListenerWrapper {
206        @Override
207        public void onNotificationEnqueued(IStatusBarNotificationHolder sbnHolder) {
208            StatusBarNotification sbn;
209            try {
210                sbn = sbnHolder.get();
211            } catch (RemoteException e) {
212                Log.w(TAG, "onNotificationEnqueued: Error receiving StatusBarNotification", e);
213                return;
214            }
215
216            SomeArgs args = SomeArgs.obtain();
217            args.arg1 = sbn;
218            mHandler.obtainMessage(MyHandler.MSG_ON_NOTIFICATION_ENQUEUED,
219                    args).sendToTarget();
220        }
221
222        @Override
223        public void onNotificationSnoozedUntilContext(
224                IStatusBarNotificationHolder sbnHolder, String snoozeCriterionId)
225                throws RemoteException {
226            StatusBarNotification sbn;
227            try {
228                sbn = sbnHolder.get();
229            } catch (RemoteException e) {
230                Log.w(TAG, "onNotificationSnoozed: Error receiving StatusBarNotification", e);
231                return;
232            }
233
234            SomeArgs args = SomeArgs.obtain();
235            args.arg1 = sbn;
236            args.arg2 = snoozeCriterionId;
237            mHandler.obtainMessage(MyHandler.MSG_ON_NOTIFICATION_SNOOZED,
238                    args).sendToTarget();
239        }
240    }
241
242    private final class MyHandler extends Handler {
243        public static final int MSG_ON_NOTIFICATION_ENQUEUED = 1;
244        public static final int MSG_ON_NOTIFICATION_SNOOZED = 2;
245
246        public MyHandler(Looper looper) {
247            super(looper, null, false);
248        }
249
250        @Override
251        public void handleMessage(Message msg) {
252            switch (msg.what) {
253                case MSG_ON_NOTIFICATION_ENQUEUED: {
254                    SomeArgs args = (SomeArgs) msg.obj;
255                    StatusBarNotification sbn = (StatusBarNotification) args.arg1;
256                    args.recycle();
257                    Adjustment adjustment = onNotificationEnqueued(sbn);
258                    if (adjustment != null) {
259                        if (!isBound()) return;
260                        try {
261                            getNotificationInterface().applyEnqueuedAdjustmentFromAssistant(
262                                    mWrapper, adjustment);
263                        } catch (android.os.RemoteException ex) {
264                            Log.v(TAG, "Unable to contact notification manager", ex);
265                            throw ex.rethrowFromSystemServer();
266                        }
267                    }
268                    break;
269                }
270                case MSG_ON_NOTIFICATION_SNOOZED: {
271                    SomeArgs args = (SomeArgs) msg.obj;
272                    StatusBarNotification sbn = (StatusBarNotification) args.arg1;
273                    String snoozeCriterionId = (String) args.arg2;
274                    args.recycle();
275                    onNotificationSnoozedUntilContext(sbn, snoozeCriterionId);
276                    break;
277                }
278            }
279        }
280    }
281}
282