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