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