| 1 | /* |
| 2 | * Copyright (C) 2022 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 | |
| 17 | package android.app.ambientcontext; |
| 18 | |
| 19 | import android.Manifest; |
| 20 | import android.annotation.CallbackExecutor; |
| 21 | import android.annotation.IntDef; |
| 22 | import android.annotation.NonNull; |
| 23 | import android.annotation.RequiresPermission; |
| 24 | import android.annotation.SystemApi; |
| 25 | import android.annotation.SystemService; |
| 26 | import android.app.PendingIntent; |
| 27 | import android.content.Context; |
| 28 | import android.content.Intent; |
| 29 | import android.os.Binder; |
| 30 | import android.os.RemoteCallback; |
| 31 | import android.os.RemoteException; |
| 32 | |
| 33 | import com.android.internal.util.Preconditions; |
| 34 | |
| 35 | import java.util.ArrayList; |
| 36 | import java.util.List; |
| 37 | import java.util.Set; |
| 38 | import java.util.concurrent.Executor; |
| 39 | import java.util.function.Consumer; |
| 40 | |
| 41 | /** |
| 42 | * Allows granted apps to register for event types defined in {@link AmbientContextEvent}. |
| 43 | * After registration, the app receives a Consumer callback of the service status. |
| 44 | * If it is {@link STATUS_SUCCESSFUL}, when the requested events are detected, the provided |
| 45 | * {@link PendingIntent} callback will receive the list of detected {@link AmbientContextEvent}s. |
| 46 | * If it is {@link STATUS_ACCESS_DENIED}, the app can call {@link #startConsentActivity} |
| 47 | * to load the consent screen. |
| 48 | * |
| 49 | * @hide |
| 50 | */ |
| 51 | @SystemApi |
| 52 | @SystemService(Context.AMBIENT_CONTEXT_SERVICE) |
| 53 | public final class AmbientContextManager { |
| 54 | /** |
| 55 | * The bundle key for the service status query result, used in |
| 56 | * {@code RemoteCallback#sendResult}. |
| 57 | * |
| 58 | * @hide |
| 59 | */ |
| 60 | public static final String STATUS_RESPONSE_BUNDLE_KEY = |
| 61 | "android.app.ambientcontext.AmbientContextStatusBundleKey"; |
| 62 | |
| 63 | /** |
| 64 | * The key of an intent extra indicating a list of detected {@link AmbientContextEvent}s. |
| 65 | * The intent is sent to the app in the app's registered {@link PendingIntent}. |
| 66 | */ |
| 67 | public static final String EXTRA_AMBIENT_CONTEXT_EVENTS = |
| 68 | "android.app.ambientcontext.extra.AMBIENT_CONTEXT_EVENTS"; |
| 69 | |
| 70 | /** |
| 71 | * An unknown status. |
| 72 | */ |
| 73 | public static final int STATUS_UNKNOWN = 0; |
| 74 | |
| 75 | /** |
| 76 | * The value of the status code that indicates success. |
| 77 | */ |
| 78 | public static final int STATUS_SUCCESS = 1; |
| 79 | |
| 80 | /** |
| 81 | * The value of the status code that indicates one or more of the |
| 82 | * requested events are not supported. |
| 83 | */ |
| 84 | public static final int STATUS_NOT_SUPPORTED = 2; |
| 85 | |
| 86 | /** |
| 87 | * The value of the status code that indicates service not available. |
| 88 | */ |
| 89 | public static final int STATUS_SERVICE_UNAVAILABLE = 3; |
| 90 | |
| 91 | /** |
| 92 | * The value of the status code that microphone is disabled. |
| 93 | */ |
| 94 | public static final int STATUS_MICROPHONE_DISABLED = 4; |
| 95 | |
| 96 | /** |
| 97 | * The value of the status code that the app is not granted access. |
| 98 | */ |
| 99 | public static final int STATUS_ACCESS_DENIED = 5; |
| 100 | |
| 101 | /** @hide */ |
| 102 | @IntDef(prefix = { "STATUS_" }, value = { |
| 103 | STATUS_UNKNOWN, |
| 104 | STATUS_SUCCESS, |
| 105 | STATUS_NOT_SUPPORTED, |
| 106 | STATUS_SERVICE_UNAVAILABLE, |
| 107 | STATUS_MICROPHONE_DISABLED, |
| 108 | STATUS_ACCESS_DENIED |
| 109 | }) public @interface StatusCode {} |
| 110 | |
| 111 | /** |
| 112 | * Allows clients to retrieve the list of {@link AmbientContextEvent}s from the intent. |
| 113 | * |
| 114 | * @param intent received from the PendingIntent callback |
| 115 | * |
| 116 | * @return the list of events, or an empty list if the intent doesn't have such events. |
| 117 | */ |
| 118 | @NonNull public static List<AmbientContextEvent> getEventsFromIntent(@NonNull Intent intent) { |
| 119 | if (intent.hasExtra(AmbientContextManager.EXTRA_AMBIENT_CONTEXT_EVENTS)) { |
| 120 | return intent.getParcelableArrayListExtra(EXTRA_AMBIENT_CONTEXT_EVENTS); |
| 121 | } else { |
| 122 | return new ArrayList<>(); |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | private final Context mContext; |
| 127 | private final IAmbientContextManager mService; |
| 128 | |
| 129 | /** |
| 130 | * {@hide} |
| 131 | */ |
| 132 | public AmbientContextManager(Context context, IAmbientContextManager service) { |
| 133 | mContext = context; |
| 134 | mService = service; |
| 135 | } |
| 136 | |
| 137 | /** |
| 138 | * Queries the {@link AmbientContextEvent} service status for the calling package, and |
| 139 | * sends the result to the {@link Consumer} right after the call. This is used by foreground |
| 140 | * apps to check whether the requested events are enabled for detection on the device. |
| 141 | * If all events are enabled for detection, the response has |
| 142 | * {@link AmbientContextManager#STATUS_SUCCESS}. |
| 143 | * If any of the events are not consented by user, the response has |
| 144 | * {@link AmbientContextManager#STATUS_ACCESS_DENIED}, and the app can |
| 145 | * call {@link #startConsentActivity} to redirect the user to the consent screen. |
| 146 | * <p /> |
| 147 | * |
| 148 | * Example: |
| 149 | * |
| 150 | * <pre><code> |
| 151 | * Set<Integer> eventTypes = new HashSet<>(); |
| 152 | * eventTypes.add(AmbientContextEvent.EVENT_COUGH); |
| 153 | * eventTypes.add(AmbientContextEvent.EVENT_SNORE); |
| 154 | * |
| 155 | * // Create Consumer |
| 156 | * Consumer<Integer> statusConsumer = status -> { |
| 157 | * int status = status.getStatusCode(); |
| 158 | * if (status == AmbientContextManager.STATUS_SUCCESS) { |
| 159 | * // Show user it's enabled |
| 160 | * } else if (status == AmbientContextManager.STATUS_ACCESS_DENIED) { |
| 161 | * // Send user to grant access |
| 162 | * startConsentActivity(eventTypes); |
| 163 | * } |
| 164 | * }; |
| 165 | * |
| 166 | * // Query status |
| 167 | * AmbientContextManager ambientContextManager = |
| 168 | * context.getSystemService(AmbientContextManager.class); |
| 169 | * ambientContextManager.queryAmbientContextStatus(eventTypes, executor, statusConsumer); |
| 170 | * </code></pre> |
| 171 | * |
| 172 | * @param eventTypes The set of event codes to check status on. |
| 173 | * @param executor Executor on which to run the consumer callback. |
| 174 | * @param consumer The consumer that handles the status code. |
| 175 | */ |
| 176 | @RequiresPermission(Manifest.permission.ACCESS_AMBIENT_CONTEXT_EVENT) |
| 177 | public void queryAmbientContextServiceStatus( |
| 178 | @NonNull @AmbientContextEvent.EventCode Set<Integer> eventTypes, |
| 179 | @NonNull @CallbackExecutor Executor executor, |
| 180 | @NonNull @StatusCode Consumer<Integer> consumer) { |
| 181 | try { |
| 182 | RemoteCallback callback = new RemoteCallback(result -> { |
| 183 | int status = result.getInt(STATUS_RESPONSE_BUNDLE_KEY); |
| 184 | final long identity = Binder.clearCallingIdentity(); |
| 185 | try { |
| 186 | executor.execute(() -> consumer.accept(status)); |
| 187 | } finally { |
| 188 | Binder.restoreCallingIdentity(identity); |
| 189 | } |
| 190 | }); |
| 191 | mService.queryServiceStatus(integerSetToIntArray(eventTypes), |
| 192 | mContext.getOpPackageName(), callback); |
| 193 | } catch (RemoteException e) { |
| 194 | throw e.rethrowFromSystemServer(); |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | /** |
| 199 | * Requests the consent data host to open an activity that allows users to modify consent. |
| 200 | * |
| 201 | * @param eventTypes The set of event codes to be consented. |
| 202 | */ |
| 203 | @RequiresPermission(Manifest.permission.ACCESS_AMBIENT_CONTEXT_EVENT) |
| 204 | public void startConsentActivity( |
| 205 | @NonNull @AmbientContextEvent.EventCode Set<Integer> eventTypes) { |
| 206 | try { |
| 207 | mService.startConsentActivity( |
| 208 | integerSetToIntArray(eventTypes), mContext.getOpPackageName()); |
| 209 | } catch (RemoteException e) { |
| 210 | throw e.rethrowFromSystemServer(); |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | @NonNull |
| 215 | private static int[] integerSetToIntArray(@NonNull Set<Integer> integerSet) { |
| 216 | int[] intArray = new int[integerSet.size()]; |
| 217 | int i = 0; |
| 218 | for (Integer type : integerSet) { |
| 219 | intArray[i++] = type; |
| 220 | } |
| 221 | return intArray; |
| 222 | } |
| 223 | |
| 224 | /** |
| 225 | * Allows app to register as a {@link AmbientContextEvent} observer. The |
| 226 | * observer receives a callback on the provided {@link PendingIntent} when the requested |
| 227 | * event is detected. Registering another observer from the same package that has already been |
| 228 | * registered will override the previous observer. |
| 229 | * <p /> |
| 230 | * |
| 231 | * Example: |
| 232 | * |
| 233 | * <pre><code> |
| 234 | * // Create request |
| 235 | * AmbientContextEventRequest request = new AmbientContextEventRequest.Builder() |
| 236 | * .addEventType(AmbientContextEvent.EVENT_COUGH) |
| 237 | * .addEventType(AmbientContextEvent.EVENT_SNORE) |
| 238 | * .build(); |
| 239 | * |
| 240 | * // Create PendingIntent for delivering detection results to my receiver |
| 241 | * Intent intent = new Intent(actionString, null, context, MyBroadcastReceiver.class) |
| 242 | * .addFlags(Intent.FLAG_RECEIVER_FOREGROUND); |
| 243 | * PendingIntent pendingIntent = |
| 244 | * PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); |
| 245 | * |
| 246 | * // Create Consumer of service status |
| 247 | * Consumer<Integer> statusConsumer = status -> { |
| 248 | * if (status == AmbientContextManager.STATUS_ACCESS_DENIED) { |
| 249 | * // User did not consent event detection. See #queryAmbientContextServiceStatus and |
| 250 | * // #startConsentActivity |
| 251 | * } |
| 252 | * }; |
| 253 | * |
| 254 | * // Register as observer |
| 255 | * AmbientContextManager ambientContextManager = |
| 256 | * context.getSystemService(AmbientContextManager.class); |
| 257 | * ambientContextManager.registerObserver(request, pendingIntent, executor, statusConsumer); |
| 258 | * |
| 259 | * // Handle the list of {@link AmbientContextEvent}s in your receiver |
| 260 | * {@literal @}Override |
| 261 | * protected void onReceive(Context context, Intent intent) { |
| 262 | * List<AmbientContextEvent> events = AmbientContextManager.getEventsFromIntent(intent); |
| 263 | * if (!events.isEmpty()) { |
| 264 | * // Do something useful with the events. |
| 265 | * } |
| 266 | * } |
| 267 | * </code></pre> |
| 268 | * |
| 269 | * @param request The request with events to observe. |
| 270 | * @param resultPendingIntent A mutable {@link PendingIntent} that will be dispatched after the |
| 271 | * requested events are detected. |
| 272 | * @param executor Executor on which to run the consumer callback. |
| 273 | * @param statusConsumer A consumer that handles the status code, which is returned |
| 274 | * right after the call. |
| 275 | */ |
| 276 | @RequiresPermission(Manifest.permission.ACCESS_AMBIENT_CONTEXT_EVENT) |
| 277 | public void registerObserver( |
| 278 | @NonNull AmbientContextEventRequest request, |
| 279 | @NonNull PendingIntent resultPendingIntent, |
| 280 | @NonNull @CallbackExecutor Executor executor, |
| 281 | @NonNull @StatusCode Consumer<Integer> statusConsumer) { |
| 282 | Preconditions.checkArgument(!resultPendingIntent.isImmutable()); |
| 283 | try { |
| 284 | RemoteCallback callback = new RemoteCallback(result -> { |
| 285 | int statusCode = result.getInt(STATUS_RESPONSE_BUNDLE_KEY); |
| 286 | final long identity = Binder.clearCallingIdentity(); |
| 287 | try { |
| 288 | executor.execute(() -> statusConsumer.accept(statusCode)); |
| 289 | } finally { |
| 290 | Binder.restoreCallingIdentity(identity); |
| 291 | } |
| 292 | }); |
| 293 | mService.registerObserver(request, resultPendingIntent, callback); |
| 294 | } catch (RemoteException e) { |
| 295 | throw e.rethrowFromSystemServer(); |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | /** |
| 300 | * Allows app to register as a {@link AmbientContextEvent} observer. Same as {@link |
| 301 | * #registerObserver(AmbientContextEventRequest, PendingIntent, Executor, Consumer)}, |
| 302 | * but use {@link AmbientContextCallback} instead of {@link PendingIntent} as a callback on |
| 303 | * detected events. |
| 304 | * Registering another observer from the same package that has already been |
| 305 | * registered will override the previous observer. If the same app previously calls |
| 306 | * {@link #registerObserver(AmbientContextEventRequest, AmbientContextCallback, Executor)}, |
| 307 | * and now calls |
| 308 | * {@link #registerObserver(AmbientContextEventRequest, PendingIntent, Executor, Consumer)}, |
| 309 | * the previous observer will be replaced with the new observer with the PendingIntent callback. |
| 310 | * Or vice versa. |
| 311 | * |
| 312 | * When the registration completes, a status will be returned to client through |
| 313 | * {@link AmbientContextCallback#onRegistrationComplete(int)}. |
| 314 | * If the AmbientContextManager service is not enabled yet, or the underlying detection service |
| 315 | * is not running yet, {@link AmbientContextManager#STATUS_SERVICE_UNAVAILABLE} will be |
| 316 | * returned, and the detection won't be really started. |
| 317 | * If the underlying detection service feature is not enabled, or the requested event type is |
| 318 | * not enabled yet, {@link AmbientContextManager#STATUS_NOT_SUPPORTED} will be returned, and the |
| 319 | * detection won't be really started. |
| 320 | * If there is no user consent, {@link AmbientContextManager#STATUS_ACCESS_DENIED} will be |
| 321 | * returned, and the detection won't be really started. |
| 322 | * Otherwise, it will try to start the detection. And if it starts successfully, it will return |
| 323 | * {@link AmbientContextManager#STATUS_SUCCESS}. If it fails to start the detection, then |
| 324 | * it will return {@link AmbientContextManager#STATUS_SERVICE_UNAVAILABLE} |
| 325 | * After registerObserver succeeds and when the service detects an event, the service will |
| 326 | * trigger {@link AmbientContextCallback#onEvents(List)}. |
| 327 | * |
| 328 | * @hide |
| 329 | */ |
| 330 | @RequiresPermission(Manifest.permission.ACCESS_AMBIENT_CONTEXT_EVENT) |
| 331 | public void registerObserver( |
| 332 | @NonNull AmbientContextEventRequest request, |
| 333 | @NonNull @CallbackExecutor Executor executor, |
| 334 | @NonNull AmbientContextCallback ambientContextCallback) { |
| 335 | try { |
| 336 | IAmbientContextObserver observer = new IAmbientContextObserver.Stub() { |
| 337 | @Override |
| 338 | public void onEvents(List<AmbientContextEvent> events) throws RemoteException { |
| 339 | final long identity = Binder.clearCallingIdentity(); |
| 340 | try { |
| 341 | executor.execute(() -> ambientContextCallback.onEvents(events)); |
| 342 | } finally { |
| 343 | Binder.restoreCallingIdentity(identity); |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | @Override |
| 348 | public void onRegistrationComplete(int statusCode) throws RemoteException { |
| 349 | final long identity = Binder.clearCallingIdentity(); |
| 350 | try { |
| 351 | executor.execute( |
| 352 | () -> ambientContextCallback.onRegistrationComplete(statusCode)); |
| 353 | } finally { |
| 354 | Binder.restoreCallingIdentity(identity); |
| 355 | } |
| 356 | } |
| 357 | }; |
| 358 | |
| 359 | mService.registerObserverWithCallback(request, mContext.getPackageName(), observer); |
| 360 | } catch (RemoteException e) { |
| 361 | throw e.rethrowFromSystemServer(); |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | /** |
| 366 | * Unregisters the requesting app as an {@code AmbientContextEvent} observer. Unregistering an |
| 367 | * observer that was already unregistered or never registered will have no effect. |
| 368 | */ |
| 369 | @RequiresPermission(Manifest.permission.ACCESS_AMBIENT_CONTEXT_EVENT) |
| 370 | public void unregisterObserver() { |
| 371 | try { |
| 372 | mService.unregisterObserver(mContext.getOpPackageName()); |
| 373 | } catch (RemoteException e) { |
| 374 | throw e.rethrowFromSystemServer(); |
| 375 | } |
| 376 | } |
| 377 | } |