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