ActivityManager.java revision 3797c22ea16e932329ebffdc7e7ce09f9ecd9545
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        public RecentTaskInfo() {
1071        }
1072
1073        @Override
1074        public int describeContents() {
1075            return 0;
1076        }
1077
1078        @Override
1079        public void writeToParcel(Parcel dest, int flags) {
1080            dest.writeInt(id);
1081            dest.writeInt(persistentId);
1082            if (baseIntent != null) {
1083                dest.writeInt(1);
1084                baseIntent.writeToParcel(dest, 0);
1085            } else {
1086                dest.writeInt(0);
1087            }
1088            ComponentName.writeToParcel(origActivity, dest);
1089            ComponentName.writeToParcel(realActivity, dest);
1090            TextUtils.writeToParcel(description, dest,
1091                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1092            if (taskDescription != null) {
1093                dest.writeInt(1);
1094                taskDescription.writeToParcel(dest, 0);
1095            } else {
1096                dest.writeInt(0);
1097            }
1098            dest.writeInt(stackId);
1099            dest.writeInt(userId);
1100            dest.writeLong(firstActiveTime);
1101            dest.writeLong(lastActiveTime);
1102            dest.writeInt(affiliatedTaskId);
1103            dest.writeInt(affiliatedTaskColor);
1104            ComponentName.writeToParcel(baseActivity, dest);
1105            ComponentName.writeToParcel(topActivity, dest);
1106            dest.writeInt(numActivities);
1107        }
1108
1109        public void readFromParcel(Parcel source) {
1110            id = source.readInt();
1111            persistentId = source.readInt();
1112            baseIntent = source.readInt() > 0 ? Intent.CREATOR.createFromParcel(source) : null;
1113            origActivity = ComponentName.readFromParcel(source);
1114            realActivity = ComponentName.readFromParcel(source);
1115            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
1116            taskDescription = source.readInt() > 0 ?
1117                    TaskDescription.CREATOR.createFromParcel(source) : null;
1118            stackId = source.readInt();
1119            userId = source.readInt();
1120            firstActiveTime = source.readLong();
1121            lastActiveTime = source.readLong();
1122            affiliatedTaskId = source.readInt();
1123            affiliatedTaskColor = source.readInt();
1124            baseActivity = ComponentName.readFromParcel(source);
1125            topActivity = ComponentName.readFromParcel(source);
1126            numActivities = source.readInt();
1127        }
1128
1129        public static final Creator<RecentTaskInfo> CREATOR
1130                = new Creator<RecentTaskInfo>() {
1131            public RecentTaskInfo createFromParcel(Parcel source) {
1132                return new RecentTaskInfo(source);
1133            }
1134            public RecentTaskInfo[] newArray(int size) {
1135                return new RecentTaskInfo[size];
1136            }
1137        };
1138
1139        private RecentTaskInfo(Parcel source) {
1140            readFromParcel(source);
1141        }
1142    }
1143
1144    /**
1145     * Flag for use with {@link #getRecentTasks}: return all tasks, even those
1146     * that have set their
1147     * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
1148     */
1149    public static final int RECENT_WITH_EXCLUDED = 0x0001;
1150
1151    /**
1152     * Provides a list that does not contain any
1153     * recent tasks that currently are not available to the user.
1154     */
1155    public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002;
1156
1157    /**
1158     * Provides a list that contains recent tasks for all
1159     * profiles of a user.
1160     * @hide
1161     */
1162    public static final int RECENT_INCLUDE_PROFILES = 0x0004;
1163
1164    /**
1165     * Ignores all tasks that are on the home stack.
1166     * @hide
1167     */
1168    public static final int RECENT_IGNORE_HOME_STACK_TASKS = 0x0008;
1169
1170    /**
1171     * <p></p>Return a list of the tasks that the user has recently launched, with
1172     * the most recent being first and older ones after in order.
1173     *
1174     * <p><b>Note: this method is only intended for debugging and presenting
1175     * task management user interfaces</b>.  This should never be used for
1176     * core logic in an application, such as deciding between different
1177     * behaviors based on the information found here.  Such uses are
1178     * <em>not</em> supported, and will likely break in the future.  For
1179     * example, if multiple applications can be actively running at the
1180     * same time, assumptions made about the meaning of the data here for
1181     * purposes of control flow will be incorrect.</p>
1182     *
1183     * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method is
1184     * no longer available to third party applications: the introduction of
1185     * document-centric recents means
1186     * it can leak personal information to the caller.  For backwards compatibility,
1187     * it will still return a small subset of its data: at least the caller's
1188     * own tasks (though see {@link #getAppTasks()} for the correct supported
1189     * way to retrieve that information), and possibly some other tasks
1190     * such as home that are known to not be sensitive.
1191     *
1192     * @param maxNum The maximum number of entries to return in the list.  The
1193     * actual number returned may be smaller, depending on how many tasks the
1194     * user has started and the maximum number the system can remember.
1195     * @param flags Information about what to return.  May be any combination
1196     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
1197     *
1198     * @return Returns a list of RecentTaskInfo records describing each of
1199     * the recent tasks.
1200     */
1201    @Deprecated
1202    public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags)
1203            throws SecurityException {
1204        try {
1205            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
1206                    flags, UserHandle.myUserId());
1207        } catch (RemoteException e) {
1208            // System dead, we will be dead too soon!
1209            return null;
1210        }
1211    }
1212
1213    /**
1214     * Same as {@link #getRecentTasks(int, int)} but returns the recent tasks for a
1215     * specific user. It requires holding
1216     * the {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
1217     * @param maxNum The maximum number of entries to return in the list.  The
1218     * actual number returned may be smaller, depending on how many tasks the
1219     * user has started and the maximum number the system can remember.
1220     * @param flags Information about what to return.  May be any combination
1221     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
1222     *
1223     * @return Returns a list of RecentTaskInfo records describing each of
1224     * the recent tasks. Most recently activated tasks go first.
1225     *
1226     * @hide
1227     */
1228    public List<RecentTaskInfo> getRecentTasksForUser(int maxNum, int flags, int userId)
1229            throws SecurityException {
1230        try {
1231            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
1232                    flags, userId);
1233        } catch (RemoteException e) {
1234            // System dead, we will be dead too soon!
1235            return null;
1236        }
1237    }
1238
1239    /**
1240     * Information you can retrieve about a particular task that is currently
1241     * "running" in the system.  Note that a running task does not mean the
1242     * given task actually has a process it is actively running in; it simply
1243     * means that the user has gone to it and never closed it, but currently
1244     * the system may have killed its process and is only holding on to its
1245     * last state in order to restart it when the user returns.
1246     */
1247    public static class RunningTaskInfo implements Parcelable {
1248        /**
1249         * A unique identifier for this task.
1250         */
1251        public int id;
1252
1253        /**
1254         * The stack that currently contains this task.
1255         * @hide
1256         */
1257        public int stackId;
1258
1259        /**
1260         * The component launched as the first activity in the task.  This can
1261         * be considered the "application" of this task.
1262         */
1263        public ComponentName baseActivity;
1264
1265        /**
1266         * The activity component at the top of the history stack of the task.
1267         * This is what the user is currently doing.
1268         */
1269        public ComponentName topActivity;
1270
1271        /**
1272         * Thumbnail representation of the task's current state.  Currently
1273         * always null.
1274         */
1275        public Bitmap thumbnail;
1276
1277        /**
1278         * Description of the task's current state.
1279         */
1280        public CharSequence description;
1281
1282        /**
1283         * Number of activities in this task.
1284         */
1285        public int numActivities;
1286
1287        /**
1288         * Number of activities that are currently running (not stopped
1289         * and persisted) in this task.
1290         */
1291        public int numRunning;
1292
1293        /**
1294         * Last time task was run. For sorting.
1295         * @hide
1296         */
1297        public long lastActiveTime;
1298
1299        public RunningTaskInfo() {
1300        }
1301
1302        public int describeContents() {
1303            return 0;
1304        }
1305
1306        public void writeToParcel(Parcel dest, int flags) {
1307            dest.writeInt(id);
1308            dest.writeInt(stackId);
1309            ComponentName.writeToParcel(baseActivity, dest);
1310            ComponentName.writeToParcel(topActivity, dest);
1311            if (thumbnail != null) {
1312                dest.writeInt(1);
1313                thumbnail.writeToParcel(dest, 0);
1314            } else {
1315                dest.writeInt(0);
1316            }
1317            TextUtils.writeToParcel(description, dest,
1318                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1319            dest.writeInt(numActivities);
1320            dest.writeInt(numRunning);
1321        }
1322
1323        public void readFromParcel(Parcel source) {
1324            id = source.readInt();
1325            stackId = source.readInt();
1326            baseActivity = ComponentName.readFromParcel(source);
1327            topActivity = ComponentName.readFromParcel(source);
1328            if (source.readInt() != 0) {
1329                thumbnail = Bitmap.CREATOR.createFromParcel(source);
1330            } else {
1331                thumbnail = null;
1332            }
1333            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
1334            numActivities = source.readInt();
1335            numRunning = source.readInt();
1336        }
1337
1338        public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
1339            public RunningTaskInfo createFromParcel(Parcel source) {
1340                return new RunningTaskInfo(source);
1341            }
1342            public RunningTaskInfo[] newArray(int size) {
1343                return new RunningTaskInfo[size];
1344            }
1345        };
1346
1347        private RunningTaskInfo(Parcel source) {
1348            readFromParcel(source);
1349        }
1350    }
1351
1352    /**
1353     * Get the list of tasks associated with the calling application.
1354     *
1355     * @return The list of tasks associated with the application making this call.
1356     * @throws SecurityException
1357     */
1358    public List<ActivityManager.AppTask> getAppTasks() {
1359        ArrayList<AppTask> tasks = new ArrayList<AppTask>();
1360        List<IAppTask> appTasks;
1361        try {
1362            appTasks = ActivityManagerNative.getDefault().getAppTasks(mContext.getPackageName());
1363        } catch (RemoteException e) {
1364            // System dead, we will be dead too soon!
1365            return null;
1366        }
1367        int numAppTasks = appTasks.size();
1368        for (int i = 0; i < numAppTasks; i++) {
1369            tasks.add(new AppTask(appTasks.get(i)));
1370        }
1371        return tasks;
1372    }
1373
1374    /**
1375     * Return the current design dimensions for {@link AppTask} thumbnails, for use
1376     * with {@link #addAppTask}.
1377     */
1378    public Size getAppTaskThumbnailSize() {
1379        synchronized (this) {
1380            ensureAppTaskThumbnailSizeLocked();
1381            return new Size(mAppTaskThumbnailSize.x, mAppTaskThumbnailSize.y);
1382        }
1383    }
1384
1385    private void ensureAppTaskThumbnailSizeLocked() {
1386        if (mAppTaskThumbnailSize == null) {
1387            try {
1388                mAppTaskThumbnailSize = ActivityManagerNative.getDefault().getAppTaskThumbnailSize();
1389            } catch (RemoteException e) {
1390                throw new IllegalStateException("System dead?", e);
1391            }
1392        }
1393    }
1394
1395    /**
1396     * Add a new {@link AppTask} for the calling application.  This will create a new
1397     * recents entry that is added to the <b>end</b> of all existing recents.
1398     *
1399     * @param activity The activity that is adding the entry.   This is used to help determine
1400     * the context that the new recents entry will be in.
1401     * @param intent The Intent that describes the recents entry.  This is the same Intent that
1402     * you would have used to launch the activity for it.  In generally you will want to set
1403     * both {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT} and
1404     * {@link Intent#FLAG_ACTIVITY_RETAIN_IN_RECENTS}; the latter is required since this recents
1405     * entry will exist without an activity, so it doesn't make sense to not retain it when
1406     * its activity disappears.  The given Intent here also must have an explicit ComponentName
1407     * set on it.
1408     * @param description Optional additional description information.
1409     * @param thumbnail Thumbnail to use for the recents entry.  Should be the size given by
1410     * {@link #getAppTaskThumbnailSize()}.  If the bitmap is not that exact size, it will be
1411     * recreated in your process, probably in a way you don't like, before the recents entry
1412     * is added.
1413     *
1414     * @return Returns the task id of the newly added app task, or -1 if the add failed.  The
1415     * most likely cause of failure is that there is no more room for more tasks for your app.
1416     */
1417    public int addAppTask(@NonNull Activity activity, @NonNull Intent intent,
1418            @Nullable TaskDescription description, @NonNull Bitmap thumbnail) {
1419        Point size;
1420        synchronized (this) {
1421            ensureAppTaskThumbnailSizeLocked();
1422            size = mAppTaskThumbnailSize;
1423        }
1424        final int tw = thumbnail.getWidth();
1425        final int th = thumbnail.getHeight();
1426        if (tw != size.x || th != size.y) {
1427            Bitmap bm = Bitmap.createBitmap(size.x, size.y, thumbnail.getConfig());
1428
1429            // Use ScaleType.CENTER_CROP, except we leave the top edge at the top.
1430            float scale;
1431            float dx = 0, dy = 0;
1432            if (tw * size.x > size.y * th) {
1433                scale = (float) size.x / (float) th;
1434                dx = (size.y - tw * scale) * 0.5f;
1435            } else {
1436                scale = (float) size.y / (float) tw;
1437                dy = (size.x - th * scale) * 0.5f;
1438            }
1439            Matrix matrix = new Matrix();
1440            matrix.setScale(scale, scale);
1441            matrix.postTranslate((int) (dx + 0.5f), 0);
1442
1443            Canvas canvas = new Canvas(bm);
1444            canvas.drawBitmap(thumbnail, matrix, null);
1445            canvas.setBitmap(null);
1446
1447            thumbnail = bm;
1448        }
1449        if (description == null) {
1450            description = new TaskDescription();
1451        }
1452        try {
1453            return ActivityManagerNative.getDefault().addAppTask(activity.getActivityToken(),
1454                    intent, description, thumbnail);
1455        } catch (RemoteException e) {
1456            throw new IllegalStateException("System dead?", e);
1457        }
1458    }
1459
1460    /**
1461     * Return a list of the tasks that are currently running, with
1462     * the most recent being first and older ones after in order.  Note that
1463     * "running" does not mean any of the task's code is currently loaded or
1464     * activity -- the task may have been frozen by the system, so that it
1465     * can be restarted in its previous state when next brought to the
1466     * foreground.
1467     *
1468     * <p><b>Note: this method is only intended for debugging and presenting
1469     * task management user interfaces</b>.  This should never be used for
1470     * core logic in an application, such as deciding between different
1471     * behaviors based on the information found here.  Such uses are
1472     * <em>not</em> supported, and will likely break in the future.  For
1473     * example, if multiple applications can be actively running at the
1474     * same time, assumptions made about the meaning of the data here for
1475     * purposes of control flow will be incorrect.</p>
1476     *
1477     * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method
1478     * is no longer available to third party
1479     * applications: the introduction of document-centric recents means
1480     * it can leak person information to the caller.  For backwards compatibility,
1481     * it will still retu rn a small subset of its data: at least the caller's
1482     * own tasks, and possibly some other tasks
1483     * such as home that are known to not be sensitive.
1484     *
1485     * @param maxNum The maximum number of entries to return in the list.  The
1486     * actual number returned may be smaller, depending on how many tasks the
1487     * user has started.
1488     *
1489     * @return Returns a list of RunningTaskInfo records describing each of
1490     * the running tasks.
1491     */
1492    @Deprecated
1493    public List<RunningTaskInfo> getRunningTasks(int maxNum)
1494            throws SecurityException {
1495        try {
1496            return ActivityManagerNative.getDefault().getTasks(maxNum, 0);
1497        } catch (RemoteException e) {
1498            // System dead, we will be dead too soon!
1499            return null;
1500        }
1501    }
1502
1503    /**
1504     * Completely remove the given task.
1505     *
1506     * @param taskId Identifier of the task to be removed.
1507     * @return Returns true if the given task was found and removed.
1508     *
1509     * @hide
1510     */
1511    public boolean removeTask(int taskId) throws SecurityException {
1512        try {
1513            return ActivityManagerNative.getDefault().removeTask(taskId);
1514        } catch (RemoteException e) {
1515            // System dead, we will be dead too soon!
1516            return false;
1517        }
1518    }
1519
1520    /** @hide */
1521    public static class TaskThumbnail implements Parcelable {
1522        public Bitmap mainThumbnail;
1523        public ParcelFileDescriptor thumbnailFileDescriptor;
1524
1525        public TaskThumbnail() {
1526        }
1527
1528        public int describeContents() {
1529            if (thumbnailFileDescriptor != null) {
1530                return thumbnailFileDescriptor.describeContents();
1531            }
1532            return 0;
1533        }
1534
1535        public void writeToParcel(Parcel dest, int flags) {
1536            if (mainThumbnail != null) {
1537                dest.writeInt(1);
1538                mainThumbnail.writeToParcel(dest, flags);
1539            } else {
1540                dest.writeInt(0);
1541            }
1542            if (thumbnailFileDescriptor != null) {
1543                dest.writeInt(1);
1544                thumbnailFileDescriptor.writeToParcel(dest, flags);
1545            } else {
1546                dest.writeInt(0);
1547            }
1548        }
1549
1550        public void readFromParcel(Parcel source) {
1551            if (source.readInt() != 0) {
1552                mainThumbnail = Bitmap.CREATOR.createFromParcel(source);
1553            } else {
1554                mainThumbnail = null;
1555            }
1556            if (source.readInt() != 0) {
1557                thumbnailFileDescriptor = ParcelFileDescriptor.CREATOR.createFromParcel(source);
1558            } else {
1559                thumbnailFileDescriptor = null;
1560            }
1561        }
1562
1563        public static final Creator<TaskThumbnail> CREATOR = new Creator<TaskThumbnail>() {
1564            public TaskThumbnail createFromParcel(Parcel source) {
1565                return new TaskThumbnail(source);
1566            }
1567            public TaskThumbnail[] newArray(int size) {
1568                return new TaskThumbnail[size];
1569            }
1570        };
1571
1572        private TaskThumbnail(Parcel source) {
1573            readFromParcel(source);
1574        }
1575    }
1576
1577    /** @hide */
1578    public TaskThumbnail getTaskThumbnail(int id) throws SecurityException {
1579        try {
1580            return ActivityManagerNative.getDefault().getTaskThumbnail(id);
1581        } catch (RemoteException e) {
1582            // System dead, we will be dead too soon!
1583            return null;
1584        }
1585    }
1586
1587    /** @hide */
1588    public boolean isInHomeStack(int taskId) {
1589        try {
1590            return ActivityManagerNative.getDefault().isInHomeStack(taskId);
1591        } catch (RemoteException e) {
1592            // System dead, we will be dead too soon!
1593            return false;
1594        }
1595    }
1596
1597    /**
1598     * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
1599     * activity along with the task, so it is positioned immediately behind
1600     * the task.
1601     */
1602    public static final int MOVE_TASK_WITH_HOME = 0x00000001;
1603
1604    /**
1605     * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
1606     * user-instigated action, so the current activity will not receive a
1607     * hint that the user is leaving.
1608     */
1609    public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
1610
1611    /**
1612     * Equivalent to calling {@link #moveTaskToFront(int, int, Bundle)}
1613     * with a null options argument.
1614     *
1615     * @param taskId The identifier of the task to be moved, as found in
1616     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
1617     * @param flags Additional operational flags, 0 or more of
1618     * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
1619     */
1620    public void moveTaskToFront(int taskId, int flags) {
1621        moveTaskToFront(taskId, flags, null);
1622    }
1623
1624    /**
1625     * Ask that the task associated with a given task ID be moved to the
1626     * front of the stack, so it is now visible to the user.  Requires that
1627     * the caller hold permission {@link android.Manifest.permission#REORDER_TASKS}
1628     * or a SecurityException will be thrown.
1629     *
1630     * @param taskId The identifier of the task to be moved, as found in
1631     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
1632     * @param flags Additional operational flags, 0 or more of
1633     * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
1634     * @param options Additional options for the operation, either null or
1635     * as per {@link Context#startActivity(Intent, android.os.Bundle)
1636     * Context.startActivity(Intent, Bundle)}.
1637     */
1638    public void moveTaskToFront(int taskId, int flags, Bundle options) {
1639        try {
1640            ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags, options);
1641        } catch (RemoteException e) {
1642            // System dead, we will be dead too soon!
1643        }
1644    }
1645
1646    /**
1647     * Information you can retrieve about a particular Service that is
1648     * currently running in the system.
1649     */
1650    public static class RunningServiceInfo implements Parcelable {
1651        /**
1652         * The service component.
1653         */
1654        public ComponentName service;
1655
1656        /**
1657         * If non-zero, this is the process the service is running in.
1658         */
1659        public int pid;
1660
1661        /**
1662         * The UID that owns this service.
1663         */
1664        public int uid;
1665
1666        /**
1667         * The name of the process this service runs in.
1668         */
1669        public String process;
1670
1671        /**
1672         * Set to true if the service has asked to run as a foreground process.
1673         */
1674        public boolean foreground;
1675
1676        /**
1677         * The time when the service was first made active, either by someone
1678         * starting or binding to it.  This
1679         * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
1680         */
1681        public long activeSince;
1682
1683        /**
1684         * Set to true if this service has been explicitly started.
1685         */
1686        public boolean started;
1687
1688        /**
1689         * Number of clients connected to the service.
1690         */
1691        public int clientCount;
1692
1693        /**
1694         * Number of times the service's process has crashed while the service
1695         * is running.
1696         */
1697        public int crashCount;
1698
1699        /**
1700         * The time when there was last activity in the service (either
1701         * explicit requests to start it or clients binding to it).  This
1702         * is in units of {@link android.os.SystemClock#uptimeMillis()}.
1703         */
1704        public long lastActivityTime;
1705
1706        /**
1707         * If non-zero, this service is not currently running, but scheduled to
1708         * restart at the given time.
1709         */
1710        public long restarting;
1711
1712        /**
1713         * Bit for {@link #flags}: set if this service has been
1714         * explicitly started.
1715         */
1716        public static final int FLAG_STARTED = 1<<0;
1717
1718        /**
1719         * Bit for {@link #flags}: set if the service has asked to
1720         * run as a foreground process.
1721         */
1722        public static final int FLAG_FOREGROUND = 1<<1;
1723
1724        /**
1725         * Bit for {@link #flags): set if the service is running in a
1726         * core system process.
1727         */
1728        public static final int FLAG_SYSTEM_PROCESS = 1<<2;
1729
1730        /**
1731         * Bit for {@link #flags): set if the service is running in a
1732         * persistent process.
1733         */
1734        public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
1735
1736        /**
1737         * Running flags.
1738         */
1739        public int flags;
1740
1741        /**
1742         * For special services that are bound to by system code, this is
1743         * the package that holds the binding.
1744         */
1745        public String clientPackage;
1746
1747        /**
1748         * For special services that are bound to by system code, this is
1749         * a string resource providing a user-visible label for who the
1750         * client is.
1751         */
1752        public int clientLabel;
1753
1754        public RunningServiceInfo() {
1755        }
1756
1757        public int describeContents() {
1758            return 0;
1759        }
1760
1761        public void writeToParcel(Parcel dest, int flags) {
1762            ComponentName.writeToParcel(service, dest);
1763            dest.writeInt(pid);
1764            dest.writeInt(uid);
1765            dest.writeString(process);
1766            dest.writeInt(foreground ? 1 : 0);
1767            dest.writeLong(activeSince);
1768            dest.writeInt(started ? 1 : 0);
1769            dest.writeInt(clientCount);
1770            dest.writeInt(crashCount);
1771            dest.writeLong(lastActivityTime);
1772            dest.writeLong(restarting);
1773            dest.writeInt(this.flags);
1774            dest.writeString(clientPackage);
1775            dest.writeInt(clientLabel);
1776        }
1777
1778        public void readFromParcel(Parcel source) {
1779            service = ComponentName.readFromParcel(source);
1780            pid = source.readInt();
1781            uid = source.readInt();
1782            process = source.readString();
1783            foreground = source.readInt() != 0;
1784            activeSince = source.readLong();
1785            started = source.readInt() != 0;
1786            clientCount = source.readInt();
1787            crashCount = source.readInt();
1788            lastActivityTime = source.readLong();
1789            restarting = source.readLong();
1790            flags = source.readInt();
1791            clientPackage = source.readString();
1792            clientLabel = source.readInt();
1793        }
1794
1795        public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
1796            public RunningServiceInfo createFromParcel(Parcel source) {
1797                return new RunningServiceInfo(source);
1798            }
1799            public RunningServiceInfo[] newArray(int size) {
1800                return new RunningServiceInfo[size];
1801            }
1802        };
1803
1804        private RunningServiceInfo(Parcel source) {
1805            readFromParcel(source);
1806        }
1807    }
1808
1809    /**
1810     * Return a list of the services that are currently running.
1811     *
1812     * <p><b>Note: this method is only intended for debugging or implementing
1813     * service management type user interfaces.</b></p>
1814     *
1815     * @param maxNum The maximum number of entries to return in the list.  The
1816     * actual number returned may be smaller, depending on how many services
1817     * are running.
1818     *
1819     * @return Returns a list of RunningServiceInfo records describing each of
1820     * the running tasks.
1821     */
1822    public List<RunningServiceInfo> getRunningServices(int maxNum)
1823            throws SecurityException {
1824        try {
1825            return ActivityManagerNative.getDefault()
1826                    .getServices(maxNum, 0);
1827        } catch (RemoteException e) {
1828            // System dead, we will be dead too soon!
1829            return null;
1830        }
1831    }
1832
1833    /**
1834     * Returns a PendingIntent you can start to show a control panel for the
1835     * given running service.  If the service does not have a control panel,
1836     * null is returned.
1837     */
1838    public PendingIntent getRunningServiceControlPanel(ComponentName service)
1839            throws SecurityException {
1840        try {
1841            return ActivityManagerNative.getDefault()
1842                    .getRunningServiceControlPanel(service);
1843        } catch (RemoteException e) {
1844            // System dead, we will be dead too soon!
1845            return null;
1846        }
1847    }
1848
1849    /**
1850     * Information you can retrieve about the available memory through
1851     * {@link ActivityManager#getMemoryInfo}.
1852     */
1853    public static class MemoryInfo implements Parcelable {
1854        /**
1855         * The available memory on the system.  This number should not
1856         * be considered absolute: due to the nature of the kernel, a significant
1857         * portion of this memory is actually in use and needed for the overall
1858         * system to run well.
1859         */
1860        public long availMem;
1861
1862        /**
1863         * The total memory accessible by the kernel.  This is basically the
1864         * RAM size of the device, not including below-kernel fixed allocations
1865         * like DMA buffers, RAM for the baseband CPU, etc.
1866         */
1867        public long totalMem;
1868
1869        /**
1870         * The threshold of {@link #availMem} at which we consider memory to be
1871         * low and start killing background services and other non-extraneous
1872         * processes.
1873         */
1874        public long threshold;
1875
1876        /**
1877         * Set to true if the system considers itself to currently be in a low
1878         * memory situation.
1879         */
1880        public boolean lowMemory;
1881
1882        /** @hide */
1883        public long hiddenAppThreshold;
1884        /** @hide */
1885        public long secondaryServerThreshold;
1886        /** @hide */
1887        public long visibleAppThreshold;
1888        /** @hide */
1889        public long foregroundAppThreshold;
1890
1891        public MemoryInfo() {
1892        }
1893
1894        public int describeContents() {
1895            return 0;
1896        }
1897
1898        public void writeToParcel(Parcel dest, int flags) {
1899            dest.writeLong(availMem);
1900            dest.writeLong(totalMem);
1901            dest.writeLong(threshold);
1902            dest.writeInt(lowMemory ? 1 : 0);
1903            dest.writeLong(hiddenAppThreshold);
1904            dest.writeLong(secondaryServerThreshold);
1905            dest.writeLong(visibleAppThreshold);
1906            dest.writeLong(foregroundAppThreshold);
1907        }
1908
1909        public void readFromParcel(Parcel source) {
1910            availMem = source.readLong();
1911            totalMem = source.readLong();
1912            threshold = source.readLong();
1913            lowMemory = source.readInt() != 0;
1914            hiddenAppThreshold = source.readLong();
1915            secondaryServerThreshold = source.readLong();
1916            visibleAppThreshold = source.readLong();
1917            foregroundAppThreshold = source.readLong();
1918        }
1919
1920        public static final Creator<MemoryInfo> CREATOR
1921                = new Creator<MemoryInfo>() {
1922            public MemoryInfo createFromParcel(Parcel source) {
1923                return new MemoryInfo(source);
1924            }
1925            public MemoryInfo[] newArray(int size) {
1926                return new MemoryInfo[size];
1927            }
1928        };
1929
1930        private MemoryInfo(Parcel source) {
1931            readFromParcel(source);
1932        }
1933    }
1934
1935    /**
1936     * Return general information about the memory state of the system.  This
1937     * can be used to help decide how to manage your own memory, though note
1938     * that polling is not recommended and
1939     * {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1940     * ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this.
1941     * Also see {@link #getMyMemoryState} for how to retrieve the current trim
1942     * level of your process as needed, which gives a better hint for how to
1943     * manage its memory.
1944     */
1945    public void getMemoryInfo(MemoryInfo outInfo) {
1946        try {
1947            ActivityManagerNative.getDefault().getMemoryInfo(outInfo);
1948        } catch (RemoteException e) {
1949        }
1950    }
1951
1952    /**
1953     * Information you can retrieve about an ActivityStack in the system.
1954     * @hide
1955     */
1956    public static class StackInfo implements Parcelable {
1957        public int stackId;
1958        public Rect bounds = new Rect();
1959        public int[] taskIds;
1960        public String[] taskNames;
1961        public Rect[] taskBounds;
1962        public int displayId;
1963
1964        @Override
1965        public int describeContents() {
1966            return 0;
1967        }
1968
1969        @Override
1970        public void writeToParcel(Parcel dest, int flags) {
1971            dest.writeInt(stackId);
1972            dest.writeInt(bounds.left);
1973            dest.writeInt(bounds.top);
1974            dest.writeInt(bounds.right);
1975            dest.writeInt(bounds.bottom);
1976            dest.writeIntArray(taskIds);
1977            dest.writeStringArray(taskNames);
1978            final int boundsCount = taskBounds == null ? 0 : taskBounds.length;
1979            dest.writeInt(boundsCount);
1980            for (int i = 0; i < boundsCount; i++) {
1981                dest.writeInt(taskBounds[i].left);
1982                dest.writeInt(taskBounds[i].top);
1983                dest.writeInt(taskBounds[i].right);
1984                dest.writeInt(taskBounds[i].bottom);
1985            }
1986            dest.writeInt(displayId);
1987        }
1988
1989        public void readFromParcel(Parcel source) {
1990            stackId = source.readInt();
1991            bounds = new Rect(
1992                    source.readInt(), source.readInt(), source.readInt(), source.readInt());
1993            taskIds = source.createIntArray();
1994            taskNames = source.createStringArray();
1995            final int boundsCount = source.readInt();
1996            if (boundsCount > 0) {
1997                taskBounds = new Rect[boundsCount];
1998                for (int i = 0; i < boundsCount; i++) {
1999                    taskBounds[i] = new Rect();
2000                    taskBounds[i].set(
2001                            source.readInt(), source.readInt(), source.readInt(), source.readInt());
2002                }
2003            } else {
2004                taskBounds = null;
2005            }
2006            displayId = source.readInt();
2007        }
2008
2009        public static final Creator<StackInfo> CREATOR = new Creator<StackInfo>() {
2010            @Override
2011            public StackInfo createFromParcel(Parcel source) {
2012                return new StackInfo(source);
2013            }
2014            @Override
2015            public StackInfo[] newArray(int size) {
2016                return new StackInfo[size];
2017            }
2018        };
2019
2020        public StackInfo() {
2021        }
2022
2023        private StackInfo(Parcel source) {
2024            readFromParcel(source);
2025        }
2026
2027        public String toString(String prefix) {
2028            StringBuilder sb = new StringBuilder(256);
2029            sb.append(prefix); sb.append("Stack id="); sb.append(stackId);
2030                    sb.append(" bounds="); sb.append(bounds.toShortString());
2031                    sb.append(" displayId="); sb.append(displayId);
2032                    sb.append("\n");
2033            prefix = prefix + "  ";
2034            for (int i = 0; i < taskIds.length; ++i) {
2035                sb.append(prefix); sb.append("taskId="); sb.append(taskIds[i]);
2036                        sb.append(": "); sb.append(taskNames[i]);
2037                        if (taskBounds != null) {
2038                            sb.append(" bounds="); sb.append(taskBounds[i].toShortString());
2039                        }
2040                        sb.append("\n");
2041            }
2042            return sb.toString();
2043        }
2044
2045        @Override
2046        public String toString() {
2047            return toString("");
2048        }
2049    }
2050
2051    /**
2052     * @hide
2053     */
2054    public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
2055        try {
2056            return ActivityManagerNative.getDefault().clearApplicationUserData(packageName,
2057                    observer, UserHandle.myUserId());
2058        } catch (RemoteException e) {
2059            return false;
2060        }
2061    }
2062
2063    /**
2064     * Permits an application to erase its own data from disk.  This is equivalent to
2065     * the user choosing to clear the app's data from within the device settings UI.  It
2066     * erases all dynamic data associated with the app -- its private data and data in its
2067     * private area on external storage -- but does not remove the installed application
2068     * itself, nor any OBB files.
2069     *
2070     * @return {@code true} if the application successfully requested that the application's
2071     *     data be erased; {@code false} otherwise.
2072     */
2073    public boolean clearApplicationUserData() {
2074        return clearApplicationUserData(mContext.getPackageName(), null);
2075    }
2076
2077    /**
2078     * Information you can retrieve about any processes that are in an error condition.
2079     */
2080    public static class ProcessErrorStateInfo implements Parcelable {
2081        /**
2082         * Condition codes
2083         */
2084        public static final int NO_ERROR = 0;
2085        public static final int CRASHED = 1;
2086        public static final int NOT_RESPONDING = 2;
2087
2088        /**
2089         * The condition that the process is in.
2090         */
2091        public int condition;
2092
2093        /**
2094         * The process name in which the crash or error occurred.
2095         */
2096        public String processName;
2097
2098        /**
2099         * The pid of this process; 0 if none
2100         */
2101        public int pid;
2102
2103        /**
2104         * The kernel user-ID that has been assigned to this process;
2105         * currently this is not a unique ID (multiple applications can have
2106         * the same uid).
2107         */
2108        public int uid;
2109
2110        /**
2111         * The activity name associated with the error, if known.  May be null.
2112         */
2113        public String tag;
2114
2115        /**
2116         * A short message describing the error condition.
2117         */
2118        public String shortMsg;
2119
2120        /**
2121         * A long message describing the error condition.
2122         */
2123        public String longMsg;
2124
2125        /**
2126         * The stack trace where the error originated.  May be null.
2127         */
2128        public String stackTrace;
2129
2130        /**
2131         * to be deprecated: This value will always be null.
2132         */
2133        public byte[] crashData = null;
2134
2135        public ProcessErrorStateInfo() {
2136        }
2137
2138        @Override
2139        public int describeContents() {
2140            return 0;
2141        }
2142
2143        @Override
2144        public void writeToParcel(Parcel dest, int flags) {
2145            dest.writeInt(condition);
2146            dest.writeString(processName);
2147            dest.writeInt(pid);
2148            dest.writeInt(uid);
2149            dest.writeString(tag);
2150            dest.writeString(shortMsg);
2151            dest.writeString(longMsg);
2152            dest.writeString(stackTrace);
2153        }
2154
2155        public void readFromParcel(Parcel source) {
2156            condition = source.readInt();
2157            processName = source.readString();
2158            pid = source.readInt();
2159            uid = source.readInt();
2160            tag = source.readString();
2161            shortMsg = source.readString();
2162            longMsg = source.readString();
2163            stackTrace = source.readString();
2164        }
2165
2166        public static final Creator<ProcessErrorStateInfo> CREATOR =
2167                new Creator<ProcessErrorStateInfo>() {
2168            public ProcessErrorStateInfo createFromParcel(Parcel source) {
2169                return new ProcessErrorStateInfo(source);
2170            }
2171            public ProcessErrorStateInfo[] newArray(int size) {
2172                return new ProcessErrorStateInfo[size];
2173            }
2174        };
2175
2176        private ProcessErrorStateInfo(Parcel source) {
2177            readFromParcel(source);
2178        }
2179    }
2180
2181    /**
2182     * Returns a list of any processes that are currently in an error condition.  The result
2183     * will be null if all processes are running properly at this time.
2184     *
2185     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
2186     * current error conditions (it will not return an empty list).  This list ordering is not
2187     * specified.
2188     */
2189    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
2190        try {
2191            return ActivityManagerNative.getDefault().getProcessesInErrorState();
2192        } catch (RemoteException e) {
2193            return null;
2194        }
2195    }
2196
2197    /**
2198     * Information you can retrieve about a running process.
2199     */
2200    public static class RunningAppProcessInfo implements Parcelable {
2201        /**
2202         * The name of the process that this object is associated with
2203         */
2204        public String processName;
2205
2206        /**
2207         * The pid of this process; 0 if none
2208         */
2209        public int pid;
2210
2211        /**
2212         * The user id of this process.
2213         */
2214        public int uid;
2215
2216        /**
2217         * All packages that have been loaded into the process.
2218         */
2219        public String pkgList[];
2220
2221        /**
2222         * Constant for {@link #flags}: this is an app that is unable to
2223         * correctly save its state when going to the background,
2224         * so it can not be killed while in the background.
2225         * @hide
2226         */
2227        public static final int FLAG_CANT_SAVE_STATE = 1<<0;
2228
2229        /**
2230         * Constant for {@link #flags}: this process is associated with a
2231         * persistent system app.
2232         * @hide
2233         */
2234        public static final int FLAG_PERSISTENT = 1<<1;
2235
2236        /**
2237         * Constant for {@link #flags}: this process is associated with a
2238         * persistent system app.
2239         * @hide
2240         */
2241        public static final int FLAG_HAS_ACTIVITIES = 1<<2;
2242
2243        /**
2244         * Flags of information.  May be any of
2245         * {@link #FLAG_CANT_SAVE_STATE}.
2246         * @hide
2247         */
2248        public int flags;
2249
2250        /**
2251         * Last memory trim level reported to the process: corresponds to
2252         * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
2253         * ComponentCallbacks2.onTrimMemory(int)}.
2254         */
2255        public int lastTrimLevel;
2256
2257        /**
2258         * Constant for {@link #importance}: This process is running the
2259         * foreground UI; that is, it is the thing currently at the top of the screen
2260         * that the user is interacting with.
2261         */
2262        public static final int IMPORTANCE_FOREGROUND = 100;
2263
2264        /**
2265         * Constant for {@link #importance}: This process is running a foreground
2266         * service, for example to perform music playback even while the user is
2267         * not immediately in the app.  This generally indicates that the process
2268         * is doing something the user actively cares about.
2269         */
2270        public static final int IMPORTANCE_FOREGROUND_SERVICE = 125;
2271
2272        /**
2273         * Constant for {@link #importance}: This process is running the foreground
2274         * UI, but the device is asleep so it is not visible to the user.  This means
2275         * the user is not really aware of the process, because they can not see or
2276         * interact with it, but it is quite important because it what they expect to
2277         * return to once unlocking the device.
2278         */
2279        public static final int IMPORTANCE_TOP_SLEEPING = 150;
2280
2281        /**
2282         * Constant for {@link #importance}: This process is running something
2283         * that is actively visible to the user, though not in the immediate
2284         * foreground.  This may be running a window that is behind the current
2285         * foreground (so paused and with its state saved, not interacting with
2286         * the user, but visible to them to some degree); it may also be running
2287         * other services under the system's control that it inconsiders important.
2288         */
2289        public static final int IMPORTANCE_VISIBLE = 200;
2290
2291        /**
2292         * Constant for {@link #importance}: This process is not something the user
2293         * is directly aware of, but is otherwise perceptable to them to some degree.
2294         */
2295        public static final int IMPORTANCE_PERCEPTIBLE = 130;
2296
2297        /**
2298         * Constant for {@link #importance}: This process is running an
2299         * application that can not save its state, and thus can't be killed
2300         * while in the background.
2301         * @hide
2302         */
2303        public static final int IMPORTANCE_CANT_SAVE_STATE = 170;
2304
2305        /**
2306         * Constant for {@link #importance}: This process is contains services
2307         * that should remain running.  These are background services apps have
2308         * started, not something the user is aware of, so they may be killed by
2309         * the system relatively freely (though it is generally desired that they
2310         * stay running as long as they want to).
2311         */
2312        public static final int IMPORTANCE_SERVICE = 300;
2313
2314        /**
2315         * Constant for {@link #importance}: This process process contains
2316         * background code that is expendable.
2317         */
2318        public static final int IMPORTANCE_BACKGROUND = 400;
2319
2320        /**
2321         * Constant for {@link #importance}: This process is empty of any
2322         * actively running code.
2323         */
2324        public static final int IMPORTANCE_EMPTY = 500;
2325
2326        /**
2327         * Constant for {@link #importance}: This process does not exist.
2328         */
2329        public static final int IMPORTANCE_GONE = 1000;
2330
2331        /** @hide */
2332        public static int procStateToImportance(int procState) {
2333            if (procState == PROCESS_STATE_NONEXISTENT) {
2334                return IMPORTANCE_GONE;
2335            } else if (procState >= PROCESS_STATE_HOME) {
2336                return IMPORTANCE_BACKGROUND;
2337            } else if (procState >= PROCESS_STATE_SERVICE) {
2338                return IMPORTANCE_SERVICE;
2339            } else if (procState > PROCESS_STATE_HEAVY_WEIGHT) {
2340                return IMPORTANCE_CANT_SAVE_STATE;
2341            } else if (procState >= PROCESS_STATE_IMPORTANT_BACKGROUND) {
2342                return IMPORTANCE_PERCEPTIBLE;
2343            } else if (procState >= PROCESS_STATE_IMPORTANT_FOREGROUND) {
2344                return IMPORTANCE_VISIBLE;
2345            } else if (procState >= PROCESS_STATE_TOP_SLEEPING) {
2346                return IMPORTANCE_TOP_SLEEPING;
2347            } else if (procState >= PROCESS_STATE_FOREGROUND_SERVICE) {
2348                return IMPORTANCE_FOREGROUND_SERVICE;
2349            } else {
2350                return IMPORTANCE_FOREGROUND;
2351            }
2352        }
2353
2354        /**
2355         * The relative importance level that the system places on this
2356         * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
2357         * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE},
2358         * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}.  These
2359         * constants are numbered so that "more important" values are always
2360         * smaller than "less important" values.
2361         */
2362        public int importance;
2363
2364        /**
2365         * An additional ordering within a particular {@link #importance}
2366         * category, providing finer-grained information about the relative
2367         * utility of processes within a category.  This number means nothing
2368         * except that a smaller values are more recently used (and thus
2369         * more important).  Currently an LRU value is only maintained for
2370         * the {@link #IMPORTANCE_BACKGROUND} category, though others may
2371         * be maintained in the future.
2372         */
2373        public int lru;
2374
2375        /**
2376         * Constant for {@link #importanceReasonCode}: nothing special has
2377         * been specified for the reason for this level.
2378         */
2379        public static final int REASON_UNKNOWN = 0;
2380
2381        /**
2382         * Constant for {@link #importanceReasonCode}: one of the application's
2383         * content providers is being used by another process.  The pid of
2384         * the client process is in {@link #importanceReasonPid} and the
2385         * target provider in this process is in
2386         * {@link #importanceReasonComponent}.
2387         */
2388        public static final int REASON_PROVIDER_IN_USE = 1;
2389
2390        /**
2391         * Constant for {@link #importanceReasonCode}: one of the application's
2392         * content providers is being used by another process.  The pid of
2393         * the client process is in {@link #importanceReasonPid} and the
2394         * target provider in this process is in
2395         * {@link #importanceReasonComponent}.
2396         */
2397        public static final int REASON_SERVICE_IN_USE = 2;
2398
2399        /**
2400         * The reason for {@link #importance}, if any.
2401         */
2402        public int importanceReasonCode;
2403
2404        /**
2405         * For the specified values of {@link #importanceReasonCode}, this
2406         * is the process ID of the other process that is a client of this
2407         * process.  This will be 0 if no other process is using this one.
2408         */
2409        public int importanceReasonPid;
2410
2411        /**
2412         * For the specified values of {@link #importanceReasonCode}, this
2413         * is the name of the component that is being used in this process.
2414         */
2415        public ComponentName importanceReasonComponent;
2416
2417        /**
2418         * When {@link #importanceReasonPid} is non-0, this is the importance
2419         * of the other pid. @hide
2420         */
2421        public int importanceReasonImportance;
2422
2423        /**
2424         * Current process state, as per PROCESS_STATE_* constants.
2425         * @hide
2426         */
2427        public int processState;
2428
2429        public RunningAppProcessInfo() {
2430            importance = IMPORTANCE_FOREGROUND;
2431            importanceReasonCode = REASON_UNKNOWN;
2432            processState = PROCESS_STATE_IMPORTANT_FOREGROUND;
2433        }
2434
2435        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
2436            processName = pProcessName;
2437            pid = pPid;
2438            pkgList = pArr;
2439        }
2440
2441        public int describeContents() {
2442            return 0;
2443        }
2444
2445        public void writeToParcel(Parcel dest, int flags) {
2446            dest.writeString(processName);
2447            dest.writeInt(pid);
2448            dest.writeInt(uid);
2449            dest.writeStringArray(pkgList);
2450            dest.writeInt(this.flags);
2451            dest.writeInt(lastTrimLevel);
2452            dest.writeInt(importance);
2453            dest.writeInt(lru);
2454            dest.writeInt(importanceReasonCode);
2455            dest.writeInt(importanceReasonPid);
2456            ComponentName.writeToParcel(importanceReasonComponent, dest);
2457            dest.writeInt(importanceReasonImportance);
2458            dest.writeInt(processState);
2459        }
2460
2461        public void readFromParcel(Parcel source) {
2462            processName = source.readString();
2463            pid = source.readInt();
2464            uid = source.readInt();
2465            pkgList = source.readStringArray();
2466            flags = source.readInt();
2467            lastTrimLevel = source.readInt();
2468            importance = source.readInt();
2469            lru = source.readInt();
2470            importanceReasonCode = source.readInt();
2471            importanceReasonPid = source.readInt();
2472            importanceReasonComponent = ComponentName.readFromParcel(source);
2473            importanceReasonImportance = source.readInt();
2474            processState = source.readInt();
2475        }
2476
2477        public static final Creator<RunningAppProcessInfo> CREATOR =
2478            new Creator<RunningAppProcessInfo>() {
2479            public RunningAppProcessInfo createFromParcel(Parcel source) {
2480                return new RunningAppProcessInfo(source);
2481            }
2482            public RunningAppProcessInfo[] newArray(int size) {
2483                return new RunningAppProcessInfo[size];
2484            }
2485        };
2486
2487        private RunningAppProcessInfo(Parcel source) {
2488            readFromParcel(source);
2489        }
2490    }
2491
2492    /**
2493     * Returns a list of application processes installed on external media
2494     * that are running on the device.
2495     *
2496     * <p><b>Note: this method is only intended for debugging or building
2497     * a user-facing process management UI.</b></p>
2498     *
2499     * @return Returns a list of ApplicationInfo records, or null if none
2500     * This list ordering is not specified.
2501     * @hide
2502     */
2503    public List<ApplicationInfo> getRunningExternalApplications() {
2504        try {
2505            return ActivityManagerNative.getDefault().getRunningExternalApplications();
2506        } catch (RemoteException e) {
2507            return null;
2508        }
2509    }
2510
2511    /**
2512     * Sets the memory trim mode for a process and schedules a memory trim operation.
2513     *
2514     * <p><b>Note: this method is only intended for testing framework.</b></p>
2515     *
2516     * @return Returns true if successful.
2517     * @hide
2518     */
2519    public boolean setProcessMemoryTrimLevel(String process, int userId, int level) {
2520        try {
2521            return ActivityManagerNative.getDefault().setProcessMemoryTrimLevel(process, userId,
2522                    level);
2523        } catch (RemoteException e) {
2524            return false;
2525        }
2526    }
2527
2528    /**
2529     * Returns a list of application processes that are running on the device.
2530     *
2531     * <p><b>Note: this method is only intended for debugging or building
2532     * a user-facing process management UI.</b></p>
2533     *
2534     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
2535     * running processes (it will not return an empty list).  This list ordering is not
2536     * specified.
2537     */
2538    public List<RunningAppProcessInfo> getRunningAppProcesses() {
2539        try {
2540            return ActivityManagerNative.getDefault().getRunningAppProcesses();
2541        } catch (RemoteException e) {
2542            return null;
2543        }
2544    }
2545
2546    /**
2547     * Return the importance of a given package name, based on the processes that are
2548     * currently running.  The return value is one of the importance constants defined
2549     * in {@link RunningAppProcessInfo}, giving you the highest importance of all the
2550     * processes that this package has code running inside of.  If there are no processes
2551     * running its code, {@link RunningAppProcessInfo#IMPORTANCE_GONE} is returned.
2552     * @hide
2553     */
2554    @SystemApi
2555    public int getPackageImportance(String packageName) {
2556        try {
2557            int procState = ActivityManagerNative.getDefault().getPackageProcessState(packageName,
2558                    mContext.getOpPackageName());
2559            return RunningAppProcessInfo.procStateToImportance(procState);
2560        } catch (RemoteException e) {
2561            return RunningAppProcessInfo.IMPORTANCE_GONE;
2562        }
2563    }
2564
2565    /**
2566     * Return global memory state information for the calling process.  This
2567     * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
2568     * only fields that will be filled in are
2569     * {@link RunningAppProcessInfo#pid},
2570     * {@link RunningAppProcessInfo#uid},
2571     * {@link RunningAppProcessInfo#lastTrimLevel},
2572     * {@link RunningAppProcessInfo#importance},
2573     * {@link RunningAppProcessInfo#lru}, and
2574     * {@link RunningAppProcessInfo#importanceReasonCode}.
2575     */
2576    static public void getMyMemoryState(RunningAppProcessInfo outState) {
2577        try {
2578            ActivityManagerNative.getDefault().getMyMemoryState(outState);
2579        } catch (RemoteException e) {
2580        }
2581    }
2582
2583    /**
2584     * Return information about the memory usage of one or more processes.
2585     *
2586     * <p><b>Note: this method is only intended for debugging or building
2587     * a user-facing process management UI.</b></p>
2588     *
2589     * @param pids The pids of the processes whose memory usage is to be
2590     * retrieved.
2591     * @return Returns an array of memory information, one for each
2592     * requested pid.
2593     */
2594    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
2595        try {
2596            return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids);
2597        } catch (RemoteException e) {
2598            return null;
2599        }
2600    }
2601
2602    /**
2603     * @deprecated This is now just a wrapper for
2604     * {@link #killBackgroundProcesses(String)}; the previous behavior here
2605     * is no longer available to applications because it allows them to
2606     * break other applications by removing their alarms, stopping their
2607     * services, etc.
2608     */
2609    @Deprecated
2610    public void restartPackage(String packageName) {
2611        killBackgroundProcesses(packageName);
2612    }
2613
2614    /**
2615     * Have the system immediately kill all background processes associated
2616     * with the given package.  This is the same as the kernel killing those
2617     * processes to reclaim memory; the system will take care of restarting
2618     * these processes in the future as needed.
2619     *
2620     * <p>You must hold the permission
2621     * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
2622     * call this method.
2623     *
2624     * @param packageName The name of the package whose processes are to
2625     * be killed.
2626     */
2627    public void killBackgroundProcesses(String packageName) {
2628        try {
2629            ActivityManagerNative.getDefault().killBackgroundProcesses(packageName,
2630                    UserHandle.myUserId());
2631        } catch (RemoteException e) {
2632        }
2633    }
2634
2635    /**
2636     * Kills the specified UID.
2637     * @param uid The UID to kill.
2638     * @param reason The reason for the kill.
2639     *
2640     * @hide
2641     */
2642    @RequiresPermission(Manifest.permission.KILL_UID)
2643    public void killUid(int uid, String reason) {
2644        try {
2645            ActivityManagerNative.getDefault().killUid(UserHandle.getAppId(uid),
2646                    UserHandle.getUserId(uid), reason);
2647        } catch (RemoteException e) {
2648            Log.e(TAG, "Couldn't kill uid:" + uid, e);
2649        }
2650    }
2651
2652    /**
2653     * Have the system perform a force stop of everything associated with
2654     * the given application package.  All processes that share its uid
2655     * will be killed, all services it has running stopped, all activities
2656     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
2657     * broadcast will be sent, so that any of its registered alarms can
2658     * be stopped, notifications removed, etc.
2659     *
2660     * <p>You must hold the permission
2661     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
2662     * call this method.
2663     *
2664     * @param packageName The name of the package to be stopped.
2665     * @param userId The user for which the running package is to be stopped.
2666     *
2667     * @hide This is not available to third party applications due to
2668     * it allowing them to break other applications by stopping their
2669     * services, removing their alarms, etc.
2670     */
2671    public void forceStopPackageAsUser(String packageName, int userId) {
2672        try {
2673            ActivityManagerNative.getDefault().forceStopPackage(packageName, userId);
2674        } catch (RemoteException e) {
2675        }
2676    }
2677
2678    /**
2679     * @see #forceStopPackageAsUser(String, int)
2680     * @hide
2681     */
2682    public void forceStopPackage(String packageName) {
2683        forceStopPackageAsUser(packageName, UserHandle.myUserId());
2684    }
2685
2686    /**
2687     * Get the device configuration attributes.
2688     */
2689    public ConfigurationInfo getDeviceConfigurationInfo() {
2690        try {
2691            return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
2692        } catch (RemoteException e) {
2693        }
2694        return null;
2695    }
2696
2697    /**
2698     * Get the preferred density of icons for the launcher. This is used when
2699     * custom drawables are created (e.g., for shortcuts).
2700     *
2701     * @return density in terms of DPI
2702     */
2703    public int getLauncherLargeIconDensity() {
2704        final Resources res = mContext.getResources();
2705        final int density = res.getDisplayMetrics().densityDpi;
2706        final int sw = res.getConfiguration().smallestScreenWidthDp;
2707
2708        if (sw < 600) {
2709            // Smaller than approx 7" tablets, use the regular icon size.
2710            return density;
2711        }
2712
2713        switch (density) {
2714            case DisplayMetrics.DENSITY_LOW:
2715                return DisplayMetrics.DENSITY_MEDIUM;
2716            case DisplayMetrics.DENSITY_MEDIUM:
2717                return DisplayMetrics.DENSITY_HIGH;
2718            case DisplayMetrics.DENSITY_TV:
2719                return DisplayMetrics.DENSITY_XHIGH;
2720            case DisplayMetrics.DENSITY_HIGH:
2721                return DisplayMetrics.DENSITY_XHIGH;
2722            case DisplayMetrics.DENSITY_XHIGH:
2723                return DisplayMetrics.DENSITY_XXHIGH;
2724            case DisplayMetrics.DENSITY_XXHIGH:
2725                return DisplayMetrics.DENSITY_XHIGH * 2;
2726            default:
2727                // The density is some abnormal value.  Return some other
2728                // abnormal value that is a reasonable scaling of it.
2729                return (int)((density*1.5f)+.5f);
2730        }
2731    }
2732
2733    /**
2734     * Get the preferred launcher icon size. This is used when custom drawables
2735     * are created (e.g., for shortcuts).
2736     *
2737     * @return dimensions of square icons in terms of pixels
2738     */
2739    public int getLauncherLargeIconSize() {
2740        return getLauncherLargeIconSizeInner(mContext);
2741    }
2742
2743    static int getLauncherLargeIconSizeInner(Context context) {
2744        final Resources res = context.getResources();
2745        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
2746        final int sw = res.getConfiguration().smallestScreenWidthDp;
2747
2748        if (sw < 600) {
2749            // Smaller than approx 7" tablets, use the regular icon size.
2750            return size;
2751        }
2752
2753        final int density = res.getDisplayMetrics().densityDpi;
2754
2755        switch (density) {
2756            case DisplayMetrics.DENSITY_LOW:
2757                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
2758            case DisplayMetrics.DENSITY_MEDIUM:
2759                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
2760            case DisplayMetrics.DENSITY_TV:
2761                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
2762            case DisplayMetrics.DENSITY_HIGH:
2763                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
2764            case DisplayMetrics.DENSITY_XHIGH:
2765                return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
2766            case DisplayMetrics.DENSITY_XXHIGH:
2767                return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
2768            default:
2769                // The density is some abnormal value.  Return some other
2770                // abnormal value that is a reasonable scaling of it.
2771                return (int)((size*1.5f) + .5f);
2772        }
2773    }
2774
2775    /**
2776     * Returns "true" if the user interface is currently being messed with
2777     * by a monkey.
2778     */
2779    public static boolean isUserAMonkey() {
2780        try {
2781            return ActivityManagerNative.getDefault().isUserAMonkey();
2782        } catch (RemoteException e) {
2783        }
2784        return false;
2785    }
2786
2787    /**
2788     * Returns "true" if device is running in a test harness.
2789     */
2790    public static boolean isRunningInTestHarness() {
2791        return SystemProperties.getBoolean("ro.test_harness", false);
2792    }
2793
2794    /**
2795     * Returns the launch count of each installed package.
2796     *
2797     * @hide
2798     */
2799    /*public Map<String, Integer> getAllPackageLaunchCounts() {
2800        try {
2801            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
2802                    ServiceManager.getService("usagestats"));
2803            if (usageStatsService == null) {
2804                return new HashMap<String, Integer>();
2805            }
2806
2807            UsageStats.PackageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats(
2808                    ActivityThread.currentPackageName());
2809            if (allPkgUsageStats == null) {
2810                return new HashMap<String, Integer>();
2811            }
2812
2813            Map<String, Integer> launchCounts = new HashMap<String, Integer>();
2814            for (UsageStats.PackageStats pkgUsageStats : allPkgUsageStats) {
2815                launchCounts.put(pkgUsageStats.getPackageName(), pkgUsageStats.getLaunchCount());
2816            }
2817
2818            return launchCounts;
2819        } catch (RemoteException e) {
2820            Log.w(TAG, "Could not query launch counts", e);
2821            return new HashMap<String, Integer>();
2822        }
2823    }*/
2824
2825    /** @hide */
2826    public static int checkComponentPermission(String permission, int uid,
2827            int owningUid, boolean exported) {
2828        // Root, system server get to do everything.
2829        final int appId = UserHandle.getAppId(uid);
2830        if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
2831            return PackageManager.PERMISSION_GRANTED;
2832        }
2833        // Isolated processes don't get any permissions.
2834        if (UserHandle.isIsolated(uid)) {
2835            return PackageManager.PERMISSION_DENIED;
2836        }
2837        // If there is a uid that owns whatever is being accessed, it has
2838        // blanket access to it regardless of the permissions it requires.
2839        if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
2840            return PackageManager.PERMISSION_GRANTED;
2841        }
2842        // If the target is not exported, then nobody else can get to it.
2843        if (!exported) {
2844            /*
2845            RuntimeException here = new RuntimeException("here");
2846            here.fillInStackTrace();
2847            Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
2848                    here);
2849            */
2850            return PackageManager.PERMISSION_DENIED;
2851        }
2852        if (permission == null) {
2853            return PackageManager.PERMISSION_GRANTED;
2854        }
2855        try {
2856            return AppGlobals.getPackageManager()
2857                    .checkUidPermission(permission, uid);
2858        } catch (RemoteException e) {
2859            // Should never happen, but if it does... deny!
2860            Slog.e(TAG, "PackageManager is dead?!?", e);
2861        }
2862        return PackageManager.PERMISSION_DENIED;
2863    }
2864
2865    /** @hide */
2866    public static int checkUidPermission(String permission, int uid) {
2867        try {
2868            return AppGlobals.getPackageManager()
2869                    .checkUidPermission(permission, uid);
2870        } catch (RemoteException e) {
2871            // Should never happen, but if it does... deny!
2872            Slog.e(TAG, "PackageManager is dead?!?", e);
2873        }
2874        return PackageManager.PERMISSION_DENIED;
2875    }
2876
2877    /**
2878     * @hide
2879     * Helper for dealing with incoming user arguments to system service calls.
2880     * Takes care of checking permissions and converting USER_CURRENT to the
2881     * actual current user.
2882     *
2883     * @param callingPid The pid of the incoming call, as per Binder.getCallingPid().
2884     * @param callingUid The uid of the incoming call, as per Binder.getCallingUid().
2885     * @param userId The user id argument supplied by the caller -- this is the user
2886     * they want to run as.
2887     * @param allowAll If true, we will allow USER_ALL.  This means you must be prepared
2888     * to get a USER_ALL returned and deal with it correctly.  If false,
2889     * an exception will be thrown if USER_ALL is supplied.
2890     * @param requireFull If true, the caller must hold
2891     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a
2892     * different user than their current process; otherwise they must hold
2893     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
2894     * @param name Optional textual name of the incoming call; only for generating error messages.
2895     * @param callerPackage Optional package name of caller; only for error messages.
2896     *
2897     * @return Returns the user ID that the call should run as.  Will always be a concrete
2898     * user number, unless <var>allowAll</var> is true in which case it could also be
2899     * USER_ALL.
2900     */
2901    public static int handleIncomingUser(int callingPid, int callingUid, int userId,
2902            boolean allowAll, boolean requireFull, String name, String callerPackage) {
2903        if (UserHandle.getUserId(callingUid) == userId) {
2904            return userId;
2905        }
2906        try {
2907            return ActivityManagerNative.getDefault().handleIncomingUser(callingPid,
2908                    callingUid, userId, allowAll, requireFull, name, callerPackage);
2909        } catch (RemoteException e) {
2910            throw new SecurityException("Failed calling activity manager", e);
2911        }
2912    }
2913
2914    /**
2915     * Gets the userId of the current foreground user. Requires system permissions.
2916     * @hide
2917     */
2918    @SystemApi
2919    public static int getCurrentUser() {
2920        UserInfo ui;
2921        try {
2922            ui = ActivityManagerNative.getDefault().getCurrentUser();
2923            return ui != null ? ui.id : 0;
2924        } catch (RemoteException e) {
2925            return 0;
2926        }
2927    }
2928
2929    /**
2930     * @param userid the user's id. Zero indicates the default user.
2931     * @hide
2932     */
2933    public boolean switchUser(int userid) {
2934        try {
2935            return ActivityManagerNative.getDefault().switchUser(userid);
2936        } catch (RemoteException e) {
2937            return false;
2938        }
2939    }
2940
2941    /**
2942     * Return whether the given user is actively running.  This means that
2943     * the user is in the "started" state, not "stopped" -- it is currently
2944     * allowed to run code through scheduled alarms, receiving broadcasts,
2945     * etc.  A started user may be either the current foreground user or a
2946     * background user; the result here does not distinguish between the two.
2947     * @param userid the user's id. Zero indicates the default user.
2948     * @hide
2949     */
2950    public boolean isUserRunning(int userid) {
2951        try {
2952            return ActivityManagerNative.getDefault().isUserRunning(userid, false);
2953        } catch (RemoteException e) {
2954            return false;
2955        }
2956    }
2957
2958    /**
2959     * Perform a system dump of various state associated with the given application
2960     * package name.  This call blocks while the dump is being performed, so should
2961     * not be done on a UI thread.  The data will be written to the given file
2962     * descriptor as text.  An application must hold the
2963     * {@link android.Manifest.permission#DUMP} permission to make this call.
2964     * @param fd The file descriptor that the dump should be written to.  The file
2965     * descriptor is <em>not</em> closed by this function; the caller continues to
2966     * own it.
2967     * @param packageName The name of the package that is to be dumped.
2968     */
2969    public void dumpPackageState(FileDescriptor fd, String packageName) {
2970        dumpPackageStateStatic(fd, packageName);
2971    }
2972
2973    /**
2974     * @hide
2975     */
2976    public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) {
2977        FileOutputStream fout = new FileOutputStream(fd);
2978        PrintWriter pw = new FastPrintWriter(fout);
2979        dumpService(pw, fd, "package", new String[] { packageName });
2980        pw.println();
2981        dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] {
2982                "-a", "package", packageName });
2983        pw.println();
2984        dumpService(pw, fd, "meminfo", new String[] { "--local", "--package", packageName });
2985        pw.println();
2986        dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { packageName });
2987        pw.println();
2988        dumpService(pw, fd, "usagestats", new String[] { "--packages", packageName });
2989        pw.println();
2990        dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName });
2991        pw.flush();
2992    }
2993
2994    private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) {
2995        pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
2996        IBinder service = ServiceManager.checkService(name);
2997        if (service == null) {
2998            pw.println("  (Service not found)");
2999            return;
3000        }
3001        TransferPipe tp = null;
3002        try {
3003            pw.flush();
3004            tp = new TransferPipe();
3005            tp.setBufferPrefix("  ");
3006            service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args);
3007            tp.go(fd, 10000);
3008        } catch (Throwable e) {
3009            if (tp != null) {
3010                tp.kill();
3011            }
3012            pw.println("Failure dumping service:");
3013            e.printStackTrace(pw);
3014        }
3015    }
3016
3017    /**
3018     * Request that the system start watching for the calling process to exceed a pss
3019     * size as given here.  Once called, the system will look for any occasions where it
3020     * sees the associated process with a larger pss size and, when this happens, automatically
3021     * pull a heap dump from it and allow the user to share the data.  Note that this request
3022     * continues running even if the process is killed and restarted.  To remove the watch,
3023     * use {@link #clearWatchHeapLimit()}.
3024     *
3025     * <p>This API only work if the calling process has been marked as
3026     * {@link ApplicationInfo#FLAG_DEBUGGABLE} or this is running on a debuggable
3027     * (userdebug or eng) build.</p>
3028     *
3029     * <p>Callers can optionally implement {@link #ACTION_REPORT_HEAP_LIMIT} to directly
3030     * handle heap limit reports themselves.</p>
3031     *
3032     * @param pssSize The size in bytes to set the limit at.
3033     */
3034    public void setWatchHeapLimit(long pssSize) {
3035        try {
3036            ActivityManagerNative.getDefault().setDumpHeapDebugLimit(null, 0, pssSize,
3037                    mContext.getPackageName());
3038        } catch (RemoteException e) {
3039        }
3040    }
3041
3042    /**
3043     * Action an app can implement to handle reports from {@link #setWatchHeapLimit(long)}.
3044     * If your package has an activity handling this action, it will be launched with the
3045     * heap data provided to it the same way as {@link Intent#ACTION_SEND}.  Note that to
3046     * match the activty must support this action and a MIME type of "*&#47;*".
3047     */
3048    public static final String ACTION_REPORT_HEAP_LIMIT = "android.app.action.REPORT_HEAP_LIMIT";
3049
3050    /**
3051     * Clear a heap watch limit previously set by {@link #setWatchHeapLimit(long)}.
3052     */
3053    public void clearWatchHeapLimit() {
3054        try {
3055            ActivityManagerNative.getDefault().setDumpHeapDebugLimit(null, 0, 0, null);
3056        } catch (RemoteException e) {
3057        }
3058    }
3059
3060    /**
3061     * @hide
3062     */
3063    public void startLockTaskMode(int taskId) {
3064        try {
3065            ActivityManagerNative.getDefault().startLockTaskMode(taskId);
3066        } catch (RemoteException e) {
3067        }
3068    }
3069
3070    /**
3071     * @hide
3072     */
3073    public void stopLockTaskMode() {
3074        try {
3075            ActivityManagerNative.getDefault().stopLockTaskMode();
3076        } catch (RemoteException e) {
3077        }
3078    }
3079
3080    /**
3081     * Return whether currently in lock task mode.  When in this mode
3082     * no new tasks can be created or switched to.
3083     *
3084     * @see Activity#startLockTask()
3085     *
3086     * @deprecated Use {@link #getLockTaskModeState} instead.
3087     */
3088    public boolean isInLockTaskMode() {
3089        return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3090    }
3091
3092    /**
3093     * Return the current state of task locking. The three possible outcomes
3094     * are {@link #LOCK_TASK_MODE_NONE}, {@link #LOCK_TASK_MODE_LOCKED}
3095     * and {@link #LOCK_TASK_MODE_PINNED}.
3096     *
3097     * @see Activity#startLockTask()
3098     */
3099    public int getLockTaskModeState() {
3100        try {
3101            return ActivityManagerNative.getDefault().getLockTaskModeState();
3102        } catch (RemoteException e) {
3103            return ActivityManager.LOCK_TASK_MODE_NONE;
3104        }
3105    }
3106
3107    /**
3108     * The AppTask allows you to manage your own application's tasks.
3109     * See {@link android.app.ActivityManager#getAppTasks()}
3110     */
3111    public static class AppTask {
3112        private IAppTask mAppTaskImpl;
3113
3114        /** @hide */
3115        public AppTask(IAppTask task) {
3116            mAppTaskImpl = task;
3117        }
3118
3119        /**
3120         * Finishes all activities in this task and removes it from the recent tasks list.
3121         */
3122        public void finishAndRemoveTask() {
3123            try {
3124                mAppTaskImpl.finishAndRemoveTask();
3125            } catch (RemoteException e) {
3126                Slog.e(TAG, "Invalid AppTask", e);
3127            }
3128        }
3129
3130        /**
3131         * Get the RecentTaskInfo associated with this task.
3132         *
3133         * @return The RecentTaskInfo for this task, or null if the task no longer exists.
3134         */
3135        public RecentTaskInfo getTaskInfo() {
3136            try {
3137                return mAppTaskImpl.getTaskInfo();
3138            } catch (RemoteException e) {
3139                Slog.e(TAG, "Invalid AppTask", e);
3140                return null;
3141            }
3142        }
3143
3144        /**
3145         * Bring this task to the foreground.  If it contains activities, they will be
3146         * brought to the foreground with it and their instances re-created if needed.
3147         * If it doesn't contain activities, the root activity of the task will be
3148         * re-launched.
3149         */
3150        public void moveToFront() {
3151            try {
3152                mAppTaskImpl.moveToFront();
3153            } catch (RemoteException e) {
3154                Slog.e(TAG, "Invalid AppTask", e);
3155            }
3156        }
3157
3158        /**
3159         * Start an activity in this task.  Brings the task to the foreground.  If this task
3160         * is not currently active (that is, its id < 0), then a new activity for the given
3161         * Intent will be launched as the root of the task and the task brought to the
3162         * foreground.  Otherwise, if this task is currently active and the Intent does not specify
3163         * an activity to launch in a new task, then a new activity for the given Intent will
3164         * be launched on top of the task and the task brought to the foreground.  If this
3165         * task is currently active and the Intent specifies {@link Intent#FLAG_ACTIVITY_NEW_TASK}
3166         * or would otherwise be launched in to a new task, then the activity not launched but
3167         * this task be brought to the foreground and a new intent delivered to the top
3168         * activity if appropriate.
3169         *
3170         * <p>In other words, you generally want to use an Intent here that does not specify
3171         * {@link Intent#FLAG_ACTIVITY_NEW_TASK} or {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT},
3172         * and let the system do the right thing.</p>
3173         *
3174         * @param intent The Intent describing the new activity to be launched on the task.
3175         * @param options Optional launch options.
3176         *
3177         * @see Activity#startActivity(android.content.Intent, android.os.Bundle)
3178         */
3179        public void startActivity(Context context, Intent intent, Bundle options) {
3180            ActivityThread thread = ActivityThread.currentActivityThread();
3181            thread.getInstrumentation().execStartActivityFromAppTask(context,
3182                    thread.getApplicationThread(), mAppTaskImpl, intent, options);
3183        }
3184
3185        /**
3186         * Modify the {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag in the root
3187         * Intent of this AppTask.
3188         *
3189         * @param exclude If true, {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} will
3190         * be set; otherwise, it will be cleared.
3191         */
3192        public void setExcludeFromRecents(boolean exclude) {
3193            try {
3194                mAppTaskImpl.setExcludeFromRecents(exclude);
3195            } catch (RemoteException e) {
3196                Slog.e(TAG, "Invalid AppTask", e);
3197            }
3198        }
3199    }
3200}
3201