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