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