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