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