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