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