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