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