ActivityManager.java revision bf15587d0d7522aabfbc975738d8fd08aef3c40f
1/*
2 * Copyright (C) 2007 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.app;
18
19import android.Manifest;
20import android.annotation.DrawableRes;
21import android.annotation.IntDef;
22import android.annotation.NonNull;
23import android.annotation.Nullable;
24import android.annotation.RequiresPermission;
25import android.annotation.SystemApi;
26import android.annotation.SystemService;
27import android.annotation.TestApi;
28import android.content.ComponentName;
29import android.content.Context;
30import android.content.Intent;
31import android.content.UriPermission;
32import android.content.pm.ActivityInfo;
33import android.content.pm.ApplicationInfo;
34import android.content.pm.ConfigurationInfo;
35import android.content.pm.IPackageDataObserver;
36import android.content.pm.PackageManager;
37import android.content.pm.ParceledListSlice;
38import android.content.pm.UserInfo;
39import android.content.res.Configuration;
40import android.content.res.Resources;
41import android.graphics.Bitmap;
42import android.graphics.Canvas;
43import android.graphics.Color;
44import android.graphics.GraphicBuffer;
45import android.graphics.Matrix;
46import android.graphics.Point;
47import android.graphics.Rect;
48import android.os.BatteryStats;
49import android.os.Binder;
50import android.os.Build;
51import android.os.Build.VERSION_CODES;
52import android.os.Bundle;
53import android.os.Debug;
54import android.os.Handler;
55import android.os.IBinder;
56import android.os.Parcel;
57import android.os.Parcelable;
58import android.os.Process;
59import android.os.RemoteException;
60import android.os.ServiceManager;
61import android.os.SystemProperties;
62import android.os.UserHandle;
63import android.text.TextUtils;
64import android.util.ArrayMap;
65import android.util.DisplayMetrics;
66import android.util.Singleton;
67import android.util.Size;
68
69import com.android.internal.app.procstats.ProcessStats;
70import com.android.internal.os.RoSystemProperties;
71import com.android.internal.os.TransferPipe;
72import com.android.internal.util.FastPrintWriter;
73import com.android.server.LocalServices;
74
75import org.xmlpull.v1.XmlSerializer;
76
77import java.io.FileDescriptor;
78import java.io.FileOutputStream;
79import java.io.IOException;
80import java.io.PrintWriter;
81import java.lang.annotation.Retention;
82import java.lang.annotation.RetentionPolicy;
83import java.util.ArrayList;
84import java.util.List;
85
86/**
87 * <p>
88 * This class gives information about, and interacts
89 * with, activities, services, and the containing
90 * process.
91 * </p>
92 *
93 * <p>
94 * A number of the methods in this class are for
95 * debugging or informational purposes and they should
96 * not be used to affect any runtime behavior of
97 * your app. These methods are called out as such in
98 * the method level documentation.
99 * </p>
100 *
101 *<p>
102 * Most application developers should not have the need to
103 * use this class, most of whose methods are for specialized
104 * use cases. However, a few methods are more broadly applicable.
105 * For instance, {@link android.app.ActivityManager#isLowRamDevice() isLowRamDevice()}
106 * enables your app to detect whether it is running on a low-memory device,
107 * and behave accordingly.
108 * {@link android.app.ActivityManager#clearApplicationUserData() clearApplicationUserData()}
109 * is for apps with reset-data functionality.
110 * </p>
111 *
112 * <p>
113 * In some special use cases, where an app interacts with
114 * its Task stack, the app may use the
115 * {@link android.app.ActivityManager.AppTask} and
116 * {@link android.app.ActivityManager.RecentTaskInfo} inner
117 * classes. However, in general, the methods in this class should
118 * be used for testing and debugging purposes only.
119 * </p>
120 */
121@SystemService(Context.ACTIVITY_SERVICE)
122public class ActivityManager {
123    private static String TAG = "ActivityManager";
124
125    private static int gMaxRecentTasks = -1;
126
127    private final Context mContext;
128
129    private static volatile boolean sSystemReady = false;
130
131
132    private static final int FIRST_START_FATAL_ERROR_CODE = -100;
133    private static final int LAST_START_FATAL_ERROR_CODE = -1;
134    private static final int FIRST_START_SUCCESS_CODE = 0;
135    private static final int LAST_START_SUCCESS_CODE = 99;
136    private static final int FIRST_START_NON_FATAL_ERROR_CODE = 100;
137    private static final int LAST_START_NON_FATAL_ERROR_CODE = 199;
138
139    static final class UidObserver extends IUidObserver.Stub {
140        final OnUidImportanceListener mListener;
141        final Context mContext;
142
143        UidObserver(OnUidImportanceListener listener, Context clientContext) {
144            mListener = listener;
145            mContext = clientContext;
146        }
147
148        @Override
149        public void onUidStateChanged(int uid, int procState, long procStateSeq) {
150            mListener.onUidImportance(uid, RunningAppProcessInfo.procStateToImportanceForClient(
151                    procState, mContext));
152        }
153
154        @Override
155        public void onUidGone(int uid, boolean disabled) {
156            mListener.onUidImportance(uid, RunningAppProcessInfo.IMPORTANCE_GONE);
157        }
158
159        @Override
160        public void onUidActive(int uid) {
161        }
162
163        @Override
164        public void onUidIdle(int uid, boolean disabled) {
165        }
166
167        @Override public void onUidCachedChanged(int uid, boolean cached) {
168        }
169    }
170
171    final ArrayMap<OnUidImportanceListener, UidObserver> mImportanceListeners = new ArrayMap<>();
172
173    /**
174     * Defines acceptable types of bugreports.
175     * @hide
176     */
177    @Retention(RetentionPolicy.SOURCE)
178    @IntDef({
179            BUGREPORT_OPTION_FULL,
180            BUGREPORT_OPTION_INTERACTIVE,
181            BUGREPORT_OPTION_REMOTE,
182            BUGREPORT_OPTION_WEAR,
183            BUGREPORT_OPTION_TELEPHONY
184    })
185    public @interface BugreportMode {}
186    /**
187     * Takes a bugreport without user interference (and hence causing less
188     * interference to the system), but includes all sections.
189     * @hide
190     */
191    public static final int BUGREPORT_OPTION_FULL = 0;
192    /**
193     * Allows user to monitor progress and enter additional data; might not include all
194     * sections.
195     * @hide
196     */
197    public static final int BUGREPORT_OPTION_INTERACTIVE = 1;
198    /**
199     * Takes a bugreport requested remotely by administrator of the Device Owner app,
200     * not the device's user.
201     * @hide
202     */
203    public static final int BUGREPORT_OPTION_REMOTE = 2;
204    /**
205     * Takes a bugreport on a wearable device.
206     * @hide
207     */
208    public static final int BUGREPORT_OPTION_WEAR = 3;
209
210    /**
211     * Takes a lightweight version of bugreport that only includes a few, urgent sections
212     * used to report telephony bugs.
213     * @hide
214     */
215    public static final int BUGREPORT_OPTION_TELEPHONY = 4;
216
217    /**
218     * <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code
219     * <meta-data>}</a> name for a 'home' Activity that declares a package that is to be
220     * uninstalled in lieu of the declaring one.  The package named here must be
221     * signed with the same certificate as the one declaring the {@code <meta-data>}.
222     */
223    public static final String META_HOME_ALTERNATE = "android.app.home.alternate";
224
225    // NOTE: Before adding a new start result, please reference the defined ranges to ensure the
226    // result is properly categorized.
227
228    /**
229     * Result for IActivityManager.startVoiceActivity: active session is currently hidden.
230     * @hide
231     */
232    public static final int START_VOICE_HIDDEN_SESSION = FIRST_START_FATAL_ERROR_CODE;
233
234    /**
235     * Result for IActivityManager.startVoiceActivity: active session does not match
236     * the requesting token.
237     * @hide
238     */
239    public static final int START_VOICE_NOT_ACTIVE_SESSION = FIRST_START_FATAL_ERROR_CODE + 1;
240
241    /**
242     * Result for IActivityManager.startActivity: trying to start a background user
243     * activity that shouldn't be displayed for all users.
244     * @hide
245     */
246    public static final int START_NOT_CURRENT_USER_ACTIVITY = FIRST_START_FATAL_ERROR_CODE + 2;
247
248    /**
249     * Result for IActivityManager.startActivity: trying to start an activity under voice
250     * control when that activity does not support the VOICE category.
251     * @hide
252     */
253    public static final int START_NOT_VOICE_COMPATIBLE = FIRST_START_FATAL_ERROR_CODE + 3;
254
255    /**
256     * Result for IActivityManager.startActivity: an error where the
257     * start had to be canceled.
258     * @hide
259     */
260    public static final int START_CANCELED = FIRST_START_FATAL_ERROR_CODE + 4;
261
262    /**
263     * Result for IActivityManager.startActivity: an error where the
264     * thing being started is not an activity.
265     * @hide
266     */
267    public static final int START_NOT_ACTIVITY = FIRST_START_FATAL_ERROR_CODE + 5;
268
269    /**
270     * Result for IActivityManager.startActivity: an error where the
271     * caller does not have permission to start the activity.
272     * @hide
273     */
274    public static final int START_PERMISSION_DENIED = FIRST_START_FATAL_ERROR_CODE + 6;
275
276    /**
277     * Result for IActivityManager.startActivity: an error where the
278     * caller has requested both to forward a result and to receive
279     * a result.
280     * @hide
281     */
282    public static final int START_FORWARD_AND_REQUEST_CONFLICT = FIRST_START_FATAL_ERROR_CODE + 7;
283
284    /**
285     * Result for IActivityManager.startActivity: an error where the
286     * requested class is not found.
287     * @hide
288     */
289    public static final int START_CLASS_NOT_FOUND = FIRST_START_FATAL_ERROR_CODE + 8;
290
291    /**
292     * Result for IActivityManager.startActivity: an error where the
293     * given Intent could not be resolved to an activity.
294     * @hide
295     */
296    public static final int START_INTENT_NOT_RESOLVED = FIRST_START_FATAL_ERROR_CODE + 9;
297
298    /**
299     * Result for IActivityManager.startAssistantActivity: active session is currently hidden.
300     * @hide
301     */
302    public static final int START_ASSISTANT_HIDDEN_SESSION = FIRST_START_FATAL_ERROR_CODE + 10;
303
304    /**
305     * Result for IActivityManager.startAssistantActivity: active session does not match
306     * the requesting token.
307     * @hide
308     */
309    public static final int START_ASSISTANT_NOT_ACTIVE_SESSION = FIRST_START_FATAL_ERROR_CODE + 11;
310
311    /**
312     * Result for IActivityManaqer.startActivity: the activity was started
313     * successfully as normal.
314     * @hide
315     */
316    public static final int START_SUCCESS = FIRST_START_SUCCESS_CODE;
317
318    /**
319     * Result for IActivityManaqer.startActivity: the caller asked that the Intent not
320     * be executed if it is the recipient, and that is indeed the case.
321     * @hide
322     */
323    public static final int START_RETURN_INTENT_TO_CALLER = FIRST_START_SUCCESS_CODE + 1;
324
325    /**
326     * Result for IActivityManaqer.startActivity: activity wasn't really started, but
327     * a task was simply brought to the foreground.
328     * @hide
329     */
330    public static final int START_TASK_TO_FRONT = FIRST_START_SUCCESS_CODE + 2;
331
332    /**
333     * Result for IActivityManaqer.startActivity: activity wasn't really started, but
334     * the given Intent was given to the existing top activity.
335     * @hide
336     */
337    public static final int START_DELIVERED_TO_TOP = FIRST_START_SUCCESS_CODE + 3;
338
339    /**
340     * Result for IActivityManaqer.startActivity: request was canceled because
341     * app switches are temporarily canceled to ensure the user's last request
342     * (such as pressing home) is performed.
343     * @hide
344     */
345    public static final int START_SWITCHES_CANCELED = FIRST_START_NON_FATAL_ERROR_CODE;
346
347    /**
348     * Result for IActivityManaqer.startActivity: a new activity was attempted to be started
349     * while in Lock Task Mode.
350     * @hide
351     */
352    public static final int START_RETURN_LOCK_TASK_MODE_VIOLATION =
353            FIRST_START_NON_FATAL_ERROR_CODE + 1;
354
355    /**
356     * Result for IActivityManaqer.startActivity: a new activity start was aborted. Never returned
357     * externally.
358     * @hide
359     */
360    public static final int START_ABORTED = FIRST_START_NON_FATAL_ERROR_CODE + 2;
361
362    /**
363     * Flag for IActivityManaqer.startActivity: do special start mode where
364     * a new activity is launched only if it is needed.
365     * @hide
366     */
367    public static final int START_FLAG_ONLY_IF_NEEDED = 1<<0;
368
369    /**
370     * Flag for IActivityManaqer.startActivity: launch the app for
371     * debugging.
372     * @hide
373     */
374    public static final int START_FLAG_DEBUG = 1<<1;
375
376    /**
377     * Flag for IActivityManaqer.startActivity: launch the app for
378     * allocation tracking.
379     * @hide
380     */
381    public static final int START_FLAG_TRACK_ALLOCATION = 1<<2;
382
383    /**
384     * Flag for IActivityManaqer.startActivity: launch the app with
385     * native debugging support.
386     * @hide
387     */
388    public static final int START_FLAG_NATIVE_DEBUGGING = 1<<3;
389
390    /**
391     * Result for IActivityManaqer.broadcastIntent: success!
392     * @hide
393     */
394    public static final int BROADCAST_SUCCESS = 0;
395
396    /**
397     * Result for IActivityManaqer.broadcastIntent: attempt to broadcast
398     * a sticky intent without appropriate permission.
399     * @hide
400     */
401    public static final int BROADCAST_STICKY_CANT_HAVE_PERMISSION = -1;
402
403    /**
404     * Result for IActivityManager.broadcastIntent: trying to send a broadcast
405     * to a stopped user. Fail.
406     * @hide
407     */
408    public static final int BROADCAST_FAILED_USER_STOPPED = -2;
409
410    /**
411     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
412     * for a sendBroadcast operation.
413     * @hide
414     */
415    public static final int INTENT_SENDER_BROADCAST = 1;
416
417    /**
418     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
419     * for a startActivity operation.
420     * @hide
421     */
422    public static final int INTENT_SENDER_ACTIVITY = 2;
423
424    /**
425     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
426     * for an activity result operation.
427     * @hide
428     */
429    public static final int INTENT_SENDER_ACTIVITY_RESULT = 3;
430
431    /**
432     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
433     * for a startService operation.
434     * @hide
435     */
436    public static final int INTENT_SENDER_SERVICE = 4;
437
438    /**
439     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
440     * for a startForegroundService operation.
441     * @hide
442     */
443    public static final int INTENT_SENDER_FOREGROUND_SERVICE = 5;
444
445    /** @hide User operation call: success! */
446    public static final int USER_OP_SUCCESS = 0;
447
448    /** @hide User operation call: given user id is not known. */
449    public static final int USER_OP_UNKNOWN_USER = -1;
450
451    /** @hide User operation call: given user id is the current user, can't be stopped. */
452    public static final int USER_OP_IS_CURRENT = -2;
453
454    /** @hide User operation call: system user can't be stopped. */
455    public static final int USER_OP_ERROR_IS_SYSTEM = -3;
456
457    /** @hide User operation call: one of related users cannot be stopped. */
458    public static final int USER_OP_ERROR_RELATED_USERS_CANNOT_STOP = -4;
459
460    /** @hide Not a real process state. */
461    public static final int PROCESS_STATE_UNKNOWN = -1;
462
463    /** @hide Process is a persistent system process. */
464    public static final int PROCESS_STATE_PERSISTENT = 0;
465
466    /** @hide Process is a persistent system process and is doing UI. */
467    public static final int PROCESS_STATE_PERSISTENT_UI = 1;
468
469    /** @hide Process is hosting the current top activities.  Note that this covers
470     * all activities that are visible to the user. */
471    public static final int PROCESS_STATE_TOP = 2;
472
473    /** @hide Process is hosting a foreground service due to a system binding. */
474    public static final int PROCESS_STATE_BOUND_FOREGROUND_SERVICE = 3;
475
476    /** @hide Process is hosting a foreground service. */
477    public static final int PROCESS_STATE_FOREGROUND_SERVICE = 4;
478
479    /** @hide Same as {@link #PROCESS_STATE_TOP} but while device is sleeping. */
480    public static final int PROCESS_STATE_TOP_SLEEPING = 5;
481
482    /** @hide Process is important to the user, and something they are aware of. */
483    public static final int PROCESS_STATE_IMPORTANT_FOREGROUND = 6;
484
485    /** @hide Process is important to the user, but not something they are aware of. */
486    public static final int PROCESS_STATE_IMPORTANT_BACKGROUND = 7;
487
488    /** @hide Process is in the background transient so we will try to keep running. */
489    public static final int PROCESS_STATE_TRANSIENT_BACKGROUND = 8;
490
491    /** @hide Process is in the background running a backup/restore operation. */
492    public static final int PROCESS_STATE_BACKUP = 9;
493
494    /** @hide Process is in the background, but it can't restore its state so we want
495     * to try to avoid killing it. */
496    public static final int PROCESS_STATE_HEAVY_WEIGHT = 10;
497
498    /** @hide Process is in the background running a service.  Unlike oom_adj, this level
499     * is used for both the normal running in background state and the executing
500     * operations state. */
501    public static final int PROCESS_STATE_SERVICE = 11;
502
503    /** @hide Process is in the background running a receiver.   Note that from the
504     * perspective of oom_adj, receivers run at a higher foreground level, but for our
505     * prioritization here that is not necessary and putting them below services means
506     * many fewer changes in some process states as they receive broadcasts. */
507    public static final int PROCESS_STATE_RECEIVER = 12;
508
509    /** @hide Process is in the background but hosts the home activity. */
510    public static final int PROCESS_STATE_HOME = 13;
511
512    /** @hide Process is in the background but hosts the last shown activity. */
513    public static final int PROCESS_STATE_LAST_ACTIVITY = 14;
514
515    /** @hide Process is being cached for later use and contains activities. */
516    public static final int PROCESS_STATE_CACHED_ACTIVITY = 15;
517
518    /** @hide Process is being cached for later use and is a client of another cached
519     * process that contains activities. */
520    public static final int PROCESS_STATE_CACHED_ACTIVITY_CLIENT = 16;
521
522    /** @hide Process is being cached for later use and is empty. */
523    public static final int PROCESS_STATE_CACHED_EMPTY = 17;
524
525    /** @hide Process does not exist. */
526    public static final int PROCESS_STATE_NONEXISTENT = 18;
527
528    // NOTE: If PROCESS_STATEs are added or changed, then new fields must be added
529    // to frameworks/base/core/proto/android/app/activitymanager.proto and the following method must
530    // be updated to correctly map between them.
531    /**
532     * Maps ActivityManager.PROCESS_STATE_ values to ActivityManagerProto.ProcessState enum.
533     *
534     * @param amInt a process state of the form ActivityManager.PROCESS_STATE_
535     * @return the value of the corresponding android.app.ActivityManagerProto's ProcessState enum.
536     * @hide
537     */
538    public static final int processStateAmToProto(int amInt) {
539        return amInt * 100;
540    }
541
542    /** @hide The lowest process state number */
543    public static final int MIN_PROCESS_STATE = PROCESS_STATE_PERSISTENT;
544
545    /** @hide The highest process state number */
546    public static final int MAX_PROCESS_STATE = PROCESS_STATE_NONEXISTENT;
547
548    /** @hide Should this process state be considered a background state? */
549    public static final boolean isProcStateBackground(int procState) {
550        return procState >= PROCESS_STATE_TRANSIENT_BACKGROUND;
551    }
552
553    /** @hide requestType for assist context: only basic information. */
554    public static final int ASSIST_CONTEXT_BASIC = 0;
555
556    /** @hide requestType for assist context: generate full AssistStructure. */
557    public static final int ASSIST_CONTEXT_FULL = 1;
558
559    /** @hide requestType for assist context: generate full AssistStructure for autofill. */
560    public static final int ASSIST_CONTEXT_AUTOFILL = 2;
561
562    /** @hide Flag for registerUidObserver: report changes in process state. */
563    public static final int UID_OBSERVER_PROCSTATE = 1<<0;
564
565    /** @hide Flag for registerUidObserver: report uid gone. */
566    public static final int UID_OBSERVER_GONE = 1<<1;
567
568    /** @hide Flag for registerUidObserver: report uid has become idle. */
569    public static final int UID_OBSERVER_IDLE = 1<<2;
570
571    /** @hide Flag for registerUidObserver: report uid has become active. */
572    public static final int UID_OBSERVER_ACTIVE = 1<<3;
573
574    /** @hide Flag for registerUidObserver: report uid cached state has changed. */
575    public static final int UID_OBSERVER_CACHED = 1<<4;
576
577    /** @hide Mode for {@link IActivityManager#isAppStartModeDisabled}: normal free-to-run operation. */
578    public static final int APP_START_MODE_NORMAL = 0;
579
580    /** @hide Mode for {@link IActivityManager#isAppStartModeDisabled}: delay running until later. */
581    public static final int APP_START_MODE_DELAYED = 1;
582
583    /** @hide Mode for {@link IActivityManager#isAppStartModeDisabled}: delay running until later, with
584     * rigid errors (throwing exception). */
585    public static final int APP_START_MODE_DELAYED_RIGID = 2;
586
587    /** @hide Mode for {@link IActivityManager#isAppStartModeDisabled}: disable/cancel pending
588     * launches; this is the mode for ephemeral apps. */
589    public static final int APP_START_MODE_DISABLED = 3;
590
591    /**
592     * Lock task mode is not active.
593     */
594    public static final int LOCK_TASK_MODE_NONE = 0;
595
596    /**
597     * Full lock task mode is active.
598     */
599    public static final int LOCK_TASK_MODE_LOCKED = 1;
600
601    /**
602     * App pinning mode is active.
603     */
604    public static final int LOCK_TASK_MODE_PINNED = 2;
605
606    Point mAppTaskThumbnailSize;
607
608    /*package*/ ActivityManager(Context context, Handler handler) {
609        mContext = context;
610    }
611
612    /**
613     * Returns whether the launch was successful.
614     * @hide
615     */
616    public static final boolean isStartResultSuccessful(int result) {
617        return FIRST_START_SUCCESS_CODE <= result && result <= LAST_START_SUCCESS_CODE;
618    }
619
620    /**
621     * Returns whether the launch result was a fatal error.
622     * @hide
623     */
624    public static final boolean isStartResultFatalError(int result) {
625        return FIRST_START_FATAL_ERROR_CODE <= result && result <= LAST_START_FATAL_ERROR_CODE;
626    }
627
628    /**
629     * Screen compatibility mode: the application most always run in
630     * compatibility mode.
631     * @hide
632     */
633    public static final int COMPAT_MODE_ALWAYS = -1;
634
635    /**
636     * Screen compatibility mode: the application can never run in
637     * compatibility mode.
638     * @hide
639     */
640    public static final int COMPAT_MODE_NEVER = -2;
641
642    /**
643     * Screen compatibility mode: unknown.
644     * @hide
645     */
646    public static final int COMPAT_MODE_UNKNOWN = -3;
647
648    /**
649     * Screen compatibility mode: the application currently has compatibility
650     * mode disabled.
651     * @hide
652     */
653    public static final int COMPAT_MODE_DISABLED = 0;
654
655    /**
656     * Screen compatibility mode: the application currently has compatibility
657     * mode enabled.
658     * @hide
659     */
660    public static final int COMPAT_MODE_ENABLED = 1;
661
662    /**
663     * Screen compatibility mode: request to toggle the application's
664     * compatibility mode.
665     * @hide
666     */
667    public static final int COMPAT_MODE_TOGGLE = 2;
668
669    private static final boolean DEVELOPMENT_FORCE_LOW_RAM =
670            SystemProperties.getBoolean("debug.force_low_ram", false);
671
672    /** @hide */
673    @TestApi
674    public static class StackId {
675
676        private StackId() {
677        }
678
679        /** Invalid stack ID. */
680        public static final int INVALID_STACK_ID = -1;
681
682    }
683
684    /**
685     * Parameter to {@link android.app.IActivityManager#setTaskWindowingModeSplitScreenPrimary}
686     * which specifies the position of the created docked stack at the top half of the screen if
687     * in portrait mode or at the left half of the screen if in landscape mode.
688     * @hide
689     */
690    public static final int SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT = 0;
691
692    /**
693     * Parameter to {@link android.app.IActivityManager#setTaskWindowingModeSplitScreenPrimary}
694     * which
695     * specifies the position of the created docked stack at the bottom half of the screen if
696     * in portrait mode or at the right half of the screen if in landscape mode.
697     * @hide
698     */
699    public static final int SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT = 1;
700
701    /**
702     * Input parameter to {@link android.app.IActivityManager#resizeTask} which indicates
703     * that the resize doesn't need to preserve the window, and can be skipped if bounds
704     * is unchanged. This mode is used by window manager in most cases.
705     * @hide
706     */
707    public static final int RESIZE_MODE_SYSTEM = 0;
708
709    /**
710     * Input parameter to {@link android.app.IActivityManager#resizeTask} which indicates
711     * that the resize should preserve the window if possible.
712     * @hide
713     */
714    public static final int RESIZE_MODE_PRESERVE_WINDOW   = (0x1 << 0);
715
716    /**
717     * Input parameter to {@link android.app.IActivityManager#resizeTask} which indicates
718     * that the resize should be performed even if the bounds appears unchanged.
719     * @hide
720     */
721    public static final int RESIZE_MODE_FORCED = (0x1 << 1);
722
723    /**
724     * Input parameter to {@link android.app.IActivityManager#resizeTask} used by window
725     * manager during a screen rotation.
726     * @hide
727     */
728    public static final int RESIZE_MODE_SYSTEM_SCREEN_ROTATION = RESIZE_MODE_PRESERVE_WINDOW;
729
730    /**
731     * Input parameter to {@link android.app.IActivityManager#resizeTask} used when the
732     * resize is due to a drag action.
733     * @hide
734     */
735    public static final int RESIZE_MODE_USER = RESIZE_MODE_PRESERVE_WINDOW;
736
737    /**
738     * Input parameter to {@link android.app.IActivityManager#resizeTask} which indicates
739     * that the resize should preserve the window if possible, and should not be skipped
740     * even if the bounds is unchanged. Usually used to force a resizing when a drag action
741     * is ending.
742     * @hide
743     */
744    public static final int RESIZE_MODE_USER_FORCED =
745            RESIZE_MODE_PRESERVE_WINDOW | RESIZE_MODE_FORCED;
746
747    /** @hide */
748    public int getFrontActivityScreenCompatMode() {
749        try {
750            return getService().getFrontActivityScreenCompatMode();
751        } catch (RemoteException e) {
752            throw e.rethrowFromSystemServer();
753        }
754    }
755
756    /** @hide */
757    public void setFrontActivityScreenCompatMode(int mode) {
758        try {
759            getService().setFrontActivityScreenCompatMode(mode);
760        } catch (RemoteException e) {
761            throw e.rethrowFromSystemServer();
762        }
763    }
764
765    /** @hide */
766    public int getPackageScreenCompatMode(String packageName) {
767        try {
768            return getService().getPackageScreenCompatMode(packageName);
769        } catch (RemoteException e) {
770            throw e.rethrowFromSystemServer();
771        }
772    }
773
774    /** @hide */
775    public void setPackageScreenCompatMode(String packageName, int mode) {
776        try {
777            getService().setPackageScreenCompatMode(packageName, mode);
778        } catch (RemoteException e) {
779            throw e.rethrowFromSystemServer();
780        }
781    }
782
783    /** @hide */
784    public boolean getPackageAskScreenCompat(String packageName) {
785        try {
786            return getService().getPackageAskScreenCompat(packageName);
787        } catch (RemoteException e) {
788            throw e.rethrowFromSystemServer();
789        }
790    }
791
792    /** @hide */
793    public void setPackageAskScreenCompat(String packageName, boolean ask) {
794        try {
795            getService().setPackageAskScreenCompat(packageName, ask);
796        } catch (RemoteException e) {
797            throw e.rethrowFromSystemServer();
798        }
799    }
800
801    /**
802     * Return the approximate per-application memory class of the current
803     * device.  This gives you an idea of how hard a memory limit you should
804     * impose on your application to let the overall system work best.  The
805     * returned value is in megabytes; the baseline Android memory class is
806     * 16 (which happens to be the Java heap limit of those devices); some
807     * device with more memory may return 24 or even higher numbers.
808     */
809    public int getMemoryClass() {
810        return staticGetMemoryClass();
811    }
812
813    /** @hide */
814    static public int staticGetMemoryClass() {
815        // Really brain dead right now -- just take this from the configured
816        // vm heap size, and assume it is in megabytes and thus ends with "m".
817        String vmHeapSize = SystemProperties.get("dalvik.vm.heapgrowthlimit", "");
818        if (vmHeapSize != null && !"".equals(vmHeapSize)) {
819            return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
820        }
821        return staticGetLargeMemoryClass();
822    }
823
824    /**
825     * Return the approximate per-application memory class of the current
826     * device when an application is running with a large heap.  This is the
827     * space available for memory-intensive applications; most applications
828     * should not need this amount of memory, and should instead stay with the
829     * {@link #getMemoryClass()} limit.  The returned value is in megabytes.
830     * This may be the same size as {@link #getMemoryClass()} on memory
831     * constrained devices, or it may be significantly larger on devices with
832     * a large amount of available RAM.
833     *
834     * <p>The is the size of the application's Dalvik heap if it has
835     * specified <code>android:largeHeap="true"</code> in its manifest.
836     */
837    public int getLargeMemoryClass() {
838        return staticGetLargeMemoryClass();
839    }
840
841    /** @hide */
842    static public int staticGetLargeMemoryClass() {
843        // Really brain dead right now -- just take this from the configured
844        // vm heap size, and assume it is in megabytes and thus ends with "m".
845        String vmHeapSize = SystemProperties.get("dalvik.vm.heapsize", "16m");
846        return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length() - 1));
847    }
848
849    /**
850     * Returns true if this is a low-RAM device.  Exactly whether a device is low-RAM
851     * is ultimately up to the device configuration, but currently it generally means
852     * something with 1GB or less of RAM.  This is mostly intended to be used by apps
853     * to determine whether they should turn off certain features that require more RAM.
854     */
855    public boolean isLowRamDevice() {
856        return isLowRamDeviceStatic();
857    }
858
859    /** @hide */
860    public static boolean isLowRamDeviceStatic() {
861        return RoSystemProperties.CONFIG_LOW_RAM ||
862                (Build.IS_DEBUGGABLE && DEVELOPMENT_FORCE_LOW_RAM);
863    }
864
865    /**
866     * Returns true if this is a small battery device. Exactly whether a device is considered to be
867     * small battery is ultimately up to the device configuration, but currently it generally means
868     * something in the class of a device with 1000 mAh or less. This is mostly intended to be used
869     * to determine whether certain features should be altered to account for a drastically smaller
870     * battery.
871     * @hide
872     */
873    public static boolean isSmallBatteryDevice() {
874        return RoSystemProperties.CONFIG_SMALL_BATTERY;
875    }
876
877    /**
878     * Used by persistent processes to determine if they are running on a
879     * higher-end device so should be okay using hardware drawing acceleration
880     * (which tends to consume a lot more RAM).
881     * @hide
882     */
883    static public boolean isHighEndGfx() {
884        return !isLowRamDeviceStatic() &&
885                !Resources.getSystem().getBoolean(com.android.internal.R.bool.config_avoidGfxAccel);
886    }
887
888    /**
889     * Return the maximum number of recents entries that we will maintain and show.
890     * @hide
891     */
892    static public int getMaxRecentTasksStatic() {
893        if (gMaxRecentTasks < 0) {
894            return gMaxRecentTasks = isLowRamDeviceStatic() ? 36 : 48;
895        }
896        return gMaxRecentTasks;
897    }
898
899    /**
900     * Return the default limit on the number of recents that an app can make.
901     * @hide
902     */
903    static public int getDefaultAppRecentsLimitStatic() {
904        return getMaxRecentTasksStatic() / 6;
905    }
906
907    /**
908     * Return the maximum limit on the number of recents that an app can make.
909     * @hide
910     */
911    static public int getMaxAppRecentsLimitStatic() {
912        return getMaxRecentTasksStatic() / 2;
913    }
914
915    /**
916     * Returns true if the system supports at least one form of multi-window.
917     * E.g. freeform, split-screen, picture-in-picture.
918     * @hide
919     */
920    @TestApi
921    static public boolean supportsMultiWindow(Context context) {
922        // On watches, multi-window is used to present essential system UI, and thus it must be
923        // supported regardless of device memory characteristics.
924        boolean isWatch = context.getPackageManager().hasSystemFeature(
925                PackageManager.FEATURE_WATCH);
926        return (!isLowRamDeviceStatic() || isWatch)
927                && Resources.getSystem().getBoolean(
928                    com.android.internal.R.bool.config_supportsMultiWindow);
929    }
930
931    /**
932     * Returns true if the system supports split screen multi-window.
933     * @hide
934     */
935    @TestApi
936    static public boolean supportsSplitScreenMultiWindow(Context context) {
937        return supportsMultiWindow(context)
938                && Resources.getSystem().getBoolean(
939                    com.android.internal.R.bool.config_supportsSplitScreenMultiWindow);
940    }
941
942    /** @removed */
943    @Deprecated
944    public static int getMaxNumPictureInPictureActions() {
945        return 3;
946    }
947
948    /**
949     * Information you can set and retrieve about the current activity within the recent task list.
950     */
951    public static class TaskDescription implements Parcelable {
952        /** @hide */
953        public static final String ATTR_TASKDESCRIPTION_PREFIX = "task_description_";
954        private static final String ATTR_TASKDESCRIPTIONLABEL =
955                ATTR_TASKDESCRIPTION_PREFIX + "label";
956        private static final String ATTR_TASKDESCRIPTIONCOLOR_PRIMARY =
957                ATTR_TASKDESCRIPTION_PREFIX + "color";
958        private static final String ATTR_TASKDESCRIPTIONCOLOR_BACKGROUND =
959                ATTR_TASKDESCRIPTION_PREFIX + "colorBackground";
960        private static final String ATTR_TASKDESCRIPTIONICON_FILENAME =
961                ATTR_TASKDESCRIPTION_PREFIX + "icon_filename";
962        private static final String ATTR_TASKDESCRIPTIONICON_RESOURCE =
963                ATTR_TASKDESCRIPTION_PREFIX + "icon_resource";
964
965        private String mLabel;
966        private Bitmap mIcon;
967        private int mIconRes;
968        private String mIconFilename;
969        private int mColorPrimary;
970        private int mColorBackground;
971        private int mStatusBarColor;
972        private int mNavigationBarColor;
973
974        /**
975         * Creates the TaskDescription to the specified values.
976         *
977         * @param label A label and description of the current state of this task.
978         * @param icon An icon that represents the current state of this task.
979         * @param colorPrimary A color to override the theme's primary color.  This color must be
980         *                     opaque.
981         * @deprecated use TaskDescription constructor with icon resource instead
982         */
983        @Deprecated
984        public TaskDescription(String label, Bitmap icon, int colorPrimary) {
985            this(label, icon, 0, null, colorPrimary, 0, 0, 0);
986            if ((colorPrimary != 0) && (Color.alpha(colorPrimary) != 255)) {
987                throw new RuntimeException("A TaskDescription's primary color should be opaque");
988            }
989        }
990
991        /**
992         * Creates the TaskDescription to the specified values.
993         *
994         * @param label A label and description of the current state of this task.
995         * @param iconRes A drawable resource of an icon that represents the current state of this
996         *                activity.
997         * @param colorPrimary A color to override the theme's primary color.  This color must be
998         *                     opaque.
999         */
1000        public TaskDescription(String label, @DrawableRes int iconRes, int colorPrimary) {
1001            this(label, null, iconRes, null, colorPrimary, 0, 0, 0);
1002            if ((colorPrimary != 0) && (Color.alpha(colorPrimary) != 255)) {
1003                throw new RuntimeException("A TaskDescription's primary color should be opaque");
1004            }
1005        }
1006
1007        /**
1008         * Creates the TaskDescription to the specified values.
1009         *
1010         * @param label A label and description of the current state of this activity.
1011         * @param icon An icon that represents the current state of this activity.
1012         * @deprecated use TaskDescription constructor with icon resource instead
1013         */
1014        @Deprecated
1015        public TaskDescription(String label, Bitmap icon) {
1016            this(label, icon, 0, null, 0, 0, 0, 0);
1017        }
1018
1019        /**
1020         * Creates the TaskDescription to the specified values.
1021         *
1022         * @param label A label and description of the current state of this activity.
1023         * @param iconRes A drawable resource of an icon that represents the current state of this
1024         *                activity.
1025         */
1026        public TaskDescription(String label, @DrawableRes int iconRes) {
1027            this(label, null, iconRes, null, 0, 0, 0, 0);
1028        }
1029
1030        /**
1031         * Creates the TaskDescription to the specified values.
1032         *
1033         * @param label A label and description of the current state of this activity.
1034         */
1035        public TaskDescription(String label) {
1036            this(label, null, 0, null, 0, 0, 0, 0);
1037        }
1038
1039        /**
1040         * Creates an empty TaskDescription.
1041         */
1042        public TaskDescription() {
1043            this(null, null, 0, null, 0, 0, 0, 0);
1044        }
1045
1046        /** @hide */
1047        public TaskDescription(String label, Bitmap bitmap, int iconRes, String iconFilename,
1048                int colorPrimary, int colorBackground, int statusBarColor, int navigationBarColor) {
1049            mLabel = label;
1050            mIcon = bitmap;
1051            mIconRes = iconRes;
1052            mIconFilename = iconFilename;
1053            mColorPrimary = colorPrimary;
1054            mColorBackground = colorBackground;
1055            mStatusBarColor = statusBarColor;
1056            mNavigationBarColor = navigationBarColor;
1057        }
1058
1059        /**
1060         * Creates a copy of another TaskDescription.
1061         */
1062        public TaskDescription(TaskDescription td) {
1063            copyFrom(td);
1064        }
1065
1066        /**
1067         * Copies this the values from another TaskDescription.
1068         * @hide
1069         */
1070        public void copyFrom(TaskDescription other) {
1071            mLabel = other.mLabel;
1072            mIcon = other.mIcon;
1073            mIconRes = other.mIconRes;
1074            mIconFilename = other.mIconFilename;
1075            mColorPrimary = other.mColorPrimary;
1076            mColorBackground = other.mColorBackground;
1077            mStatusBarColor = other.mStatusBarColor;
1078            mNavigationBarColor = other.mNavigationBarColor;
1079        }
1080
1081        /**
1082         * Copies this the values from another TaskDescription, but preserves the hidden fields
1083         * if they weren't set on {@code other}
1084         * @hide
1085         */
1086        public void copyFromPreserveHiddenFields(TaskDescription other) {
1087            mLabel = other.mLabel;
1088            mIcon = other.mIcon;
1089            mIconRes = other.mIconRes;
1090            mIconFilename = other.mIconFilename;
1091            mColorPrimary = other.mColorPrimary;
1092            if (other.mColorBackground != 0) {
1093                mColorBackground = other.mColorBackground;
1094            }
1095            if (other.mStatusBarColor != 0) {
1096                mStatusBarColor = other.mStatusBarColor;
1097            }
1098            if (other.mNavigationBarColor != 0) {
1099                mNavigationBarColor = other.mNavigationBarColor;
1100            }
1101        }
1102
1103        private TaskDescription(Parcel source) {
1104            readFromParcel(source);
1105        }
1106
1107        /**
1108         * Sets the label for this task description.
1109         * @hide
1110         */
1111        public void setLabel(String label) {
1112            mLabel = label;
1113        }
1114
1115        /**
1116         * Sets the primary color for this task description.
1117         * @hide
1118         */
1119        public void setPrimaryColor(int primaryColor) {
1120            // Ensure that the given color is valid
1121            if ((primaryColor != 0) && (Color.alpha(primaryColor) != 255)) {
1122                throw new RuntimeException("A TaskDescription's primary color should be opaque");
1123            }
1124            mColorPrimary = primaryColor;
1125        }
1126
1127        /**
1128         * Sets the background color for this task description.
1129         * @hide
1130         */
1131        public void setBackgroundColor(int backgroundColor) {
1132            // Ensure that the given color is valid
1133            if ((backgroundColor != 0) && (Color.alpha(backgroundColor) != 255)) {
1134                throw new RuntimeException("A TaskDescription's background color should be opaque");
1135            }
1136            mColorBackground = backgroundColor;
1137        }
1138
1139        /**
1140         * @hide
1141         */
1142        public void setStatusBarColor(int statusBarColor) {
1143            mStatusBarColor = statusBarColor;
1144        }
1145
1146        /**
1147         * @hide
1148         */
1149        public void setNavigationBarColor(int navigationBarColor) {
1150            mNavigationBarColor = navigationBarColor;
1151        }
1152
1153        /**
1154         * Sets the icon for this task description.
1155         * @hide
1156         */
1157        public void setIcon(Bitmap icon) {
1158            mIcon = icon;
1159        }
1160
1161        /**
1162         * Sets the icon resource for this task description.
1163         * @hide
1164         */
1165        public void setIcon(int iconRes) {
1166            mIconRes = iconRes;
1167        }
1168
1169        /**
1170         * Moves the icon bitmap reference from an actual Bitmap to a file containing the
1171         * bitmap.
1172         * @hide
1173         */
1174        public void setIconFilename(String iconFilename) {
1175            mIconFilename = iconFilename;
1176            mIcon = null;
1177        }
1178
1179        /**
1180         * @return The label and description of the current state of this task.
1181         */
1182        public String getLabel() {
1183            return mLabel;
1184        }
1185
1186        /**
1187         * @return The icon that represents the current state of this task.
1188         */
1189        public Bitmap getIcon() {
1190            if (mIcon != null) {
1191                return mIcon;
1192            }
1193            return loadTaskDescriptionIcon(mIconFilename, UserHandle.myUserId());
1194        }
1195
1196        /** @hide */
1197        @TestApi
1198        public int getIconResource() {
1199            return mIconRes;
1200        }
1201
1202        /** @hide */
1203        @TestApi
1204        public String getIconFilename() {
1205            return mIconFilename;
1206        }
1207
1208        /** @hide */
1209        public Bitmap getInMemoryIcon() {
1210            return mIcon;
1211        }
1212
1213        /** @hide */
1214        public static Bitmap loadTaskDescriptionIcon(String iconFilename, int userId) {
1215            if (iconFilename != null) {
1216                try {
1217                    return getService().getTaskDescriptionIcon(iconFilename,
1218                            userId);
1219                } catch (RemoteException e) {
1220                    throw e.rethrowFromSystemServer();
1221                }
1222            }
1223            return null;
1224        }
1225
1226        /**
1227         * @return The color override on the theme's primary color.
1228         */
1229        public int getPrimaryColor() {
1230            return mColorPrimary;
1231        }
1232
1233        /**
1234         * @return The background color.
1235         * @hide
1236         */
1237        public int getBackgroundColor() {
1238            return mColorBackground;
1239        }
1240
1241        /**
1242         * @hide
1243         */
1244        public int getStatusBarColor() {
1245            return mStatusBarColor;
1246        }
1247
1248        /**
1249         * @hide
1250         */
1251        public int getNavigationBarColor() {
1252            return mNavigationBarColor;
1253        }
1254
1255        /** @hide */
1256        public void saveToXml(XmlSerializer out) throws IOException {
1257            if (mLabel != null) {
1258                out.attribute(null, ATTR_TASKDESCRIPTIONLABEL, mLabel);
1259            }
1260            if (mColorPrimary != 0) {
1261                out.attribute(null, ATTR_TASKDESCRIPTIONCOLOR_PRIMARY,
1262                        Integer.toHexString(mColorPrimary));
1263            }
1264            if (mColorBackground != 0) {
1265                out.attribute(null, ATTR_TASKDESCRIPTIONCOLOR_BACKGROUND,
1266                        Integer.toHexString(mColorBackground));
1267            }
1268            if (mIconFilename != null) {
1269                out.attribute(null, ATTR_TASKDESCRIPTIONICON_FILENAME, mIconFilename);
1270            }
1271            if (mIconRes != 0) {
1272                out.attribute(null, ATTR_TASKDESCRIPTIONICON_RESOURCE, Integer.toString(mIconRes));
1273            }
1274        }
1275
1276        /** @hide */
1277        public void restoreFromXml(String attrName, String attrValue) {
1278            if (ATTR_TASKDESCRIPTIONLABEL.equals(attrName)) {
1279                setLabel(attrValue);
1280            } else if (ATTR_TASKDESCRIPTIONCOLOR_PRIMARY.equals(attrName)) {
1281                setPrimaryColor((int) Long.parseLong(attrValue, 16));
1282            } else if (ATTR_TASKDESCRIPTIONCOLOR_BACKGROUND.equals(attrName)) {
1283                setBackgroundColor((int) Long.parseLong(attrValue, 16));
1284            } else if (ATTR_TASKDESCRIPTIONICON_FILENAME.equals(attrName)) {
1285                setIconFilename(attrValue);
1286            } else if (ATTR_TASKDESCRIPTIONICON_RESOURCE.equals(attrName)) {
1287                setIcon(Integer.parseInt(attrValue, 10));
1288            }
1289        }
1290
1291        @Override
1292        public int describeContents() {
1293            return 0;
1294        }
1295
1296        @Override
1297        public void writeToParcel(Parcel dest, int flags) {
1298            if (mLabel == null) {
1299                dest.writeInt(0);
1300            } else {
1301                dest.writeInt(1);
1302                dest.writeString(mLabel);
1303            }
1304            if (mIcon == null) {
1305                dest.writeInt(0);
1306            } else {
1307                dest.writeInt(1);
1308                mIcon.writeToParcel(dest, 0);
1309            }
1310            dest.writeInt(mIconRes);
1311            dest.writeInt(mColorPrimary);
1312            dest.writeInt(mColorBackground);
1313            dest.writeInt(mStatusBarColor);
1314            dest.writeInt(mNavigationBarColor);
1315            if (mIconFilename == null) {
1316                dest.writeInt(0);
1317            } else {
1318                dest.writeInt(1);
1319                dest.writeString(mIconFilename);
1320            }
1321        }
1322
1323        public void readFromParcel(Parcel source) {
1324            mLabel = source.readInt() > 0 ? source.readString() : null;
1325            mIcon = source.readInt() > 0 ? Bitmap.CREATOR.createFromParcel(source) : null;
1326            mIconRes = source.readInt();
1327            mColorPrimary = source.readInt();
1328            mColorBackground = source.readInt();
1329            mStatusBarColor = source.readInt();
1330            mNavigationBarColor = source.readInt();
1331            mIconFilename = source.readInt() > 0 ? source.readString() : null;
1332        }
1333
1334        public static final Creator<TaskDescription> CREATOR
1335                = new Creator<TaskDescription>() {
1336            public TaskDescription createFromParcel(Parcel source) {
1337                return new TaskDescription(source);
1338            }
1339            public TaskDescription[] newArray(int size) {
1340                return new TaskDescription[size];
1341            }
1342        };
1343
1344        @Override
1345        public String toString() {
1346            return "TaskDescription Label: " + mLabel + " Icon: " + mIcon +
1347                    " IconRes: " + mIconRes + " IconFilename: " + mIconFilename +
1348                    " colorPrimary: " + mColorPrimary + " colorBackground: " + mColorBackground +
1349                    " statusBarColor: " + mColorBackground +
1350                    " navigationBarColor: " + mNavigationBarColor;
1351        }
1352    }
1353
1354    /**
1355     * Information you can retrieve about tasks that the user has most recently
1356     * started or visited.
1357     */
1358    public static class RecentTaskInfo implements Parcelable {
1359        /**
1360         * If this task is currently running, this is the identifier for it.
1361         * If it is not running, this will be -1.
1362         */
1363        public int id;
1364
1365        /**
1366         * The true identifier of this task, valid even if it is not running.
1367         */
1368        public int persistentId;
1369
1370        /**
1371         * The original Intent used to launch the task.  You can use this
1372         * Intent to re-launch the task (if it is no longer running) or bring
1373         * the current task to the front.
1374         */
1375        public Intent baseIntent;
1376
1377        /**
1378         * If this task was started from an alias, this is the actual
1379         * activity component that was initially started; the component of
1380         * the baseIntent in this case is the name of the actual activity
1381         * implementation that the alias referred to.  Otherwise, this is null.
1382         */
1383        public ComponentName origActivity;
1384
1385        /**
1386         * The actual activity component that started the task.
1387         * @hide
1388         */
1389        @Nullable
1390        public ComponentName realActivity;
1391
1392        /**
1393         * Description of the task's last state.
1394         */
1395        public CharSequence description;
1396
1397        /**
1398         * The id of the ActivityStack this Task was on most recently.
1399         * @hide
1400         */
1401        public int stackId;
1402
1403        /**
1404         * The id of the user the task was running as.
1405         * @hide
1406         */
1407        public int userId;
1408
1409        /**
1410         * The first time this task was active.
1411         * @hide
1412         */
1413        public long firstActiveTime;
1414
1415        /**
1416         * The last time this task was active.
1417         * @hide
1418         */
1419        public long lastActiveTime;
1420
1421        /**
1422         * The recent activity values for the highest activity in the stack to have set the values.
1423         * {@link Activity#setTaskDescription(android.app.ActivityManager.TaskDescription)}.
1424         */
1425        public TaskDescription taskDescription;
1426
1427        /**
1428         * Task affiliation for grouping with other tasks.
1429         */
1430        public int affiliatedTaskId;
1431
1432        /**
1433         * Task affiliation color of the source task with the affiliated task id.
1434         *
1435         * @hide
1436         */
1437        public int affiliatedTaskColor;
1438
1439        /**
1440         * The component launched as the first activity in the task.
1441         * This can be considered the "application" of this task.
1442         */
1443        public ComponentName baseActivity;
1444
1445        /**
1446         * The activity component at the top of the history stack of the task.
1447         * This is what the user is currently doing.
1448         */
1449        public ComponentName topActivity;
1450
1451        /**
1452         * Number of activities in this task.
1453         */
1454        public int numActivities;
1455
1456        /**
1457         * The bounds of the task.
1458         * @hide
1459         */
1460        public Rect bounds;
1461
1462        /**
1463         * True if the task can go in the docked stack.
1464         * @hide
1465         */
1466        public boolean supportsSplitScreenMultiWindow;
1467
1468        /**
1469         * The resize mode of the task. See {@link ActivityInfo#resizeMode}.
1470         * @hide
1471         */
1472        public int resizeMode;
1473
1474        /**
1475         * The current configuration this task is in.
1476         * @hide
1477         */
1478        final public Configuration configuration = new Configuration();
1479
1480        public RecentTaskInfo() {
1481        }
1482
1483        @Override
1484        public int describeContents() {
1485            return 0;
1486        }
1487
1488        @Override
1489        public void writeToParcel(Parcel dest, int flags) {
1490            dest.writeInt(id);
1491            dest.writeInt(persistentId);
1492            if (baseIntent != null) {
1493                dest.writeInt(1);
1494                baseIntent.writeToParcel(dest, 0);
1495            } else {
1496                dest.writeInt(0);
1497            }
1498            ComponentName.writeToParcel(origActivity, dest);
1499            ComponentName.writeToParcel(realActivity, dest);
1500            TextUtils.writeToParcel(description, dest,
1501                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1502            if (taskDescription != null) {
1503                dest.writeInt(1);
1504                taskDescription.writeToParcel(dest, 0);
1505            } else {
1506                dest.writeInt(0);
1507            }
1508            dest.writeInt(stackId);
1509            dest.writeInt(userId);
1510            dest.writeLong(lastActiveTime);
1511            dest.writeInt(affiliatedTaskId);
1512            dest.writeInt(affiliatedTaskColor);
1513            ComponentName.writeToParcel(baseActivity, dest);
1514            ComponentName.writeToParcel(topActivity, dest);
1515            dest.writeInt(numActivities);
1516            if (bounds != null) {
1517                dest.writeInt(1);
1518                bounds.writeToParcel(dest, 0);
1519            } else {
1520                dest.writeInt(0);
1521            }
1522            dest.writeInt(supportsSplitScreenMultiWindow ? 1 : 0);
1523            dest.writeInt(resizeMode);
1524            configuration.writeToParcel(dest, flags);
1525        }
1526
1527        public void readFromParcel(Parcel source) {
1528            id = source.readInt();
1529            persistentId = source.readInt();
1530            baseIntent = source.readInt() > 0 ? Intent.CREATOR.createFromParcel(source) : null;
1531            origActivity = ComponentName.readFromParcel(source);
1532            realActivity = ComponentName.readFromParcel(source);
1533            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
1534            taskDescription = source.readInt() > 0 ?
1535                    TaskDescription.CREATOR.createFromParcel(source) : null;
1536            stackId = source.readInt();
1537            userId = source.readInt();
1538            lastActiveTime = source.readLong();
1539            affiliatedTaskId = source.readInt();
1540            affiliatedTaskColor = source.readInt();
1541            baseActivity = ComponentName.readFromParcel(source);
1542            topActivity = ComponentName.readFromParcel(source);
1543            numActivities = source.readInt();
1544            bounds = source.readInt() > 0 ?
1545                    Rect.CREATOR.createFromParcel(source) : null;
1546            supportsSplitScreenMultiWindow = source.readInt() == 1;
1547            resizeMode = source.readInt();
1548            configuration.readFromParcel(source);
1549        }
1550
1551        public static final Creator<RecentTaskInfo> CREATOR
1552                = new Creator<RecentTaskInfo>() {
1553            public RecentTaskInfo createFromParcel(Parcel source) {
1554                return new RecentTaskInfo(source);
1555            }
1556            public RecentTaskInfo[] newArray(int size) {
1557                return new RecentTaskInfo[size];
1558            }
1559        };
1560
1561        private RecentTaskInfo(Parcel source) {
1562            readFromParcel(source);
1563        }
1564    }
1565
1566    /**
1567     * Flag for use with {@link #getRecentTasks}: return all tasks, even those
1568     * that have set their
1569     * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
1570     */
1571    public static final int RECENT_WITH_EXCLUDED = 0x0001;
1572
1573    /**
1574     * Provides a list that does not contain any
1575     * recent tasks that currently are not available to the user.
1576     */
1577    public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002;
1578
1579    /**
1580     * <p></p>Return a list of the tasks that the user has recently launched, with
1581     * the most recent being first and older ones after in order.
1582     *
1583     * <p><b>Note: this method is only intended for debugging and presenting
1584     * task management user interfaces</b>.  This should never be used for
1585     * core logic in an application, such as deciding between different
1586     * behaviors based on the information found here.  Such uses are
1587     * <em>not</em> supported, and will likely break in the future.  For
1588     * example, if multiple applications can be actively running at the
1589     * same time, assumptions made about the meaning of the data here for
1590     * purposes of control flow will be incorrect.</p>
1591     *
1592     * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method is
1593     * no longer available to third party applications: the introduction of
1594     * document-centric recents means
1595     * it can leak personal information to the caller.  For backwards compatibility,
1596     * it will still return a small subset of its data: at least the caller's
1597     * own tasks (though see {@link #getAppTasks()} for the correct supported
1598     * way to retrieve that information), and possibly some other tasks
1599     * such as home that are known to not be sensitive.
1600     *
1601     * @param maxNum The maximum number of entries to return in the list.  The
1602     * actual number returned may be smaller, depending on how many tasks the
1603     * user has started and the maximum number the system can remember.
1604     * @param flags Information about what to return.  May be any combination
1605     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
1606     *
1607     * @return Returns a list of RecentTaskInfo records describing each of
1608     * the recent tasks.
1609     */
1610    @Deprecated
1611    public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags)
1612            throws SecurityException {
1613        try {
1614            if (maxNum < 0) {
1615                throw new IllegalArgumentException("The requested number of tasks should be >= 0");
1616            }
1617            return getService().getRecentTasks(maxNum, flags, UserHandle.myUserId()).getList();
1618        } catch (RemoteException e) {
1619            throw e.rethrowFromSystemServer();
1620        }
1621    }
1622
1623    /**
1624     * Information you can retrieve about a particular task that is currently
1625     * "running" in the system.  Note that a running task does not mean the
1626     * given task actually has a process it is actively running in; it simply
1627     * means that the user has gone to it and never closed it, but currently
1628     * the system may have killed its process and is only holding on to its
1629     * last state in order to restart it when the user returns.
1630     */
1631    public static class RunningTaskInfo implements Parcelable {
1632        /**
1633         * A unique identifier for this task.
1634         */
1635        public int id;
1636
1637        /**
1638         * The stack that currently contains this task.
1639         * @hide
1640         */
1641        public int stackId;
1642
1643        /**
1644         * The component launched as the first activity in the task.  This can
1645         * be considered the "application" of this task.
1646         */
1647        public ComponentName baseActivity;
1648
1649        /**
1650         * The activity component at the top of the history stack of the task.
1651         * This is what the user is currently doing.
1652         */
1653        public ComponentName topActivity;
1654
1655        /**
1656         * Thumbnail representation of the task's current state.  Currently
1657         * always null.
1658         */
1659        public Bitmap thumbnail;
1660
1661        /**
1662         * Description of the task's current state.
1663         */
1664        public CharSequence description;
1665
1666        /**
1667         * Number of activities in this task.
1668         */
1669        public int numActivities;
1670
1671        /**
1672         * Number of activities that are currently running (not stopped
1673         * and persisted) in this task.
1674         */
1675        public int numRunning;
1676
1677        /**
1678         * Last time task was run. For sorting.
1679         * @hide
1680         */
1681        public long lastActiveTime;
1682
1683        /**
1684         * True if the task can go in the docked stack.
1685         * @hide
1686         */
1687        public boolean supportsSplitScreenMultiWindow;
1688
1689        /**
1690         * The resize mode of the task. See {@link ActivityInfo#resizeMode}.
1691         * @hide
1692         */
1693        public int resizeMode;
1694
1695        /**
1696         * The full configuration the task is currently running in.
1697         * @hide
1698         */
1699        final public Configuration configuration = new Configuration();
1700
1701        public RunningTaskInfo() {
1702        }
1703
1704        public int describeContents() {
1705            return 0;
1706        }
1707
1708        public void writeToParcel(Parcel dest, int flags) {
1709            dest.writeInt(id);
1710            dest.writeInt(stackId);
1711            ComponentName.writeToParcel(baseActivity, dest);
1712            ComponentName.writeToParcel(topActivity, dest);
1713            if (thumbnail != null) {
1714                dest.writeInt(1);
1715                thumbnail.writeToParcel(dest, 0);
1716            } else {
1717                dest.writeInt(0);
1718            }
1719            TextUtils.writeToParcel(description, dest,
1720                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1721            dest.writeInt(numActivities);
1722            dest.writeInt(numRunning);
1723            dest.writeInt(supportsSplitScreenMultiWindow ? 1 : 0);
1724            dest.writeInt(resizeMode);
1725            configuration.writeToParcel(dest, flags);
1726        }
1727
1728        public void readFromParcel(Parcel source) {
1729            id = source.readInt();
1730            stackId = source.readInt();
1731            baseActivity = ComponentName.readFromParcel(source);
1732            topActivity = ComponentName.readFromParcel(source);
1733            if (source.readInt() != 0) {
1734                thumbnail = Bitmap.CREATOR.createFromParcel(source);
1735            } else {
1736                thumbnail = null;
1737            }
1738            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
1739            numActivities = source.readInt();
1740            numRunning = source.readInt();
1741            supportsSplitScreenMultiWindow = source.readInt() != 0;
1742            resizeMode = source.readInt();
1743            configuration.readFromParcel(source);
1744        }
1745
1746        public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
1747            public RunningTaskInfo createFromParcel(Parcel source) {
1748                return new RunningTaskInfo(source);
1749            }
1750            public RunningTaskInfo[] newArray(int size) {
1751                return new RunningTaskInfo[size];
1752            }
1753        };
1754
1755        private RunningTaskInfo(Parcel source) {
1756            readFromParcel(source);
1757        }
1758    }
1759
1760    /**
1761     * Get the list of tasks associated with the calling application.
1762     *
1763     * @return The list of tasks associated with the application making this call.
1764     * @throws SecurityException
1765     */
1766    public List<ActivityManager.AppTask> getAppTasks() {
1767        ArrayList<AppTask> tasks = new ArrayList<AppTask>();
1768        List<IBinder> appTasks;
1769        try {
1770            appTasks = getService().getAppTasks(mContext.getPackageName());
1771        } catch (RemoteException e) {
1772            throw e.rethrowFromSystemServer();
1773        }
1774        int numAppTasks = appTasks.size();
1775        for (int i = 0; i < numAppTasks; i++) {
1776            tasks.add(new AppTask(IAppTask.Stub.asInterface(appTasks.get(i))));
1777        }
1778        return tasks;
1779    }
1780
1781    /**
1782     * Return the current design dimensions for {@link AppTask} thumbnails, for use
1783     * with {@link #addAppTask}.
1784     */
1785    public Size getAppTaskThumbnailSize() {
1786        synchronized (this) {
1787            ensureAppTaskThumbnailSizeLocked();
1788            return new Size(mAppTaskThumbnailSize.x, mAppTaskThumbnailSize.y);
1789        }
1790    }
1791
1792    private void ensureAppTaskThumbnailSizeLocked() {
1793        if (mAppTaskThumbnailSize == null) {
1794            try {
1795                mAppTaskThumbnailSize = getService().getAppTaskThumbnailSize();
1796            } catch (RemoteException e) {
1797                throw e.rethrowFromSystemServer();
1798            }
1799        }
1800    }
1801
1802    /**
1803     * Add a new {@link AppTask} for the calling application.  This will create a new
1804     * recents entry that is added to the <b>end</b> of all existing recents.
1805     *
1806     * @param activity The activity that is adding the entry.   This is used to help determine
1807     * the context that the new recents entry will be in.
1808     * @param intent The Intent that describes the recents entry.  This is the same Intent that
1809     * you would have used to launch the activity for it.  In generally you will want to set
1810     * both {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT} and
1811     * {@link Intent#FLAG_ACTIVITY_RETAIN_IN_RECENTS}; the latter is required since this recents
1812     * entry will exist without an activity, so it doesn't make sense to not retain it when
1813     * its activity disappears.  The given Intent here also must have an explicit ComponentName
1814     * set on it.
1815     * @param description Optional additional description information.
1816     * @param thumbnail Thumbnail to use for the recents entry.  Should be the size given by
1817     * {@link #getAppTaskThumbnailSize()}.  If the bitmap is not that exact size, it will be
1818     * recreated in your process, probably in a way you don't like, before the recents entry
1819     * is added.
1820     *
1821     * @return Returns the task id of the newly added app task, or -1 if the add failed.  The
1822     * most likely cause of failure is that there is no more room for more tasks for your app.
1823     */
1824    public int addAppTask(@NonNull Activity activity, @NonNull Intent intent,
1825            @Nullable TaskDescription description, @NonNull Bitmap thumbnail) {
1826        Point size;
1827        synchronized (this) {
1828            ensureAppTaskThumbnailSizeLocked();
1829            size = mAppTaskThumbnailSize;
1830        }
1831        final int tw = thumbnail.getWidth();
1832        final int th = thumbnail.getHeight();
1833        if (tw != size.x || th != size.y) {
1834            Bitmap bm = Bitmap.createBitmap(size.x, size.y, thumbnail.getConfig());
1835
1836            // Use ScaleType.CENTER_CROP, except we leave the top edge at the top.
1837            float scale;
1838            float dx = 0, dy = 0;
1839            if (tw * size.x > size.y * th) {
1840                scale = (float) size.x / (float) th;
1841                dx = (size.y - tw * scale) * 0.5f;
1842            } else {
1843                scale = (float) size.y / (float) tw;
1844                dy = (size.x - th * scale) * 0.5f;
1845            }
1846            Matrix matrix = new Matrix();
1847            matrix.setScale(scale, scale);
1848            matrix.postTranslate((int) (dx + 0.5f), 0);
1849
1850            Canvas canvas = new Canvas(bm);
1851            canvas.drawBitmap(thumbnail, matrix, null);
1852            canvas.setBitmap(null);
1853
1854            thumbnail = bm;
1855        }
1856        if (description == null) {
1857            description = new TaskDescription();
1858        }
1859        try {
1860            return getService().addAppTask(activity.getActivityToken(),
1861                    intent, description, thumbnail);
1862        } catch (RemoteException e) {
1863            throw e.rethrowFromSystemServer();
1864        }
1865    }
1866
1867    /**
1868     * Return a list of the tasks that are currently running, with
1869     * the most recent being first and older ones after in order.  Note that
1870     * "running" does not mean any of the task's code is currently loaded or
1871     * activity -- the task may have been frozen by the system, so that it
1872     * can be restarted in its previous state when next brought to the
1873     * foreground.
1874     *
1875     * <p><b>Note: this method is only intended for debugging and presenting
1876     * task management user interfaces</b>.  This should never be used for
1877     * core logic in an application, such as deciding between different
1878     * behaviors based on the information found here.  Such uses are
1879     * <em>not</em> supported, and will likely break in the future.  For
1880     * example, if multiple applications can be actively running at the
1881     * same time, assumptions made about the meaning of the data here for
1882     * purposes of control flow will be incorrect.</p>
1883     *
1884     * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method
1885     * is no longer available to third party
1886     * applications: the introduction of document-centric recents means
1887     * it can leak person information to the caller.  For backwards compatibility,
1888     * it will still return a small subset of its data: at least the caller's
1889     * own tasks, and possibly some other tasks
1890     * such as home that are known to not be sensitive.
1891     *
1892     * @param maxNum The maximum number of entries to return in the list.  The
1893     * actual number returned may be smaller, depending on how many tasks the
1894     * user has started.
1895     *
1896     * @return Returns a list of RunningTaskInfo records describing each of
1897     * the running tasks.
1898     */
1899    @Deprecated
1900    public List<RunningTaskInfo> getRunningTasks(int maxNum)
1901            throws SecurityException {
1902        try {
1903            return getService().getTasks(maxNum);
1904        } catch (RemoteException e) {
1905            throw e.rethrowFromSystemServer();
1906        }
1907    }
1908
1909    /**
1910     * Sets the windowing mode for a specific task. Only works on tasks of type
1911     * {@link WindowConfiguration#ACTIVITY_TYPE_STANDARD}
1912     * @param taskId The id of the task to set the windowing mode for.
1913     * @param windowingMode The windowing mode to set for the task.
1914     * @param toTop If the task should be moved to the top once the windowing mode changes.
1915     * @hide
1916     */
1917    @TestApi
1918    @RequiresPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS)
1919    public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop)
1920            throws SecurityException {
1921        try {
1922            getService().setTaskWindowingMode(taskId, windowingMode, toTop);
1923        } catch (RemoteException e) {
1924            throw e.rethrowFromSystemServer();
1925        }
1926    }
1927
1928    /**
1929     * Resizes the input stack id to the given bounds.
1930     * @param stackId Id of the stack to resize.
1931     * @param bounds Bounds to resize the stack to or {@code null} for fullscreen.
1932     * @hide
1933     */
1934    @TestApi
1935    @RequiresPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS)
1936    public void resizeStack(int stackId, Rect bounds) throws SecurityException {
1937        try {
1938            getService().resizeStack(stackId, bounds, false /* allowResizeInDockedMode */,
1939                    false /* preserveWindows */, false /* animate */, -1 /* animationDuration */);
1940        } catch (RemoteException e) {
1941            throw e.rethrowFromSystemServer();
1942        }
1943    }
1944
1945    /**
1946     * Removes stacks in the windowing modes from the system if they are of activity type
1947     * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
1948     *
1949     * @hide
1950     */
1951    @TestApi
1952    @RequiresPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS)
1953    public void removeStacksInWindowingModes(int[] windowingModes) throws SecurityException {
1954        try {
1955            getService().removeStacksInWindowingModes(windowingModes);
1956        } catch (RemoteException e) {
1957            throw e.rethrowFromSystemServer();
1958        }
1959    }
1960
1961    /**
1962     * Removes stack of the activity types from the system.
1963     *
1964     * @hide
1965     */
1966    @TestApi
1967    @RequiresPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS)
1968    public void removeStacksWithActivityTypes(int[] activityTypes) throws SecurityException {
1969        try {
1970            getService().removeStacksWithActivityTypes(activityTypes);
1971        } catch (RemoteException e) {
1972            throw e.rethrowFromSystemServer();
1973        }
1974    }
1975
1976    /**
1977     * Represents a task snapshot.
1978     * @hide
1979     */
1980    public static class TaskSnapshot implements Parcelable {
1981
1982        private final GraphicBuffer mSnapshot;
1983        private final int mOrientation;
1984        private final Rect mContentInsets;
1985        private final boolean mReducedResolution;
1986        private final float mScale;
1987
1988        public TaskSnapshot(GraphicBuffer snapshot, int orientation, Rect contentInsets,
1989                boolean reducedResolution, float scale) {
1990            mSnapshot = snapshot;
1991            mOrientation = orientation;
1992            mContentInsets = new Rect(contentInsets);
1993            mReducedResolution = reducedResolution;
1994            mScale = scale;
1995        }
1996
1997        private TaskSnapshot(Parcel source) {
1998            mSnapshot = source.readParcelable(null /* classLoader */);
1999            mOrientation = source.readInt();
2000            mContentInsets = source.readParcelable(null /* classLoader */);
2001            mReducedResolution = source.readBoolean();
2002            mScale = source.readFloat();
2003        }
2004
2005        /**
2006         * @return The graphic buffer representing the screenshot.
2007         */
2008        public GraphicBuffer getSnapshot() {
2009            return mSnapshot;
2010        }
2011
2012        /**
2013         * @return The screen orientation the screenshot was taken in.
2014         */
2015        public int getOrientation() {
2016            return mOrientation;
2017        }
2018
2019        /**
2020         * @return The system/content insets on the snapshot. These can be clipped off in order to
2021         *         remove any areas behind system bars in the snapshot.
2022         */
2023        public Rect getContentInsets() {
2024            return mContentInsets;
2025        }
2026
2027        /**
2028         * @return Whether this snapshot is a down-sampled version of the full resolution.
2029         */
2030        public boolean isReducedResolution() {
2031            return mReducedResolution;
2032        }
2033
2034        /**
2035         * @return The scale this snapshot was taken in.
2036         */
2037        public float getScale() {
2038            return mScale;
2039        }
2040
2041        @Override
2042        public int describeContents() {
2043            return 0;
2044        }
2045
2046        @Override
2047        public void writeToParcel(Parcel dest, int flags) {
2048            dest.writeParcelable(mSnapshot, 0);
2049            dest.writeInt(mOrientation);
2050            dest.writeParcelable(mContentInsets, 0);
2051            dest.writeBoolean(mReducedResolution);
2052            dest.writeFloat(mScale);
2053        }
2054
2055        @Override
2056        public String toString() {
2057            return "TaskSnapshot{mSnapshot=" + mSnapshot + " mOrientation=" + mOrientation
2058                    + " mContentInsets=" + mContentInsets.toShortString()
2059                    + " mReducedResolution=" + mReducedResolution + " mScale=" + mScale;
2060        }
2061
2062        public static final Creator<TaskSnapshot> CREATOR = new Creator<TaskSnapshot>() {
2063            public TaskSnapshot createFromParcel(Parcel source) {
2064                return new TaskSnapshot(source);
2065            }
2066            public TaskSnapshot[] newArray(int size) {
2067                return new TaskSnapshot[size];
2068            }
2069        };
2070    }
2071
2072    /** @hide */
2073    @IntDef(flag = true, prefix = { "MOVE_TASK_" }, value = {
2074            MOVE_TASK_WITH_HOME,
2075            MOVE_TASK_NO_USER_ACTION,
2076    })
2077    @Retention(RetentionPolicy.SOURCE)
2078    public @interface MoveTaskFlags {}
2079
2080    /**
2081     * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
2082     * activity along with the task, so it is positioned immediately behind
2083     * the task.
2084     */
2085    public static final int MOVE_TASK_WITH_HOME = 0x00000001;
2086
2087    /**
2088     * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
2089     * user-instigated action, so the current activity will not receive a
2090     * hint that the user is leaving.
2091     */
2092    public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
2093
2094    /**
2095     * Equivalent to calling {@link #moveTaskToFront(int, int, Bundle)}
2096     * with a null options argument.
2097     *
2098     * @param taskId The identifier of the task to be moved, as found in
2099     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
2100     * @param flags Additional operational flags.
2101     */
2102    @RequiresPermission(android.Manifest.permission.REORDER_TASKS)
2103    public void moveTaskToFront(int taskId, @MoveTaskFlags int flags) {
2104        moveTaskToFront(taskId, flags, null);
2105    }
2106
2107    /**
2108     * Ask that the task associated with a given task ID be moved to the
2109     * front of the stack, so it is now visible to the user.
2110     *
2111     * @param taskId The identifier of the task to be moved, as found in
2112     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
2113     * @param flags Additional operational flags.
2114     * @param options Additional options for the operation, either null or
2115     * as per {@link Context#startActivity(Intent, android.os.Bundle)
2116     * Context.startActivity(Intent, Bundle)}.
2117     */
2118    @RequiresPermission(android.Manifest.permission.REORDER_TASKS)
2119    public void moveTaskToFront(int taskId, @MoveTaskFlags int flags, Bundle options) {
2120        try {
2121            getService().moveTaskToFront(taskId, flags, options);
2122        } catch (RemoteException e) {
2123            throw e.rethrowFromSystemServer();
2124        }
2125    }
2126
2127    /**
2128     * Information you can retrieve about a particular Service that is
2129     * currently running in the system.
2130     */
2131    public static class RunningServiceInfo implements Parcelable {
2132        /**
2133         * The service component.
2134         */
2135        public ComponentName service;
2136
2137        /**
2138         * If non-zero, this is the process the service is running in.
2139         */
2140        public int pid;
2141
2142        /**
2143         * The UID that owns this service.
2144         */
2145        public int uid;
2146
2147        /**
2148         * The name of the process this service runs in.
2149         */
2150        public String process;
2151
2152        /**
2153         * Set to true if the service has asked to run as a foreground process.
2154         */
2155        public boolean foreground;
2156
2157        /**
2158         * The time when the service was first made active, either by someone
2159         * starting or binding to it.  This
2160         * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
2161         */
2162        public long activeSince;
2163
2164        /**
2165         * Set to true if this service has been explicitly started.
2166         */
2167        public boolean started;
2168
2169        /**
2170         * Number of clients connected to the service.
2171         */
2172        public int clientCount;
2173
2174        /**
2175         * Number of times the service's process has crashed while the service
2176         * is running.
2177         */
2178        public int crashCount;
2179
2180        /**
2181         * The time when there was last activity in the service (either
2182         * explicit requests to start it or clients binding to it).  This
2183         * is in units of {@link android.os.SystemClock#uptimeMillis()}.
2184         */
2185        public long lastActivityTime;
2186
2187        /**
2188         * If non-zero, this service is not currently running, but scheduled to
2189         * restart at the given time.
2190         */
2191        public long restarting;
2192
2193        /**
2194         * Bit for {@link #flags}: set if this service has been
2195         * explicitly started.
2196         */
2197        public static final int FLAG_STARTED = 1<<0;
2198
2199        /**
2200         * Bit for {@link #flags}: set if the service has asked to
2201         * run as a foreground process.
2202         */
2203        public static final int FLAG_FOREGROUND = 1<<1;
2204
2205        /**
2206         * Bit for {@link #flags}: set if the service is running in a
2207         * core system process.
2208         */
2209        public static final int FLAG_SYSTEM_PROCESS = 1<<2;
2210
2211        /**
2212         * Bit for {@link #flags}: set if the service is running in a
2213         * persistent process.
2214         */
2215        public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
2216
2217        /**
2218         * Running flags.
2219         */
2220        public int flags;
2221
2222        /**
2223         * For special services that are bound to by system code, this is
2224         * the package that holds the binding.
2225         */
2226        public String clientPackage;
2227
2228        /**
2229         * For special services that are bound to by system code, this is
2230         * a string resource providing a user-visible label for who the
2231         * client is.
2232         */
2233        public int clientLabel;
2234
2235        public RunningServiceInfo() {
2236        }
2237
2238        public int describeContents() {
2239            return 0;
2240        }
2241
2242        public void writeToParcel(Parcel dest, int flags) {
2243            ComponentName.writeToParcel(service, dest);
2244            dest.writeInt(pid);
2245            dest.writeInt(uid);
2246            dest.writeString(process);
2247            dest.writeInt(foreground ? 1 : 0);
2248            dest.writeLong(activeSince);
2249            dest.writeInt(started ? 1 : 0);
2250            dest.writeInt(clientCount);
2251            dest.writeInt(crashCount);
2252            dest.writeLong(lastActivityTime);
2253            dest.writeLong(restarting);
2254            dest.writeInt(this.flags);
2255            dest.writeString(clientPackage);
2256            dest.writeInt(clientLabel);
2257        }
2258
2259        public void readFromParcel(Parcel source) {
2260            service = ComponentName.readFromParcel(source);
2261            pid = source.readInt();
2262            uid = source.readInt();
2263            process = source.readString();
2264            foreground = source.readInt() != 0;
2265            activeSince = source.readLong();
2266            started = source.readInt() != 0;
2267            clientCount = source.readInt();
2268            crashCount = source.readInt();
2269            lastActivityTime = source.readLong();
2270            restarting = source.readLong();
2271            flags = source.readInt();
2272            clientPackage = source.readString();
2273            clientLabel = source.readInt();
2274        }
2275
2276        public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
2277            public RunningServiceInfo createFromParcel(Parcel source) {
2278                return new RunningServiceInfo(source);
2279            }
2280            public RunningServiceInfo[] newArray(int size) {
2281                return new RunningServiceInfo[size];
2282            }
2283        };
2284
2285        private RunningServiceInfo(Parcel source) {
2286            readFromParcel(source);
2287        }
2288    }
2289
2290    /**
2291     * Return a list of the services that are currently running.
2292     *
2293     * <p><b>Note: this method is only intended for debugging or implementing
2294     * service management type user interfaces.</b></p>
2295     *
2296     * @deprecated As of {@link android.os.Build.VERSION_CODES#O}, this method
2297     * is no longer available to third party applications.  For backwards compatibility,
2298     * it will still return the caller's own services.
2299     *
2300     * @param maxNum The maximum number of entries to return in the list.  The
2301     * actual number returned may be smaller, depending on how many services
2302     * are running.
2303     *
2304     * @return Returns a list of RunningServiceInfo records describing each of
2305     * the running tasks.
2306     */
2307    @Deprecated
2308    public List<RunningServiceInfo> getRunningServices(int maxNum)
2309            throws SecurityException {
2310        try {
2311            return getService()
2312                    .getServices(maxNum, 0);
2313        } catch (RemoteException e) {
2314            throw e.rethrowFromSystemServer();
2315        }
2316    }
2317
2318    /**
2319     * Returns a PendingIntent you can start to show a control panel for the
2320     * given running service.  If the service does not have a control panel,
2321     * null is returned.
2322     */
2323    public PendingIntent getRunningServiceControlPanel(ComponentName service)
2324            throws SecurityException {
2325        try {
2326            return getService()
2327                    .getRunningServiceControlPanel(service);
2328        } catch (RemoteException e) {
2329            throw e.rethrowFromSystemServer();
2330        }
2331    }
2332
2333    /**
2334     * Information you can retrieve about the available memory through
2335     * {@link ActivityManager#getMemoryInfo}.
2336     */
2337    public static class MemoryInfo implements Parcelable {
2338        /**
2339         * The available memory on the system.  This number should not
2340         * be considered absolute: due to the nature of the kernel, a significant
2341         * portion of this memory is actually in use and needed for the overall
2342         * system to run well.
2343         */
2344        public long availMem;
2345
2346        /**
2347         * The total memory accessible by the kernel.  This is basically the
2348         * RAM size of the device, not including below-kernel fixed allocations
2349         * like DMA buffers, RAM for the baseband CPU, etc.
2350         */
2351        public long totalMem;
2352
2353        /**
2354         * The threshold of {@link #availMem} at which we consider memory to be
2355         * low and start killing background services and other non-extraneous
2356         * processes.
2357         */
2358        public long threshold;
2359
2360        /**
2361         * Set to true if the system considers itself to currently be in a low
2362         * memory situation.
2363         */
2364        public boolean lowMemory;
2365
2366        /** @hide */
2367        public long hiddenAppThreshold;
2368        /** @hide */
2369        public long secondaryServerThreshold;
2370        /** @hide */
2371        public long visibleAppThreshold;
2372        /** @hide */
2373        public long foregroundAppThreshold;
2374
2375        public MemoryInfo() {
2376        }
2377
2378        public int describeContents() {
2379            return 0;
2380        }
2381
2382        public void writeToParcel(Parcel dest, int flags) {
2383            dest.writeLong(availMem);
2384            dest.writeLong(totalMem);
2385            dest.writeLong(threshold);
2386            dest.writeInt(lowMemory ? 1 : 0);
2387            dest.writeLong(hiddenAppThreshold);
2388            dest.writeLong(secondaryServerThreshold);
2389            dest.writeLong(visibleAppThreshold);
2390            dest.writeLong(foregroundAppThreshold);
2391        }
2392
2393        public void readFromParcel(Parcel source) {
2394            availMem = source.readLong();
2395            totalMem = source.readLong();
2396            threshold = source.readLong();
2397            lowMemory = source.readInt() != 0;
2398            hiddenAppThreshold = source.readLong();
2399            secondaryServerThreshold = source.readLong();
2400            visibleAppThreshold = source.readLong();
2401            foregroundAppThreshold = source.readLong();
2402        }
2403
2404        public static final Creator<MemoryInfo> CREATOR
2405                = new Creator<MemoryInfo>() {
2406            public MemoryInfo createFromParcel(Parcel source) {
2407                return new MemoryInfo(source);
2408            }
2409            public MemoryInfo[] newArray(int size) {
2410                return new MemoryInfo[size];
2411            }
2412        };
2413
2414        private MemoryInfo(Parcel source) {
2415            readFromParcel(source);
2416        }
2417    }
2418
2419    /**
2420     * Return general information about the memory state of the system.  This
2421     * can be used to help decide how to manage your own memory, though note
2422     * that polling is not recommended and
2423     * {@link android.content.ComponentCallbacks2#onTrimMemory(int)
2424     * ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this.
2425     * Also see {@link #getMyMemoryState} for how to retrieve the current trim
2426     * level of your process as needed, which gives a better hint for how to
2427     * manage its memory.
2428     */
2429    public void getMemoryInfo(MemoryInfo outInfo) {
2430        try {
2431            getService().getMemoryInfo(outInfo);
2432        } catch (RemoteException e) {
2433            throw e.rethrowFromSystemServer();
2434        }
2435    }
2436
2437    /**
2438     * Information you can retrieve about an ActivityStack in the system.
2439     * @hide
2440     */
2441    public static class StackInfo implements Parcelable {
2442        public int stackId;
2443        public Rect bounds = new Rect();
2444        public int[] taskIds;
2445        public String[] taskNames;
2446        public Rect[] taskBounds;
2447        public int[] taskUserIds;
2448        public ComponentName topActivity;
2449        public int displayId;
2450        public int userId;
2451        public boolean visible;
2452        // Index of the stack in the display's stack list, can be used for comparison of stack order
2453        public int position;
2454        /**
2455         * The full configuration the stack is currently running in.
2456         * @hide
2457         */
2458        final public Configuration configuration = new Configuration();
2459
2460        @Override
2461        public int describeContents() {
2462            return 0;
2463        }
2464
2465        @Override
2466        public void writeToParcel(Parcel dest, int flags) {
2467            dest.writeInt(stackId);
2468            dest.writeInt(bounds.left);
2469            dest.writeInt(bounds.top);
2470            dest.writeInt(bounds.right);
2471            dest.writeInt(bounds.bottom);
2472            dest.writeIntArray(taskIds);
2473            dest.writeStringArray(taskNames);
2474            final int boundsCount = taskBounds == null ? 0 : taskBounds.length;
2475            dest.writeInt(boundsCount);
2476            for (int i = 0; i < boundsCount; i++) {
2477                dest.writeInt(taskBounds[i].left);
2478                dest.writeInt(taskBounds[i].top);
2479                dest.writeInt(taskBounds[i].right);
2480                dest.writeInt(taskBounds[i].bottom);
2481            }
2482            dest.writeIntArray(taskUserIds);
2483            dest.writeInt(displayId);
2484            dest.writeInt(userId);
2485            dest.writeInt(visible ? 1 : 0);
2486            dest.writeInt(position);
2487            if (topActivity != null) {
2488                dest.writeInt(1);
2489                topActivity.writeToParcel(dest, 0);
2490            } else {
2491                dest.writeInt(0);
2492            }
2493            configuration.writeToParcel(dest, flags);
2494        }
2495
2496        public void readFromParcel(Parcel source) {
2497            stackId = source.readInt();
2498            bounds = new Rect(
2499                    source.readInt(), source.readInt(), source.readInt(), source.readInt());
2500            taskIds = source.createIntArray();
2501            taskNames = source.createStringArray();
2502            final int boundsCount = source.readInt();
2503            if (boundsCount > 0) {
2504                taskBounds = new Rect[boundsCount];
2505                for (int i = 0; i < boundsCount; i++) {
2506                    taskBounds[i] = new Rect();
2507                    taskBounds[i].set(
2508                            source.readInt(), source.readInt(), source.readInt(), source.readInt());
2509                }
2510            } else {
2511                taskBounds = null;
2512            }
2513            taskUserIds = source.createIntArray();
2514            displayId = source.readInt();
2515            userId = source.readInt();
2516            visible = source.readInt() > 0;
2517            position = source.readInt();
2518            if (source.readInt() > 0) {
2519                topActivity = ComponentName.readFromParcel(source);
2520            }
2521            configuration.readFromParcel(source);
2522        }
2523
2524        public static final Creator<StackInfo> CREATOR = new Creator<StackInfo>() {
2525            @Override
2526            public StackInfo createFromParcel(Parcel source) {
2527                return new StackInfo(source);
2528            }
2529            @Override
2530            public StackInfo[] newArray(int size) {
2531                return new StackInfo[size];
2532            }
2533        };
2534
2535        public StackInfo() {
2536        }
2537
2538        private StackInfo(Parcel source) {
2539            readFromParcel(source);
2540        }
2541
2542        public String toString(String prefix) {
2543            StringBuilder sb = new StringBuilder(256);
2544            sb.append(prefix); sb.append("Stack id="); sb.append(stackId);
2545                    sb.append(" bounds="); sb.append(bounds.toShortString());
2546                    sb.append(" displayId="); sb.append(displayId);
2547                    sb.append(" userId="); sb.append(userId);
2548                    sb.append("\n");
2549                    sb.append(" configuration="); sb.append(configuration);
2550                    sb.append("\n");
2551            prefix = prefix + "  ";
2552            for (int i = 0; i < taskIds.length; ++i) {
2553                sb.append(prefix); sb.append("taskId="); sb.append(taskIds[i]);
2554                        sb.append(": "); sb.append(taskNames[i]);
2555                        if (taskBounds != null) {
2556                            sb.append(" bounds="); sb.append(taskBounds[i].toShortString());
2557                        }
2558                        sb.append(" userId=").append(taskUserIds[i]);
2559                        sb.append(" visible=").append(visible);
2560                        if (topActivity != null) {
2561                            sb.append(" topActivity=").append(topActivity);
2562                        }
2563                        sb.append("\n");
2564            }
2565            return sb.toString();
2566        }
2567
2568        @Override
2569        public String toString() {
2570            return toString("");
2571        }
2572    }
2573
2574    /**
2575     * @hide
2576     */
2577    @RequiresPermission(anyOf={Manifest.permission.CLEAR_APP_USER_DATA,
2578            Manifest.permission.ACCESS_INSTANT_APPS})
2579    public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
2580        try {
2581            return getService().clearApplicationUserData(packageName,
2582                    observer, UserHandle.myUserId());
2583        } catch (RemoteException e) {
2584            throw e.rethrowFromSystemServer();
2585        }
2586    }
2587
2588    /**
2589     * Permits an application to erase its own data from disk.  This is equivalent to
2590     * the user choosing to clear the app's data from within the device settings UI.  It
2591     * erases all dynamic data associated with the app -- its private data and data in its
2592     * private area on external storage -- but does not remove the installed application
2593     * itself, nor any OBB files. It also revokes all runtime permissions that the app has acquired,
2594     * clears all notifications and removes all Uri grants related to this application.
2595     *
2596     * @return {@code true} if the application successfully requested that the application's
2597     *     data be erased; {@code false} otherwise.
2598     */
2599    public boolean clearApplicationUserData() {
2600        return clearApplicationUserData(mContext.getPackageName(), null);
2601    }
2602
2603
2604    /**
2605     * Permits an application to get the persistent URI permissions granted to another.
2606     *
2607     * <p>Typically called by Settings.
2608     *
2609     * @param packageName application to look for the granted permissions
2610     * @return list of granted URI permissions
2611     *
2612     * @hide
2613     */
2614    public ParceledListSlice<UriPermission> getGrantedUriPermissions(String packageName) {
2615        try {
2616            return getService().getGrantedUriPermissions(packageName,
2617                    UserHandle.myUserId());
2618        } catch (RemoteException e) {
2619            throw e.rethrowFromSystemServer();
2620        }
2621    }
2622
2623    /**
2624     * Permits an application to clear the persistent URI permissions granted to another.
2625     *
2626     * <p>Typically called by Settings.
2627     *
2628     * @param packageName application to clear its granted permissions
2629     *
2630     * @hide
2631     */
2632    public void clearGrantedUriPermissions(String packageName) {
2633        try {
2634            getService().clearGrantedUriPermissions(packageName,
2635                    UserHandle.myUserId());
2636        } catch (RemoteException e) {
2637            throw e.rethrowFromSystemServer();
2638        }
2639    }
2640
2641    /**
2642     * Information you can retrieve about any processes that are in an error condition.
2643     */
2644    public static class ProcessErrorStateInfo implements Parcelable {
2645        /**
2646         * Condition codes
2647         */
2648        public static final int NO_ERROR = 0;
2649        public static final int CRASHED = 1;
2650        public static final int NOT_RESPONDING = 2;
2651
2652        /**
2653         * The condition that the process is in.
2654         */
2655        public int condition;
2656
2657        /**
2658         * The process name in which the crash or error occurred.
2659         */
2660        public String processName;
2661
2662        /**
2663         * The pid of this process; 0 if none
2664         */
2665        public int pid;
2666
2667        /**
2668         * The kernel user-ID that has been assigned to this process;
2669         * currently this is not a unique ID (multiple applications can have
2670         * the same uid).
2671         */
2672        public int uid;
2673
2674        /**
2675         * The activity name associated with the error, if known.  May be null.
2676         */
2677        public String tag;
2678
2679        /**
2680         * A short message describing the error condition.
2681         */
2682        public String shortMsg;
2683
2684        /**
2685         * A long message describing the error condition.
2686         */
2687        public String longMsg;
2688
2689        /**
2690         * The stack trace where the error originated.  May be null.
2691         */
2692        public String stackTrace;
2693
2694        /**
2695         * to be deprecated: This value will always be null.
2696         */
2697        public byte[] crashData = null;
2698
2699        public ProcessErrorStateInfo() {
2700        }
2701
2702        @Override
2703        public int describeContents() {
2704            return 0;
2705        }
2706
2707        @Override
2708        public void writeToParcel(Parcel dest, int flags) {
2709            dest.writeInt(condition);
2710            dest.writeString(processName);
2711            dest.writeInt(pid);
2712            dest.writeInt(uid);
2713            dest.writeString(tag);
2714            dest.writeString(shortMsg);
2715            dest.writeString(longMsg);
2716            dest.writeString(stackTrace);
2717        }
2718
2719        public void readFromParcel(Parcel source) {
2720            condition = source.readInt();
2721            processName = source.readString();
2722            pid = source.readInt();
2723            uid = source.readInt();
2724            tag = source.readString();
2725            shortMsg = source.readString();
2726            longMsg = source.readString();
2727            stackTrace = source.readString();
2728        }
2729
2730        public static final Creator<ProcessErrorStateInfo> CREATOR =
2731                new Creator<ProcessErrorStateInfo>() {
2732            public ProcessErrorStateInfo createFromParcel(Parcel source) {
2733                return new ProcessErrorStateInfo(source);
2734            }
2735            public ProcessErrorStateInfo[] newArray(int size) {
2736                return new ProcessErrorStateInfo[size];
2737            }
2738        };
2739
2740        private ProcessErrorStateInfo(Parcel source) {
2741            readFromParcel(source);
2742        }
2743    }
2744
2745    /**
2746     * Returns a list of any processes that are currently in an error condition.  The result
2747     * will be null if all processes are running properly at this time.
2748     *
2749     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
2750     * current error conditions (it will not return an empty list).  This list ordering is not
2751     * specified.
2752     */
2753    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
2754        try {
2755            return getService().getProcessesInErrorState();
2756        } catch (RemoteException e) {
2757            throw e.rethrowFromSystemServer();
2758        }
2759    }
2760
2761    /**
2762     * Information you can retrieve about a running process.
2763     */
2764    public static class RunningAppProcessInfo implements Parcelable {
2765        /**
2766         * The name of the process that this object is associated with
2767         */
2768        public String processName;
2769
2770        /**
2771         * The pid of this process; 0 if none
2772         */
2773        public int pid;
2774
2775        /**
2776         * The user id of this process.
2777         */
2778        public int uid;
2779
2780        /**
2781         * All packages that have been loaded into the process.
2782         */
2783        public String pkgList[];
2784
2785        /**
2786         * Constant for {@link #flags}: this is an app that is unable to
2787         * correctly save its state when going to the background,
2788         * so it can not be killed while in the background.
2789         * @hide
2790         */
2791        public static final int FLAG_CANT_SAVE_STATE = 1<<0;
2792
2793        /**
2794         * Constant for {@link #flags}: this process is associated with a
2795         * persistent system app.
2796         * @hide
2797         */
2798        public static final int FLAG_PERSISTENT = 1<<1;
2799
2800        /**
2801         * Constant for {@link #flags}: this process is associated with a
2802         * persistent system app.
2803         * @hide
2804         */
2805        public static final int FLAG_HAS_ACTIVITIES = 1<<2;
2806
2807        /**
2808         * Flags of information.  May be any of
2809         * {@link #FLAG_CANT_SAVE_STATE}.
2810         * @hide
2811         */
2812        public int flags;
2813
2814        /**
2815         * Last memory trim level reported to the process: corresponds to
2816         * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
2817         * ComponentCallbacks2.onTrimMemory(int)}.
2818         */
2819        public int lastTrimLevel;
2820
2821        /** @hide */
2822        @IntDef(prefix = { "IMPORTANCE_" }, value = {
2823                IMPORTANCE_FOREGROUND,
2824                IMPORTANCE_FOREGROUND_SERVICE,
2825                IMPORTANCE_TOP_SLEEPING,
2826                IMPORTANCE_VISIBLE,
2827                IMPORTANCE_PERCEPTIBLE,
2828                IMPORTANCE_CANT_SAVE_STATE,
2829                IMPORTANCE_SERVICE,
2830                IMPORTANCE_CACHED,
2831                IMPORTANCE_GONE,
2832        })
2833        @Retention(RetentionPolicy.SOURCE)
2834        public @interface Importance {}
2835
2836        /**
2837         * Constant for {@link #importance}: This process is running the
2838         * foreground UI; that is, it is the thing currently at the top of the screen
2839         * that the user is interacting with.
2840         */
2841        public static final int IMPORTANCE_FOREGROUND = 100;
2842
2843        /**
2844         * Constant for {@link #importance}: This process is running a foreground
2845         * service, for example to perform music playback even while the user is
2846         * not immediately in the app.  This generally indicates that the process
2847         * is doing something the user actively cares about.
2848         */
2849        public static final int IMPORTANCE_FOREGROUND_SERVICE = 125;
2850
2851        /**
2852         * Constant for {@link #importance}: This process is running the foreground
2853         * UI, but the device is asleep so it is not visible to the user.  This means
2854         * the user is not really aware of the process, because they can not see or
2855         * interact with it, but it is quite important because it what they expect to
2856         * return to once unlocking the device.
2857         */
2858        public static final int IMPORTANCE_TOP_SLEEPING = 150;
2859
2860        /**
2861         * Constant for {@link #importance}: This process is running something
2862         * that is actively visible to the user, though not in the immediate
2863         * foreground.  This may be running a window that is behind the current
2864         * foreground (so paused and with its state saved, not interacting with
2865         * the user, but visible to them to some degree); it may also be running
2866         * other services under the system's control that it inconsiders important.
2867         */
2868        public static final int IMPORTANCE_VISIBLE = 200;
2869
2870        /**
2871         * Constant for {@link #importance}: {@link #IMPORTANCE_PERCEPTIBLE} had this wrong value
2872         * before {@link Build.VERSION_CODES#O}.  Since the {@link Build.VERSION_CODES#O} SDK,
2873         * the value of {@link #IMPORTANCE_PERCEPTIBLE} has been fixed.
2874         *
2875         * <p>The system will return this value instead of {@link #IMPORTANCE_PERCEPTIBLE}
2876         * on Android versions below {@link Build.VERSION_CODES#O}.
2877         *
2878         * <p>On Android version {@link Build.VERSION_CODES#O} and later, this value will still be
2879         * returned for apps with the target API level below {@link Build.VERSION_CODES#O}.
2880         * For apps targeting version {@link Build.VERSION_CODES#O} and later,
2881         * the correct value {@link #IMPORTANCE_PERCEPTIBLE} will be returned.
2882         */
2883        public static final int IMPORTANCE_PERCEPTIBLE_PRE_26 = 130;
2884
2885        /**
2886         * Constant for {@link #importance}: This process is not something the user
2887         * is directly aware of, but is otherwise perceptible to them to some degree.
2888         */
2889        public static final int IMPORTANCE_PERCEPTIBLE = 230;
2890
2891        /**
2892         * Constant for {@link #importance}: {@link #IMPORTANCE_CANT_SAVE_STATE} had
2893         * this wrong value
2894         * before {@link Build.VERSION_CODES#O}.  Since the {@link Build.VERSION_CODES#O} SDK,
2895         * the value of {@link #IMPORTANCE_CANT_SAVE_STATE} has been fixed.
2896         *
2897         * <p>The system will return this value instead of {@link #IMPORTANCE_CANT_SAVE_STATE}
2898         * on Android versions below {@link Build.VERSION_CODES#O}.
2899         *
2900         * <p>On Android version {@link Build.VERSION_CODES#O} after, this value will still be
2901         * returned for apps with the target API level below {@link Build.VERSION_CODES#O}.
2902         * For apps targeting version {@link Build.VERSION_CODES#O} and later,
2903         * the correct value {@link #IMPORTANCE_CANT_SAVE_STATE} will be returned.
2904         *
2905         * @hide
2906         */
2907        public static final int IMPORTANCE_CANT_SAVE_STATE_PRE_26 = 170;
2908
2909        /**
2910         * Constant for {@link #importance}: This process is running an
2911         * application that can not save its state, and thus can't be killed
2912         * while in the background.
2913         * @hide
2914         */
2915        public static final int IMPORTANCE_CANT_SAVE_STATE= 270;
2916
2917        /**
2918         * Constant for {@link #importance}: This process is contains services
2919         * that should remain running.  These are background services apps have
2920         * started, not something the user is aware of, so they may be killed by
2921         * the system relatively freely (though it is generally desired that they
2922         * stay running as long as they want to).
2923         */
2924        public static final int IMPORTANCE_SERVICE = 300;
2925
2926        /**
2927         * Constant for {@link #importance}: This process process contains
2928         * cached code that is expendable, not actively running any app components
2929         * we care about.
2930         */
2931        public static final int IMPORTANCE_CACHED = 400;
2932
2933        /**
2934         * @deprecated Renamed to {@link #IMPORTANCE_CACHED}.
2935         */
2936        public static final int IMPORTANCE_BACKGROUND = IMPORTANCE_CACHED;
2937
2938        /**
2939         * Constant for {@link #importance}: This process is empty of any
2940         * actively running code.
2941         * @deprecated This value is no longer reported, use {@link #IMPORTANCE_CACHED} instead.
2942         */
2943        @Deprecated
2944        public static final int IMPORTANCE_EMPTY = 500;
2945
2946        /**
2947         * Constant for {@link #importance}: This process does not exist.
2948         */
2949        public static final int IMPORTANCE_GONE = 1000;
2950
2951        /**
2952         * Convert a proc state to the correspondent IMPORTANCE_* constant.  If the return value
2953         * will be passed to a client, use {@link #procStateToImportanceForClient}.
2954         * @hide
2955         */
2956        public static @Importance int procStateToImportance(int procState) {
2957            if (procState == PROCESS_STATE_NONEXISTENT) {
2958                return IMPORTANCE_GONE;
2959            } else if (procState >= PROCESS_STATE_HOME) {
2960                return IMPORTANCE_CACHED;
2961            } else if (procState >= PROCESS_STATE_SERVICE) {
2962                return IMPORTANCE_SERVICE;
2963            } else if (procState > PROCESS_STATE_HEAVY_WEIGHT) {
2964                return IMPORTANCE_CANT_SAVE_STATE;
2965            } else if (procState >= PROCESS_STATE_TRANSIENT_BACKGROUND) {
2966                return IMPORTANCE_PERCEPTIBLE;
2967            } else if (procState >= PROCESS_STATE_IMPORTANT_FOREGROUND) {
2968                return IMPORTANCE_VISIBLE;
2969            } else if (procState >= PROCESS_STATE_TOP_SLEEPING) {
2970                return IMPORTANCE_TOP_SLEEPING;
2971            } else if (procState >= PROCESS_STATE_FOREGROUND_SERVICE) {
2972                return IMPORTANCE_FOREGROUND_SERVICE;
2973            } else {
2974                return IMPORTANCE_FOREGROUND;
2975            }
2976        }
2977
2978        /**
2979         * Convert a proc state to the correspondent IMPORTANCE_* constant for a client represented
2980         * by a given {@link Context}, with converting {@link #IMPORTANCE_PERCEPTIBLE}
2981         * and {@link #IMPORTANCE_CANT_SAVE_STATE} to the corresponding "wrong" value if the
2982         * client's target SDK < {@link VERSION_CODES#O}.
2983         * @hide
2984         */
2985        public static @Importance int procStateToImportanceForClient(int procState,
2986                Context clientContext) {
2987            return procStateToImportanceForTargetSdk(procState,
2988                    clientContext.getApplicationInfo().targetSdkVersion);
2989        }
2990
2991        /**
2992         * See {@link #procStateToImportanceForClient}.
2993         * @hide
2994         */
2995        public static @Importance int procStateToImportanceForTargetSdk(int procState,
2996                int targetSdkVersion) {
2997            final int importance = procStateToImportance(procState);
2998
2999            // For pre O apps, convert to the old, wrong values.
3000            if (targetSdkVersion < VERSION_CODES.O) {
3001                switch (importance) {
3002                    case IMPORTANCE_PERCEPTIBLE:
3003                        return IMPORTANCE_PERCEPTIBLE_PRE_26;
3004                    case IMPORTANCE_CANT_SAVE_STATE:
3005                        return IMPORTANCE_CANT_SAVE_STATE_PRE_26;
3006                }
3007            }
3008            return importance;
3009        }
3010
3011        /** @hide */
3012        public static int importanceToProcState(@Importance int importance) {
3013            if (importance == IMPORTANCE_GONE) {
3014                return PROCESS_STATE_NONEXISTENT;
3015            } else if (importance >= IMPORTANCE_CACHED) {
3016                return PROCESS_STATE_HOME;
3017            } else if (importance >= IMPORTANCE_SERVICE) {
3018                return PROCESS_STATE_SERVICE;
3019            } else if (importance > IMPORTANCE_CANT_SAVE_STATE) {
3020                return PROCESS_STATE_HEAVY_WEIGHT;
3021            } else if (importance >= IMPORTANCE_PERCEPTIBLE) {
3022                return PROCESS_STATE_TRANSIENT_BACKGROUND;
3023            } else if (importance >= IMPORTANCE_VISIBLE) {
3024                return PROCESS_STATE_IMPORTANT_FOREGROUND;
3025            } else if (importance >= IMPORTANCE_TOP_SLEEPING) {
3026                return PROCESS_STATE_TOP_SLEEPING;
3027            } else if (importance >= IMPORTANCE_FOREGROUND_SERVICE) {
3028                return PROCESS_STATE_FOREGROUND_SERVICE;
3029            } else {
3030                return PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
3031            }
3032        }
3033
3034        /**
3035         * The relative importance level that the system places on this process.
3036         * These constants are numbered so that "more important" values are
3037         * always smaller than "less important" values.
3038         */
3039        public @Importance int importance;
3040
3041        /**
3042         * An additional ordering within a particular {@link #importance}
3043         * category, providing finer-grained information about the relative
3044         * utility of processes within a category.  This number means nothing
3045         * except that a smaller values are more recently used (and thus
3046         * more important).  Currently an LRU value is only maintained for
3047         * the {@link #IMPORTANCE_CACHED} category, though others may
3048         * be maintained in the future.
3049         */
3050        public int lru;
3051
3052        /**
3053         * Constant for {@link #importanceReasonCode}: nothing special has
3054         * been specified for the reason for this level.
3055         */
3056        public static final int REASON_UNKNOWN = 0;
3057
3058        /**
3059         * Constant for {@link #importanceReasonCode}: one of the application's
3060         * content providers is being used by another process.  The pid of
3061         * the client process is in {@link #importanceReasonPid} and the
3062         * target provider in this process is in
3063         * {@link #importanceReasonComponent}.
3064         */
3065        public static final int REASON_PROVIDER_IN_USE = 1;
3066
3067        /**
3068         * Constant for {@link #importanceReasonCode}: one of the application's
3069         * content providers is being used by another process.  The pid of
3070         * the client process is in {@link #importanceReasonPid} and the
3071         * target provider in this process is in
3072         * {@link #importanceReasonComponent}.
3073         */
3074        public static final int REASON_SERVICE_IN_USE = 2;
3075
3076        /**
3077         * The reason for {@link #importance}, if any.
3078         */
3079        public int importanceReasonCode;
3080
3081        /**
3082         * For the specified values of {@link #importanceReasonCode}, this
3083         * is the process ID of the other process that is a client of this
3084         * process.  This will be 0 if no other process is using this one.
3085         */
3086        public int importanceReasonPid;
3087
3088        /**
3089         * For the specified values of {@link #importanceReasonCode}, this
3090         * is the name of the component that is being used in this process.
3091         */
3092        public ComponentName importanceReasonComponent;
3093
3094        /**
3095         * When {@link #importanceReasonPid} is non-0, this is the importance
3096         * of the other pid. @hide
3097         */
3098        public int importanceReasonImportance;
3099
3100        /**
3101         * Current process state, as per PROCESS_STATE_* constants.
3102         * @hide
3103         */
3104        public int processState;
3105
3106        public RunningAppProcessInfo() {
3107            importance = IMPORTANCE_FOREGROUND;
3108            importanceReasonCode = REASON_UNKNOWN;
3109            processState = PROCESS_STATE_IMPORTANT_FOREGROUND;
3110        }
3111
3112        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
3113            processName = pProcessName;
3114            pid = pPid;
3115            pkgList = pArr;
3116        }
3117
3118        public int describeContents() {
3119            return 0;
3120        }
3121
3122        public void writeToParcel(Parcel dest, int flags) {
3123            dest.writeString(processName);
3124            dest.writeInt(pid);
3125            dest.writeInt(uid);
3126            dest.writeStringArray(pkgList);
3127            dest.writeInt(this.flags);
3128            dest.writeInt(lastTrimLevel);
3129            dest.writeInt(importance);
3130            dest.writeInt(lru);
3131            dest.writeInt(importanceReasonCode);
3132            dest.writeInt(importanceReasonPid);
3133            ComponentName.writeToParcel(importanceReasonComponent, dest);
3134            dest.writeInt(importanceReasonImportance);
3135            dest.writeInt(processState);
3136        }
3137
3138        public void readFromParcel(Parcel source) {
3139            processName = source.readString();
3140            pid = source.readInt();
3141            uid = source.readInt();
3142            pkgList = source.readStringArray();
3143            flags = source.readInt();
3144            lastTrimLevel = source.readInt();
3145            importance = source.readInt();
3146            lru = source.readInt();
3147            importanceReasonCode = source.readInt();
3148            importanceReasonPid = source.readInt();
3149            importanceReasonComponent = ComponentName.readFromParcel(source);
3150            importanceReasonImportance = source.readInt();
3151            processState = source.readInt();
3152        }
3153
3154        public static final Creator<RunningAppProcessInfo> CREATOR =
3155            new Creator<RunningAppProcessInfo>() {
3156            public RunningAppProcessInfo createFromParcel(Parcel source) {
3157                return new RunningAppProcessInfo(source);
3158            }
3159            public RunningAppProcessInfo[] newArray(int size) {
3160                return new RunningAppProcessInfo[size];
3161            }
3162        };
3163
3164        private RunningAppProcessInfo(Parcel source) {
3165            readFromParcel(source);
3166        }
3167    }
3168
3169    /**
3170     * Returns a list of application processes installed on external media
3171     * that are running on the device.
3172     *
3173     * <p><b>Note: this method is only intended for debugging or building
3174     * a user-facing process management UI.</b></p>
3175     *
3176     * @return Returns a list of ApplicationInfo records, or null if none
3177     * This list ordering is not specified.
3178     * @hide
3179     */
3180    public List<ApplicationInfo> getRunningExternalApplications() {
3181        try {
3182            return getService().getRunningExternalApplications();
3183        } catch (RemoteException e) {
3184            throw e.rethrowFromSystemServer();
3185        }
3186    }
3187
3188    /**
3189     * Sets the memory trim mode for a process and schedules a memory trim operation.
3190     *
3191     * <p><b>Note: this method is only intended for testing framework.</b></p>
3192     *
3193     * @return Returns true if successful.
3194     * @hide
3195     */
3196    public boolean setProcessMemoryTrimLevel(String process, int userId, int level) {
3197        try {
3198            return getService().setProcessMemoryTrimLevel(process, userId,
3199                    level);
3200        } catch (RemoteException e) {
3201            throw e.rethrowFromSystemServer();
3202        }
3203    }
3204
3205    /**
3206     * Returns a list of application processes that are running on the device.
3207     *
3208     * <p><b>Note: this method is only intended for debugging or building
3209     * a user-facing process management UI.</b></p>
3210     *
3211     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
3212     * running processes (it will not return an empty list).  This list ordering is not
3213     * specified.
3214     */
3215    public List<RunningAppProcessInfo> getRunningAppProcesses() {
3216        try {
3217            return getService().getRunningAppProcesses();
3218        } catch (RemoteException e) {
3219            throw e.rethrowFromSystemServer();
3220        }
3221    }
3222
3223    /**
3224     * Return the importance of a given package name, based on the processes that are
3225     * currently running.  The return value is one of the importance constants defined
3226     * in {@link RunningAppProcessInfo}, giving you the highest importance of all the
3227     * processes that this package has code running inside of.  If there are no processes
3228     * running its code, {@link RunningAppProcessInfo#IMPORTANCE_GONE} is returned.
3229     * @hide
3230     */
3231    @SystemApi @TestApi
3232    @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3233    public @RunningAppProcessInfo.Importance int getPackageImportance(String packageName) {
3234        try {
3235            int procState = getService().getPackageProcessState(packageName,
3236                    mContext.getOpPackageName());
3237            return RunningAppProcessInfo.procStateToImportanceForClient(procState, mContext);
3238        } catch (RemoteException e) {
3239            throw e.rethrowFromSystemServer();
3240        }
3241    }
3242
3243    /**
3244     * Return the importance of a given uid, based on the processes that are
3245     * currently running.  The return value is one of the importance constants defined
3246     * in {@link RunningAppProcessInfo}, giving you the highest importance of all the
3247     * processes that this uid has running.  If there are no processes
3248     * running its code, {@link RunningAppProcessInfo#IMPORTANCE_GONE} is returned.
3249     * @hide
3250     */
3251    @SystemApi @TestApi
3252    @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3253    public @RunningAppProcessInfo.Importance int getUidImportance(int uid) {
3254        try {
3255            int procState = getService().getUidProcessState(uid,
3256                    mContext.getOpPackageName());
3257            return RunningAppProcessInfo.procStateToImportanceForClient(procState, mContext);
3258        } catch (RemoteException e) {
3259            throw e.rethrowFromSystemServer();
3260        }
3261    }
3262
3263    /**
3264     * Callback to get reports about changes to the importance of a uid.  Use with
3265     * {@link #addOnUidImportanceListener}.
3266     * @hide
3267     */
3268    @SystemApi @TestApi
3269    public interface OnUidImportanceListener {
3270        /**
3271         * The importance if a given uid has changed.  Will be one of the importance
3272         * values in {@link RunningAppProcessInfo};
3273         * {@link RunningAppProcessInfo#IMPORTANCE_GONE IMPORTANCE_GONE} will be reported
3274         * when the uid is no longer running at all.  This callback will happen on a thread
3275         * from a thread pool, not the main UI thread.
3276         * @param uid The uid whose importance has changed.
3277         * @param importance The new importance value as per {@link RunningAppProcessInfo}.
3278         */
3279        void onUidImportance(int uid, @RunningAppProcessInfo.Importance int importance);
3280    }
3281
3282    /**
3283     * Start monitoring changes to the imoportance of uids running in the system.
3284     * @param listener The listener callback that will receive change reports.
3285     * @param importanceCutpoint The level of importance in which the caller is interested
3286     * in differences.  For example, if {@link RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE}
3287     * is used here, you will receive a call each time a uids importance transitions between
3288     * being <= {@link RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE} and
3289     * > {@link RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE}.
3290     *
3291     * <p>The caller must hold the {@link android.Manifest.permission#PACKAGE_USAGE_STATS}
3292     * permission to use this feature.</p>
3293     *
3294     * @throws IllegalArgumentException If the listener is already registered.
3295     * @throws SecurityException If the caller does not hold
3296     * {@link android.Manifest.permission#PACKAGE_USAGE_STATS}.
3297     * @hide
3298     */
3299    @SystemApi @TestApi
3300    @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3301    public void addOnUidImportanceListener(OnUidImportanceListener listener,
3302            @RunningAppProcessInfo.Importance int importanceCutpoint) {
3303        synchronized (this) {
3304            if (mImportanceListeners.containsKey(listener)) {
3305                throw new IllegalArgumentException("Listener already registered: " + listener);
3306            }
3307            // TODO: implement the cut point in the system process to avoid IPCs.
3308            UidObserver observer = new UidObserver(listener, mContext);
3309            try {
3310                getService().registerUidObserver(observer,
3311                        UID_OBSERVER_PROCSTATE | UID_OBSERVER_GONE,
3312                        RunningAppProcessInfo.importanceToProcState(importanceCutpoint),
3313                        mContext.getOpPackageName());
3314            } catch (RemoteException e) {
3315                throw e.rethrowFromSystemServer();
3316            }
3317            mImportanceListeners.put(listener, observer);
3318        }
3319    }
3320
3321    /**
3322     * Remove an importance listener that was previously registered with
3323     * {@link #addOnUidImportanceListener}.
3324     *
3325     * @throws IllegalArgumentException If the listener is not registered.
3326     * @hide
3327     */
3328    @SystemApi @TestApi
3329    @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3330    public void removeOnUidImportanceListener(OnUidImportanceListener listener) {
3331        synchronized (this) {
3332            UidObserver observer = mImportanceListeners.remove(listener);
3333            if (observer == null) {
3334                throw new IllegalArgumentException("Listener not registered: " + listener);
3335            }
3336            try {
3337                getService().unregisterUidObserver(observer);
3338            } catch (RemoteException e) {
3339                throw e.rethrowFromSystemServer();
3340            }
3341        }
3342    }
3343
3344    /**
3345     * Return global memory state information for the calling process.  This
3346     * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
3347     * only fields that will be filled in are
3348     * {@link RunningAppProcessInfo#pid},
3349     * {@link RunningAppProcessInfo#uid},
3350     * {@link RunningAppProcessInfo#lastTrimLevel},
3351     * {@link RunningAppProcessInfo#importance},
3352     * {@link RunningAppProcessInfo#lru}, and
3353     * {@link RunningAppProcessInfo#importanceReasonCode}.
3354     */
3355    static public void getMyMemoryState(RunningAppProcessInfo outState) {
3356        try {
3357            getService().getMyMemoryState(outState);
3358        } catch (RemoteException e) {
3359            throw e.rethrowFromSystemServer();
3360        }
3361    }
3362
3363    /**
3364     * Return information about the memory usage of one or more processes.
3365     *
3366     * <p><b>Note: this method is only intended for debugging or building
3367     * a user-facing process management UI.</b></p>
3368     *
3369     * @param pids The pids of the processes whose memory usage is to be
3370     * retrieved.
3371     * @return Returns an array of memory information, one for each
3372     * requested pid.
3373     */
3374    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
3375        try {
3376            return getService().getProcessMemoryInfo(pids);
3377        } catch (RemoteException e) {
3378            throw e.rethrowFromSystemServer();
3379        }
3380    }
3381
3382    /**
3383     * @deprecated This is now just a wrapper for
3384     * {@link #killBackgroundProcesses(String)}; the previous behavior here
3385     * is no longer available to applications because it allows them to
3386     * break other applications by removing their alarms, stopping their
3387     * services, etc.
3388     */
3389    @Deprecated
3390    public void restartPackage(String packageName) {
3391        killBackgroundProcesses(packageName);
3392    }
3393
3394    /**
3395     * Have the system immediately kill all background processes associated
3396     * with the given package.  This is the same as the kernel killing those
3397     * processes to reclaim memory; the system will take care of restarting
3398     * these processes in the future as needed.
3399     *
3400     * @param packageName The name of the package whose processes are to
3401     * be killed.
3402     */
3403    @RequiresPermission(Manifest.permission.KILL_BACKGROUND_PROCESSES)
3404    public void killBackgroundProcesses(String packageName) {
3405        try {
3406            getService().killBackgroundProcesses(packageName,
3407                    UserHandle.myUserId());
3408        } catch (RemoteException e) {
3409            throw e.rethrowFromSystemServer();
3410        }
3411    }
3412
3413    /**
3414     * Kills the specified UID.
3415     * @param uid The UID to kill.
3416     * @param reason The reason for the kill.
3417     *
3418     * @hide
3419     */
3420    @SystemApi
3421    @RequiresPermission(Manifest.permission.KILL_UID)
3422    public void killUid(int uid, String reason) {
3423        try {
3424            getService().killUid(UserHandle.getAppId(uid),
3425                    UserHandle.getUserId(uid), reason);
3426        } catch (RemoteException e) {
3427            throw e.rethrowFromSystemServer();
3428        }
3429    }
3430
3431    /**
3432     * Have the system perform a force stop of everything associated with
3433     * the given application package.  All processes that share its uid
3434     * will be killed, all services it has running stopped, all activities
3435     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
3436     * broadcast will be sent, so that any of its registered alarms can
3437     * be stopped, notifications removed, etc.
3438     *
3439     * <p>You must hold the permission
3440     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
3441     * call this method.
3442     *
3443     * @param packageName The name of the package to be stopped.
3444     * @param userId The user for which the running package is to be stopped.
3445     *
3446     * @hide This is not available to third party applications due to
3447     * it allowing them to break other applications by stopping their
3448     * services, removing their alarms, etc.
3449     */
3450    public void forceStopPackageAsUser(String packageName, int userId) {
3451        try {
3452            getService().forceStopPackage(packageName, userId);
3453        } catch (RemoteException e) {
3454            throw e.rethrowFromSystemServer();
3455        }
3456    }
3457
3458    /**
3459     * @see #forceStopPackageAsUser(String, int)
3460     * @hide
3461     */
3462    @SystemApi
3463    @RequiresPermission(Manifest.permission.FORCE_STOP_PACKAGES)
3464    public void forceStopPackage(String packageName) {
3465        forceStopPackageAsUser(packageName, UserHandle.myUserId());
3466    }
3467
3468    /**
3469     * Get the device configuration attributes.
3470     */
3471    public ConfigurationInfo getDeviceConfigurationInfo() {
3472        try {
3473            return getService().getDeviceConfigurationInfo();
3474        } catch (RemoteException e) {
3475            throw e.rethrowFromSystemServer();
3476        }
3477    }
3478
3479    /**
3480     * Get the preferred density of icons for the launcher. This is used when
3481     * custom drawables are created (e.g., for shortcuts).
3482     *
3483     * @return density in terms of DPI
3484     */
3485    public int getLauncherLargeIconDensity() {
3486        final Resources res = mContext.getResources();
3487        final int density = res.getDisplayMetrics().densityDpi;
3488        final int sw = res.getConfiguration().smallestScreenWidthDp;
3489
3490        if (sw < 600) {
3491            // Smaller than approx 7" tablets, use the regular icon size.
3492            return density;
3493        }
3494
3495        switch (density) {
3496            case DisplayMetrics.DENSITY_LOW:
3497                return DisplayMetrics.DENSITY_MEDIUM;
3498            case DisplayMetrics.DENSITY_MEDIUM:
3499                return DisplayMetrics.DENSITY_HIGH;
3500            case DisplayMetrics.DENSITY_TV:
3501                return DisplayMetrics.DENSITY_XHIGH;
3502            case DisplayMetrics.DENSITY_HIGH:
3503                return DisplayMetrics.DENSITY_XHIGH;
3504            case DisplayMetrics.DENSITY_XHIGH:
3505                return DisplayMetrics.DENSITY_XXHIGH;
3506            case DisplayMetrics.DENSITY_XXHIGH:
3507                return DisplayMetrics.DENSITY_XHIGH * 2;
3508            default:
3509                // The density is some abnormal value.  Return some other
3510                // abnormal value that is a reasonable scaling of it.
3511                return (int)((density*1.5f)+.5f);
3512        }
3513    }
3514
3515    /**
3516     * Get the preferred launcher icon size. This is used when custom drawables
3517     * are created (e.g., for shortcuts).
3518     *
3519     * @return dimensions of square icons in terms of pixels
3520     */
3521    public int getLauncherLargeIconSize() {
3522        return getLauncherLargeIconSizeInner(mContext);
3523    }
3524
3525    static int getLauncherLargeIconSizeInner(Context context) {
3526        final Resources res = context.getResources();
3527        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
3528        final int sw = res.getConfiguration().smallestScreenWidthDp;
3529
3530        if (sw < 600) {
3531            // Smaller than approx 7" tablets, use the regular icon size.
3532            return size;
3533        }
3534
3535        final int density = res.getDisplayMetrics().densityDpi;
3536
3537        switch (density) {
3538            case DisplayMetrics.DENSITY_LOW:
3539                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
3540            case DisplayMetrics.DENSITY_MEDIUM:
3541                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
3542            case DisplayMetrics.DENSITY_TV:
3543                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
3544            case DisplayMetrics.DENSITY_HIGH:
3545                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
3546            case DisplayMetrics.DENSITY_XHIGH:
3547                return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
3548            case DisplayMetrics.DENSITY_XXHIGH:
3549                return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
3550            default:
3551                // The density is some abnormal value.  Return some other
3552                // abnormal value that is a reasonable scaling of it.
3553                return (int)((size*1.5f) + .5f);
3554        }
3555    }
3556
3557    /**
3558     * Returns "true" if the user interface is currently being messed with
3559     * by a monkey.
3560     */
3561    public static boolean isUserAMonkey() {
3562        try {
3563            return getService().isUserAMonkey();
3564        } catch (RemoteException e) {
3565            throw e.rethrowFromSystemServer();
3566        }
3567    }
3568
3569    /**
3570     * Returns "true" if device is running in a test harness.
3571     */
3572    public static boolean isRunningInTestHarness() {
3573        return SystemProperties.getBoolean("ro.test_harness", false);
3574    }
3575
3576    /**
3577     * Returns the launch count of each installed package.
3578     *
3579     * @hide
3580     */
3581    /*public Map<String, Integer> getAllPackageLaunchCounts() {
3582        try {
3583            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
3584                    ServiceManager.getService("usagestats"));
3585            if (usageStatsService == null) {
3586                return new HashMap<String, Integer>();
3587            }
3588
3589            UsageStats.PackageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats(
3590                    ActivityThread.currentPackageName());
3591            if (allPkgUsageStats == null) {
3592                return new HashMap<String, Integer>();
3593            }
3594
3595            Map<String, Integer> launchCounts = new HashMap<String, Integer>();
3596            for (UsageStats.PackageStats pkgUsageStats : allPkgUsageStats) {
3597                launchCounts.put(pkgUsageStats.getPackageName(), pkgUsageStats.getLaunchCount());
3598            }
3599
3600            return launchCounts;
3601        } catch (RemoteException e) {
3602            Log.w(TAG, "Could not query launch counts", e);
3603            return new HashMap<String, Integer>();
3604        }
3605    }*/
3606
3607    /** @hide */
3608    public static int checkComponentPermission(String permission, int uid,
3609            int owningUid, boolean exported) {
3610        // Root, system server get to do everything.
3611        final int appId = UserHandle.getAppId(uid);
3612        if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
3613            return PackageManager.PERMISSION_GRANTED;
3614        }
3615        // Isolated processes don't get any permissions.
3616        if (UserHandle.isIsolated(uid)) {
3617            return PackageManager.PERMISSION_DENIED;
3618        }
3619        // If there is a uid that owns whatever is being accessed, it has
3620        // blanket access to it regardless of the permissions it requires.
3621        if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
3622            return PackageManager.PERMISSION_GRANTED;
3623        }
3624        // If the target is not exported, then nobody else can get to it.
3625        if (!exported) {
3626            /*
3627            RuntimeException here = new RuntimeException("here");
3628            here.fillInStackTrace();
3629            Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
3630                    here);
3631            */
3632            return PackageManager.PERMISSION_DENIED;
3633        }
3634        if (permission == null) {
3635            return PackageManager.PERMISSION_GRANTED;
3636        }
3637        try {
3638            return AppGlobals.getPackageManager()
3639                    .checkUidPermission(permission, uid);
3640        } catch (RemoteException e) {
3641            throw e.rethrowFromSystemServer();
3642        }
3643    }
3644
3645    /** @hide */
3646    public static int checkUidPermission(String permission, int uid) {
3647        try {
3648            return AppGlobals.getPackageManager()
3649                    .checkUidPermission(permission, uid);
3650        } catch (RemoteException e) {
3651            throw e.rethrowFromSystemServer();
3652        }
3653    }
3654
3655    /**
3656     * @hide
3657     * Helper for dealing with incoming user arguments to system service calls.
3658     * Takes care of checking permissions and converting USER_CURRENT to the
3659     * actual current user.
3660     *
3661     * @param callingPid The pid of the incoming call, as per Binder.getCallingPid().
3662     * @param callingUid The uid of the incoming call, as per Binder.getCallingUid().
3663     * @param userId The user id argument supplied by the caller -- this is the user
3664     * they want to run as.
3665     * @param allowAll If true, we will allow USER_ALL.  This means you must be prepared
3666     * to get a USER_ALL returned and deal with it correctly.  If false,
3667     * an exception will be thrown if USER_ALL is supplied.
3668     * @param requireFull If true, the caller must hold
3669     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a
3670     * different user than their current process; otherwise they must hold
3671     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
3672     * @param name Optional textual name of the incoming call; only for generating error messages.
3673     * @param callerPackage Optional package name of caller; only for error messages.
3674     *
3675     * @return Returns the user ID that the call should run as.  Will always be a concrete
3676     * user number, unless <var>allowAll</var> is true in which case it could also be
3677     * USER_ALL.
3678     */
3679    public static int handleIncomingUser(int callingPid, int callingUid, int userId,
3680            boolean allowAll, boolean requireFull, String name, String callerPackage) {
3681        if (UserHandle.getUserId(callingUid) == userId) {
3682            return userId;
3683        }
3684        try {
3685            return getService().handleIncomingUser(callingPid,
3686                    callingUid, userId, allowAll, requireFull, name, callerPackage);
3687        } catch (RemoteException e) {
3688            throw e.rethrowFromSystemServer();
3689        }
3690    }
3691
3692    /**
3693     * Gets the userId of the current foreground user. Requires system permissions.
3694     * @hide
3695     */
3696    @SystemApi
3697    @RequiresPermission(anyOf = {
3698            "android.permission.INTERACT_ACROSS_USERS",
3699            "android.permission.INTERACT_ACROSS_USERS_FULL"
3700    })
3701    public static int getCurrentUser() {
3702        UserInfo ui;
3703        try {
3704            ui = getService().getCurrentUser();
3705            return ui != null ? ui.id : 0;
3706        } catch (RemoteException e) {
3707            throw e.rethrowFromSystemServer();
3708        }
3709    }
3710
3711    /**
3712     * @param userid the user's id. Zero indicates the default user.
3713     * @hide
3714     */
3715    public boolean switchUser(int userid) {
3716        try {
3717            return getService().switchUser(userid);
3718        } catch (RemoteException e) {
3719            throw e.rethrowFromSystemServer();
3720        }
3721    }
3722
3723    /**
3724     * Logs out current current foreground user by switching to the system user and stopping the
3725     * user being switched from.
3726     * @hide
3727     */
3728    public static void logoutCurrentUser() {
3729        int currentUser = ActivityManager.getCurrentUser();
3730        if (currentUser != UserHandle.USER_SYSTEM) {
3731            try {
3732                getService().switchUser(UserHandle.USER_SYSTEM);
3733                getService().stopUser(currentUser, /* force= */ false, null);
3734            } catch (RemoteException e) {
3735                e.rethrowFromSystemServer();
3736            }
3737        }
3738    }
3739
3740    /** {@hide} */
3741    public static final int FLAG_OR_STOPPED = 1 << 0;
3742    /** {@hide} */
3743    public static final int FLAG_AND_LOCKED = 1 << 1;
3744    /** {@hide} */
3745    public static final int FLAG_AND_UNLOCKED = 1 << 2;
3746    /** {@hide} */
3747    public static final int FLAG_AND_UNLOCKING_OR_UNLOCKED = 1 << 3;
3748
3749    /**
3750     * Return whether the given user is actively running.  This means that
3751     * the user is in the "started" state, not "stopped" -- it is currently
3752     * allowed to run code through scheduled alarms, receiving broadcasts,
3753     * etc.  A started user may be either the current foreground user or a
3754     * background user; the result here does not distinguish between the two.
3755     * @param userId the user's id. Zero indicates the default user.
3756     * @hide
3757     */
3758    public boolean isUserRunning(int userId) {
3759        try {
3760            return getService().isUserRunning(userId, 0);
3761        } catch (RemoteException e) {
3762            throw e.rethrowFromSystemServer();
3763        }
3764    }
3765
3766    /** {@hide} */
3767    public boolean isVrModePackageEnabled(ComponentName component) {
3768        try {
3769            return getService().isVrModePackageEnabled(component);
3770        } catch (RemoteException e) {
3771            throw e.rethrowFromSystemServer();
3772        }
3773    }
3774
3775    /**
3776     * Perform a system dump of various state associated with the given application
3777     * package name.  This call blocks while the dump is being performed, so should
3778     * not be done on a UI thread.  The data will be written to the given file
3779     * descriptor as text.
3780     * @param fd The file descriptor that the dump should be written to.  The file
3781     * descriptor is <em>not</em> closed by this function; the caller continues to
3782     * own it.
3783     * @param packageName The name of the package that is to be dumped.
3784     */
3785    @RequiresPermission(Manifest.permission.DUMP)
3786    public void dumpPackageState(FileDescriptor fd, String packageName) {
3787        dumpPackageStateStatic(fd, packageName);
3788    }
3789
3790    /**
3791     * @hide
3792     */
3793    public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) {
3794        FileOutputStream fout = new FileOutputStream(fd);
3795        PrintWriter pw = new FastPrintWriter(fout);
3796        dumpService(pw, fd, "package", new String[] { packageName });
3797        pw.println();
3798        dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] {
3799                "-a", "package", packageName });
3800        pw.println();
3801        dumpService(pw, fd, "meminfo", new String[] { "--local", "--package", packageName });
3802        pw.println();
3803        dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { packageName });
3804        pw.println();
3805        dumpService(pw, fd, "usagestats", new String[] { "--packages", packageName });
3806        pw.println();
3807        dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName });
3808        pw.flush();
3809    }
3810
3811    /**
3812     * @hide
3813     */
3814    public static boolean isSystemReady() {
3815        if (!sSystemReady) {
3816            if (ActivityThread.isSystem()) {
3817                sSystemReady =
3818                        LocalServices.getService(ActivityManagerInternal.class).isSystemReady();
3819            } else {
3820                // Since this is being called from outside system server, system should be
3821                // ready by now.
3822                sSystemReady = true;
3823            }
3824        }
3825        return sSystemReady;
3826    }
3827
3828    /**
3829     * @hide
3830     */
3831    public static void broadcastStickyIntent(Intent intent, int userId) {
3832        broadcastStickyIntent(intent, AppOpsManager.OP_NONE, userId);
3833    }
3834
3835    /**
3836     * Convenience for sending a sticky broadcast.  For internal use only.
3837     *
3838     * @hide
3839     */
3840    public static void broadcastStickyIntent(Intent intent, int appOp, int userId) {
3841        try {
3842            getService().broadcastIntent(
3843                    null, intent, null, null, Activity.RESULT_OK, null, null,
3844                    null /*permission*/, appOp, null, false, true, userId);
3845        } catch (RemoteException ex) {
3846        }
3847    }
3848
3849    /**
3850     * @hide
3851     */
3852    public static void noteWakeupAlarm(PendingIntent ps, int sourceUid, String sourcePkg,
3853            String tag) {
3854        try {
3855            getService().noteWakeupAlarm((ps != null) ? ps.getTarget() : null,
3856                    sourceUid, sourcePkg, tag);
3857        } catch (RemoteException ex) {
3858        }
3859    }
3860
3861    /**
3862     * @hide
3863     */
3864    public static void noteAlarmStart(PendingIntent ps, int sourceUid, String tag) {
3865        try {
3866            getService().noteAlarmStart((ps != null) ? ps.getTarget() : null, sourceUid, tag);
3867        } catch (RemoteException ex) {
3868        }
3869    }
3870
3871    /**
3872     * @hide
3873     */
3874    public static void noteAlarmFinish(PendingIntent ps, int sourceUid, String tag) {
3875        try {
3876            getService().noteAlarmFinish((ps != null) ? ps.getTarget() : null, sourceUid, tag);
3877        } catch (RemoteException ex) {
3878        }
3879    }
3880
3881    /**
3882     * @hide
3883     */
3884    public static IActivityManager getService() {
3885        return IActivityManagerSingleton.get();
3886    }
3887
3888    private static final Singleton<IActivityManager> IActivityManagerSingleton =
3889            new Singleton<IActivityManager>() {
3890                @Override
3891                protected IActivityManager create() {
3892                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
3893                    final IActivityManager am = IActivityManager.Stub.asInterface(b);
3894                    return am;
3895                }
3896            };
3897
3898    private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) {
3899        pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
3900        IBinder service = ServiceManager.checkService(name);
3901        if (service == null) {
3902            pw.println("  (Service not found)");
3903            pw.flush();
3904            return;
3905        }
3906        pw.flush();
3907        if (service instanceof Binder) {
3908            // If this is a local object, it doesn't make sense to do an async dump with it,
3909            // just directly dump.
3910            try {
3911                service.dump(fd, args);
3912            } catch (Throwable e) {
3913                pw.println("Failure dumping service:");
3914                e.printStackTrace(pw);
3915                pw.flush();
3916            }
3917        } else {
3918            // Otherwise, it is remote, do the dump asynchronously to avoid blocking.
3919            TransferPipe tp = null;
3920            try {
3921                pw.flush();
3922                tp = new TransferPipe();
3923                tp.setBufferPrefix("  ");
3924                service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args);
3925                tp.go(fd, 10000);
3926            } catch (Throwable e) {
3927                if (tp != null) {
3928                    tp.kill();
3929                }
3930                pw.println("Failure dumping service:");
3931                e.printStackTrace(pw);
3932            }
3933        }
3934    }
3935
3936    /**
3937     * Request that the system start watching for the calling process to exceed a pss
3938     * size as given here.  Once called, the system will look for any occasions where it
3939     * sees the associated process with a larger pss size and, when this happens, automatically
3940     * pull a heap dump from it and allow the user to share the data.  Note that this request
3941     * continues running even if the process is killed and restarted.  To remove the watch,
3942     * use {@link #clearWatchHeapLimit()}.
3943     *
3944     * <p>This API only work if the calling process has been marked as
3945     * {@link ApplicationInfo#FLAG_DEBUGGABLE} or this is running on a debuggable
3946     * (userdebug or eng) build.</p>
3947     *
3948     * <p>Callers can optionally implement {@link #ACTION_REPORT_HEAP_LIMIT} to directly
3949     * handle heap limit reports themselves.</p>
3950     *
3951     * @param pssSize The size in bytes to set the limit at.
3952     */
3953    public void setWatchHeapLimit(long pssSize) {
3954        try {
3955            getService().setDumpHeapDebugLimit(null, 0, pssSize,
3956                    mContext.getPackageName());
3957        } catch (RemoteException e) {
3958            throw e.rethrowFromSystemServer();
3959        }
3960    }
3961
3962    /**
3963     * Action an app can implement to handle reports from {@link #setWatchHeapLimit(long)}.
3964     * If your package has an activity handling this action, it will be launched with the
3965     * heap data provided to it the same way as {@link Intent#ACTION_SEND}.  Note that to
3966     * match the activty must support this action and a MIME type of "*&#47;*".
3967     */
3968    public static final String ACTION_REPORT_HEAP_LIMIT = "android.app.action.REPORT_HEAP_LIMIT";
3969
3970    /**
3971     * Clear a heap watch limit previously set by {@link #setWatchHeapLimit(long)}.
3972     */
3973    public void clearWatchHeapLimit() {
3974        try {
3975            getService().setDumpHeapDebugLimit(null, 0, 0, null);
3976        } catch (RemoteException e) {
3977            throw e.rethrowFromSystemServer();
3978        }
3979    }
3980
3981    /**
3982     * Return whether currently in lock task mode.  When in this mode
3983     * no new tasks can be created or switched to.
3984     *
3985     * @see Activity#startLockTask()
3986     *
3987     * @deprecated Use {@link #getLockTaskModeState} instead.
3988     */
3989    @Deprecated
3990    public boolean isInLockTaskMode() {
3991        return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3992    }
3993
3994    /**
3995     * Return the current state of task locking. The three possible outcomes
3996     * are {@link #LOCK_TASK_MODE_NONE}, {@link #LOCK_TASK_MODE_LOCKED}
3997     * and {@link #LOCK_TASK_MODE_PINNED}.
3998     *
3999     * @see Activity#startLockTask()
4000     */
4001    public int getLockTaskModeState() {
4002        try {
4003            return getService().getLockTaskModeState();
4004        } catch (RemoteException e) {
4005            throw e.rethrowFromSystemServer();
4006        }
4007    }
4008
4009    /**
4010     * Enable more aggressive scheduling for latency-sensitive low-runtime VR threads. Only one
4011     * thread can be a VR thread in a process at a time, and that thread may be subject to
4012     * restrictions on the amount of time it can run.
4013     *
4014     * If persistent VR mode is set, whatever thread has been granted aggressive scheduling via this
4015     * method will return to normal operation, and calling this method will do nothing while
4016     * persistent VR mode is enabled.
4017     *
4018     * To reset the VR thread for an application, a tid of 0 can be passed.
4019     *
4020     * @see android.os.Process#myTid()
4021     * @param tid tid of the VR thread
4022     */
4023    public static void setVrThread(int tid) {
4024        try {
4025            getService().setVrThread(tid);
4026        } catch (RemoteException e) {
4027            // pass
4028        }
4029    }
4030
4031    /**
4032     * Enable more aggressive scheduling for latency-sensitive low-runtime VR threads that persist
4033     * beyond a single process. Only one thread can be a
4034     * persistent VR thread at a time, and that thread may be subject to restrictions on the amount
4035     * of time it can run. Calling this method will disable aggressive scheduling for non-persistent
4036     * VR threads set via {@link #setVrThread}. If persistent VR mode is disabled then the
4037     * persistent VR thread loses its new scheduling priority; this method must be called again to
4038     * set the persistent thread.
4039     *
4040     * To reset the persistent VR thread, a tid of 0 can be passed.
4041     *
4042     * @see android.os.Process#myTid()
4043     * @param tid tid of the VR thread
4044     * @hide
4045     */
4046    @RequiresPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
4047    public static void setPersistentVrThread(int tid) {
4048        try {
4049            getService().setPersistentVrThread(tid);
4050        } catch (RemoteException e) {
4051            // pass
4052        }
4053    }
4054
4055    /**
4056     * The AppTask allows you to manage your own application's tasks.
4057     * See {@link android.app.ActivityManager#getAppTasks()}
4058     */
4059    public static class AppTask {
4060        private IAppTask mAppTaskImpl;
4061
4062        /** @hide */
4063        public AppTask(IAppTask task) {
4064            mAppTaskImpl = task;
4065        }
4066
4067        /**
4068         * Finishes all activities in this task and removes it from the recent tasks list.
4069         */
4070        public void finishAndRemoveTask() {
4071            try {
4072                mAppTaskImpl.finishAndRemoveTask();
4073            } catch (RemoteException e) {
4074                throw e.rethrowFromSystemServer();
4075            }
4076        }
4077
4078        /**
4079         * Get the RecentTaskInfo associated with this task.
4080         *
4081         * @return The RecentTaskInfo for this task, or null if the task no longer exists.
4082         */
4083        public RecentTaskInfo getTaskInfo() {
4084            try {
4085                return mAppTaskImpl.getTaskInfo();
4086            } catch (RemoteException e) {
4087                throw e.rethrowFromSystemServer();
4088            }
4089        }
4090
4091        /**
4092         * Bring this task to the foreground.  If it contains activities, they will be
4093         * brought to the foreground with it and their instances re-created if needed.
4094         * If it doesn't contain activities, the root activity of the task will be
4095         * re-launched.
4096         */
4097        public void moveToFront() {
4098            try {
4099                mAppTaskImpl.moveToFront();
4100            } catch (RemoteException e) {
4101                throw e.rethrowFromSystemServer();
4102            }
4103        }
4104
4105        /**
4106         * Start an activity in this task.  Brings the task to the foreground.  If this task
4107         * is not currently active (that is, its id < 0), then a new activity for the given
4108         * Intent will be launched as the root of the task and the task brought to the
4109         * foreground.  Otherwise, if this task is currently active and the Intent does not specify
4110         * an activity to launch in a new task, then a new activity for the given Intent will
4111         * be launched on top of the task and the task brought to the foreground.  If this
4112         * task is currently active and the Intent specifies {@link Intent#FLAG_ACTIVITY_NEW_TASK}
4113         * or would otherwise be launched in to a new task, then the activity not launched but
4114         * this task be brought to the foreground and a new intent delivered to the top
4115         * activity if appropriate.
4116         *
4117         * <p>In other words, you generally want to use an Intent here that does not specify
4118         * {@link Intent#FLAG_ACTIVITY_NEW_TASK} or {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT},
4119         * and let the system do the right thing.</p>
4120         *
4121         * @param intent The Intent describing the new activity to be launched on the task.
4122         * @param options Optional launch options.
4123         *
4124         * @see Activity#startActivity(android.content.Intent, android.os.Bundle)
4125         */
4126        public void startActivity(Context context, Intent intent, Bundle options) {
4127            ActivityThread thread = ActivityThread.currentActivityThread();
4128            thread.getInstrumentation().execStartActivityFromAppTask(context,
4129                    thread.getApplicationThread(), mAppTaskImpl, intent, options);
4130        }
4131
4132        /**
4133         * Modify the {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag in the root
4134         * Intent of this AppTask.
4135         *
4136         * @param exclude If true, {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} will
4137         * be set; otherwise, it will be cleared.
4138         */
4139        public void setExcludeFromRecents(boolean exclude) {
4140            try {
4141                mAppTaskImpl.setExcludeFromRecents(exclude);
4142            } catch (RemoteException e) {
4143                throw e.rethrowFromSystemServer();
4144            }
4145        }
4146    }
4147}
4148