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