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