ActivityManager.java revision 0debc9aff4c0cbc28e083a948081d91b0f171319
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.os.BatteryStats;
20import android.os.IBinder;
21import android.os.ParcelFileDescriptor;
22import com.android.internal.app.ProcessStats;
23import com.android.internal.os.TransferPipe;
24import com.android.internal.util.FastPrintWriter;
25
26import android.content.ComponentName;
27import android.content.Context;
28import android.content.Intent;
29import android.content.pm.ApplicationInfo;
30import android.content.pm.ConfigurationInfo;
31import android.content.pm.IPackageDataObserver;
32import android.content.pm.PackageManager;
33import android.content.pm.UserInfo;
34import android.content.res.Resources;
35import android.graphics.Bitmap;
36import android.graphics.Color;
37import android.graphics.Rect;
38import android.os.Bundle;
39import android.os.Debug;
40import android.os.Handler;
41import android.os.Parcel;
42import android.os.Parcelable;
43import android.os.Process;
44import android.os.RemoteException;
45import android.os.ServiceManager;
46import android.os.SystemProperties;
47import android.os.UserHandle;
48import android.text.TextUtils;
49import android.util.DisplayMetrics;
50import android.util.Log;
51import android.util.Slog;
52
53import java.io.FileDescriptor;
54import java.io.FileOutputStream;
55import java.io.PrintWriter;
56import java.util.ArrayList;
57import java.util.HashMap;
58import java.util.List;
59import java.util.Map;
60
61/**
62 * Interact with the overall activities running in the system.
63 */
64public class ActivityManager {
65    private static String TAG = "ActivityManager";
66    private static boolean localLOGV = false;
67
68    private final Context mContext;
69    private final Handler mHandler;
70
71    /**
72     * <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code
73     * &lt;meta-data>}</a> name for a 'home' Activity that declares a package that is to be
74     * uninstalled in lieu of the declaring one.  The package named here must be
75     * signed with the same certificate as the one declaring the {@code &lt;meta-data>}.
76     */
77    public static final String META_HOME_ALTERNATE = "android.app.home.alternate";
78
79    /**
80     * Result for IActivityManager.startActivity: trying to start an activity under voice
81     * control when that activity does not support the VOICE category.
82     * @hide
83     */
84    public static final int START_NOT_VOICE_COMPATIBLE = -7;
85
86    /**
87     * Result for IActivityManager.startActivity: an error where the
88     * start had to be canceled.
89     * @hide
90     */
91    public static final int START_CANCELED = -6;
92
93    /**
94     * Result for IActivityManager.startActivity: an error where the
95     * thing being started is not an activity.
96     * @hide
97     */
98    public static final int START_NOT_ACTIVITY = -5;
99
100    /**
101     * Result for IActivityManager.startActivity: an error where the
102     * caller does not have permission to start the activity.
103     * @hide
104     */
105    public static final int START_PERMISSION_DENIED = -4;
106
107    /**
108     * Result for IActivityManager.startActivity: an error where the
109     * caller has requested both to forward a result and to receive
110     * a result.
111     * @hide
112     */
113    public static final int START_FORWARD_AND_REQUEST_CONFLICT = -3;
114
115    /**
116     * Result for IActivityManager.startActivity: an error where the
117     * requested class is not found.
118     * @hide
119     */
120    public static final int START_CLASS_NOT_FOUND = -2;
121
122    /**
123     * Result for IActivityManager.startActivity: an error where the
124     * given Intent could not be resolved to an activity.
125     * @hide
126     */
127    public static final int START_INTENT_NOT_RESOLVED = -1;
128
129    /**
130     * Result for IActivityManaqer.startActivity: the activity was started
131     * successfully as normal.
132     * @hide
133     */
134    public static final int START_SUCCESS = 0;
135
136    /**
137     * Result for IActivityManaqer.startActivity: the caller asked that the Intent not
138     * be executed if it is the recipient, and that is indeed the case.
139     * @hide
140     */
141    public static final int START_RETURN_INTENT_TO_CALLER = 1;
142
143    /**
144     * Result for IActivityManaqer.startActivity: activity wasn't really started, but
145     * a task was simply brought to the foreground.
146     * @hide
147     */
148    public static final int START_TASK_TO_FRONT = 2;
149
150    /**
151     * Result for IActivityManaqer.startActivity: activity wasn't really started, but
152     * the given Intent was given to the existing top activity.
153     * @hide
154     */
155    public static final int START_DELIVERED_TO_TOP = 3;
156
157    /**
158     * Result for IActivityManaqer.startActivity: request was canceled because
159     * app switches are temporarily canceled to ensure the user's last request
160     * (such as pressing home) is performed.
161     * @hide
162     */
163    public static final int START_SWITCHES_CANCELED = 4;
164
165    /**
166     * Result for IActivityManaqer.startActivity: a new activity was attempted to be started
167     * while in Lock Task Mode.
168     * @hide
169     */
170    public static final int START_RETURN_LOCK_TASK_MODE_VIOLATION = 5;
171
172    /**
173     * Flag for IActivityManaqer.startActivity: do special start mode where
174     * a new activity is launched only if it is needed.
175     * @hide
176     */
177    public static final int START_FLAG_ONLY_IF_NEEDED = 1<<0;
178
179    /**
180     * Flag for IActivityManaqer.startActivity: launch the app for
181     * debugging.
182     * @hide
183     */
184    public static final int START_FLAG_DEBUG = 1<<1;
185
186    /**
187     * Flag for IActivityManaqer.startActivity: launch the app for
188     * OpenGL tracing.
189     * @hide
190     */
191    public static final int START_FLAG_OPENGL_TRACES = 1<<2;
192
193    /**
194     * Flag for IActivityManaqer.startActivity: if the app is being
195     * launched for profiling, automatically stop the profiler once done.
196     * @hide
197     */
198    public static final int START_FLAG_AUTO_STOP_PROFILER = 1<<3;
199
200    /**
201     * Result for IActivityManaqer.broadcastIntent: success!
202     * @hide
203     */
204    public static final int BROADCAST_SUCCESS = 0;
205
206    /**
207     * Result for IActivityManaqer.broadcastIntent: attempt to broadcast
208     * a sticky intent without appropriate permission.
209     * @hide
210     */
211    public static final int BROADCAST_STICKY_CANT_HAVE_PERMISSION = -1;
212
213    /**
214     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
215     * for a sendBroadcast operation.
216     * @hide
217     */
218    public static final int INTENT_SENDER_BROADCAST = 1;
219
220    /**
221     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
222     * for a startActivity operation.
223     * @hide
224     */
225    public static final int INTENT_SENDER_ACTIVITY = 2;
226
227    /**
228     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
229     * for an activity result operation.
230     * @hide
231     */
232    public static final int INTENT_SENDER_ACTIVITY_RESULT = 3;
233
234    /**
235     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
236     * for a startService operation.
237     * @hide
238     */
239    public static final int INTENT_SENDER_SERVICE = 4;
240
241    /** @hide User operation call: success! */
242    public static final int USER_OP_SUCCESS = 0;
243
244    /** @hide User operation call: given user id is not known. */
245    public static final int USER_OP_UNKNOWN_USER = -1;
246
247    /** @hide User operation call: given user id is the current user, can't be stopped. */
248    public static final int USER_OP_IS_CURRENT = -2;
249
250    /** @hide Process is a persistent system process. */
251    public static final int PROCESS_STATE_PERSISTENT = 0;
252
253    /** @hide Process is a persistent system process and is doing UI. */
254    public static final int PROCESS_STATE_PERSISTENT_UI = 1;
255
256    /** @hide Process is hosting the current top activities.  Note that this covers
257     * all activities that are visible to the user. */
258    public static final int PROCESS_STATE_TOP = 2;
259
260    /** @hide Process is important to the user, and something they are aware of. */
261    public static final int PROCESS_STATE_IMPORTANT_FOREGROUND = 3;
262
263    /** @hide Process is important to the user, but not something they are aware of. */
264    public static final int PROCESS_STATE_IMPORTANT_BACKGROUND = 4;
265
266    /** @hide Process is in the background running a backup/restore operation. */
267    public static final int PROCESS_STATE_BACKUP = 5;
268
269    /** @hide Process is in the background, but it can't restore its state so we want
270     * to try to avoid killing it. */
271    public static final int PROCESS_STATE_HEAVY_WEIGHT = 6;
272
273    /** @hide Process is in the background running a service.  Unlike oom_adj, this level
274     * is used for both the normal running in background state and the executing
275     * operations state. */
276    public static final int PROCESS_STATE_SERVICE = 7;
277
278    /** @hide Process is in the background running a receiver.   Note that from the
279     * perspective of oom_adj receivers run at a higher foreground level, but for our
280     * prioritization here that is not necessary and putting them below services means
281     * many fewer changes in some process states as they receive broadcasts. */
282    public static final int PROCESS_STATE_RECEIVER = 8;
283
284    /** @hide Process is in the background but hosts the home activity. */
285    public static final int PROCESS_STATE_HOME = 9;
286
287    /** @hide Process is in the background but hosts the last shown activity. */
288    public static final int PROCESS_STATE_LAST_ACTIVITY = 10;
289
290    /** @hide Process is being cached for later use and contains activities. */
291    public static final int PROCESS_STATE_CACHED_ACTIVITY = 11;
292
293    /** @hide Process is being cached for later use and is a client of another cached
294     * process that contains activities. */
295    public static final int PROCESS_STATE_CACHED_ACTIVITY_CLIENT = 12;
296
297    /** @hide Process is being cached for later use and is empty. */
298    public static final int PROCESS_STATE_CACHED_EMPTY = 13;
299
300    /*package*/ ActivityManager(Context context, Handler handler) {
301        mContext = context;
302        mHandler = handler;
303    }
304
305    /**
306     * Screen compatibility mode: the application most always run in
307     * compatibility mode.
308     * @hide
309     */
310    public static final int COMPAT_MODE_ALWAYS = -1;
311
312    /**
313     * Screen compatibility mode: the application can never run in
314     * compatibility mode.
315     * @hide
316     */
317    public static final int COMPAT_MODE_NEVER = -2;
318
319    /**
320     * Screen compatibility mode: unknown.
321     * @hide
322     */
323    public static final int COMPAT_MODE_UNKNOWN = -3;
324
325    /**
326     * Screen compatibility mode: the application currently has compatibility
327     * mode disabled.
328     * @hide
329     */
330    public static final int COMPAT_MODE_DISABLED = 0;
331
332    /**
333     * Screen compatibility mode: the application currently has compatibility
334     * mode enabled.
335     * @hide
336     */
337    public static final int COMPAT_MODE_ENABLED = 1;
338
339    /**
340     * Screen compatibility mode: request to toggle the application's
341     * compatibility mode.
342     * @hide
343     */
344    public static final int COMPAT_MODE_TOGGLE = 2;
345
346    /** @hide */
347    public int getFrontActivityScreenCompatMode() {
348        try {
349            return ActivityManagerNative.getDefault().getFrontActivityScreenCompatMode();
350        } catch (RemoteException e) {
351            // System dead, we will be dead too soon!
352            return 0;
353        }
354    }
355
356    /** @hide */
357    public void setFrontActivityScreenCompatMode(int mode) {
358        try {
359            ActivityManagerNative.getDefault().setFrontActivityScreenCompatMode(mode);
360        } catch (RemoteException e) {
361            // System dead, we will be dead too soon!
362        }
363    }
364
365    /** @hide */
366    public int getPackageScreenCompatMode(String packageName) {
367        try {
368            return ActivityManagerNative.getDefault().getPackageScreenCompatMode(packageName);
369        } catch (RemoteException e) {
370            // System dead, we will be dead too soon!
371            return 0;
372        }
373    }
374
375    /** @hide */
376    public void setPackageScreenCompatMode(String packageName, int mode) {
377        try {
378            ActivityManagerNative.getDefault().setPackageScreenCompatMode(packageName, mode);
379        } catch (RemoteException e) {
380            // System dead, we will be dead too soon!
381        }
382    }
383
384    /** @hide */
385    public boolean getPackageAskScreenCompat(String packageName) {
386        try {
387            return ActivityManagerNative.getDefault().getPackageAskScreenCompat(packageName);
388        } catch (RemoteException e) {
389            // System dead, we will be dead too soon!
390            return false;
391        }
392    }
393
394    /** @hide */
395    public void setPackageAskScreenCompat(String packageName, boolean ask) {
396        try {
397            ActivityManagerNative.getDefault().setPackageAskScreenCompat(packageName, ask);
398        } catch (RemoteException e) {
399            // System dead, we will be dead too soon!
400        }
401    }
402
403    /**
404     * Return the approximate per-application memory class of the current
405     * device.  This gives you an idea of how hard a memory limit you should
406     * impose on your application to let the overall system work best.  The
407     * returned value is in megabytes; the baseline Android memory class is
408     * 16 (which happens to be the Java heap limit of those devices); some
409     * device with more memory may return 24 or even higher numbers.
410     */
411    public int getMemoryClass() {
412        return staticGetMemoryClass();
413    }
414
415    /** @hide */
416    static public int staticGetMemoryClass() {
417        // Really brain dead right now -- just take this from the configured
418        // vm heap size, and assume it is in megabytes and thus ends with "m".
419        String vmHeapSize = SystemProperties.get("dalvik.vm.heapgrowthlimit", "");
420        if (vmHeapSize != null && !"".equals(vmHeapSize)) {
421            return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
422        }
423        return staticGetLargeMemoryClass();
424    }
425
426    /**
427     * Return the approximate per-application memory class of the current
428     * device when an application is running with a large heap.  This is the
429     * space available for memory-intensive applications; most applications
430     * should not need this amount of memory, and should instead stay with the
431     * {@link #getMemoryClass()} limit.  The returned value is in megabytes.
432     * This may be the same size as {@link #getMemoryClass()} on memory
433     * constrained devices, or it may be significantly larger on devices with
434     * a large amount of available RAM.
435     *
436     * <p>The is the size of the application's Dalvik heap if it has
437     * specified <code>android:largeHeap="true"</code> in its manifest.
438     */
439    public int getLargeMemoryClass() {
440        return staticGetLargeMemoryClass();
441    }
442
443    /** @hide */
444    static public int staticGetLargeMemoryClass() {
445        // Really brain dead right now -- just take this from the configured
446        // vm heap size, and assume it is in megabytes and thus ends with "m".
447        String vmHeapSize = SystemProperties.get("dalvik.vm.heapsize", "16m");
448        return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
449    }
450
451    /**
452     * Returns true if this is a low-RAM device.  Exactly whether a device is low-RAM
453     * is ultimately up to the device configuration, but currently it generally means
454     * something in the class of a 512MB device with about a 800x480 or less screen.
455     * This is mostly intended to be used by apps to determine whether they should turn
456     * off certain features that require more RAM.
457     */
458    public boolean isLowRamDevice() {
459        return isLowRamDeviceStatic();
460    }
461
462    /** @hide */
463    public static boolean isLowRamDeviceStatic() {
464        return "true".equals(SystemProperties.get("ro.config.low_ram", "false"));
465    }
466
467    /**
468     * Used by persistent processes to determine if they are running on a
469     * higher-end device so should be okay using hardware drawing acceleration
470     * (which tends to consume a lot more RAM).
471     * @hide
472     */
473    static public boolean isHighEndGfx() {
474        return !isLowRamDeviceStatic() &&
475                !Resources.getSystem().getBoolean(com.android.internal.R.bool.config_avoidGfxAccel);
476    }
477
478    /**
479     * Information you can set and retrieve about the current activity within the recent task list.
480     */
481    public static class TaskDescription implements Parcelable {
482        private String mLabel;
483        private Bitmap mIcon;
484        private int mColorPrimary;
485
486        /**
487         * Creates the TaskDescription to the specified values.
488         *
489         * @param label A label and description of the current state of this task.
490         * @param icon An icon that represents the current state of this task.
491         * @param colorPrimary A color to override the theme's primary color.  This color must be opaque.
492         */
493        public TaskDescription(String label, Bitmap icon, int colorPrimary) {
494            if ((colorPrimary != 0) && (Color.alpha(colorPrimary) != 255)) {
495                throw new RuntimeException("A TaskDescription's primary color should be opaque");
496            }
497
498            mLabel = label;
499            mIcon = icon;
500            mColorPrimary = colorPrimary;
501        }
502
503        /**
504         * Creates the TaskDescription to the specified values.
505         *
506         * @param label A label and description of the current state of this activity.
507         * @param icon An icon that represents the current state of this activity.
508         */
509        public TaskDescription(String label, Bitmap icon) {
510            this(label, icon, 0);
511        }
512
513        /**
514         * Creates the TaskDescription to the specified values.
515         *
516         * @param label A label and description of the current state of this activity.
517         */
518        public TaskDescription(String label) {
519            this(label, null, 0);
520        }
521
522        /**
523         * Creates an empty TaskDescription.
524         */
525        public TaskDescription() {
526            this(null, null, 0);
527        }
528
529        /**
530         * Creates a copy of another TaskDescription.
531         */
532        public TaskDescription(TaskDescription td) {
533            this(td.getLabel(), td.getIcon(), td.getPrimaryColor());
534        }
535
536        private TaskDescription(Parcel source) {
537            readFromParcel(source);
538        }
539
540        /**
541         * Sets the label for this task description.
542         * @hide
543         */
544        public void setLabel(String label) {
545            mLabel = label;
546        }
547
548        /**
549         * Sets the primary color for this task description.
550         * @hide
551         */
552        public void setPrimaryColor(int primaryColor) {
553            mColorPrimary = primaryColor;
554        }
555
556        /**
557         * Sets the icon for this task description.
558         * @hide
559         */
560        public void setIcon(Bitmap icon) {
561            mIcon = icon;
562        }
563
564        /**
565         * @return The label and description of the current state of this task.
566         */
567        public String getLabel() {
568            return mLabel;
569        }
570
571        /**
572         * @return The icon that represents the current state of this task.
573         */
574        public Bitmap getIcon() {
575            return mIcon;
576        }
577
578        /**
579         * @return The color override on the theme's primary color.
580         */
581        public int getPrimaryColor() {
582            return mColorPrimary;
583        }
584
585        @Override
586        public int describeContents() {
587            return 0;
588        }
589
590        @Override
591        public void writeToParcel(Parcel dest, int flags) {
592            if (mLabel == null) {
593                dest.writeInt(0);
594            } else {
595                dest.writeInt(1);
596                dest.writeString(mLabel);
597            }
598            if (mIcon == null) {
599                dest.writeInt(0);
600            } else {
601                dest.writeInt(1);
602                mIcon.writeToParcel(dest, 0);
603            }
604            dest.writeInt(mColorPrimary);
605        }
606
607        public void readFromParcel(Parcel source) {
608            mLabel = source.readInt() > 0 ? source.readString() : null;
609            mIcon = source.readInt() > 0 ? Bitmap.CREATOR.createFromParcel(source) : null;
610            mColorPrimary = source.readInt();
611        }
612
613        public static final Creator<TaskDescription> CREATOR
614                = new Creator<TaskDescription>() {
615            public TaskDescription createFromParcel(Parcel source) {
616                return new TaskDescription(source);
617            }
618            public TaskDescription[] newArray(int size) {
619                return new TaskDescription[size];
620            }
621        };
622
623        @Override
624        public String toString() {
625            return "TaskDescription Label: " + mLabel + " Icon: " + mIcon +
626                    " colorPrimary: " + mColorPrimary;
627        }
628    }
629
630    /**
631     * Information you can retrieve about tasks that the user has most recently
632     * started or visited.
633     */
634    public static class RecentTaskInfo implements Parcelable {
635        /**
636         * If this task is currently running, this is the identifier for it.
637         * If it is not running, this will be -1.
638         */
639        public int id;
640
641        /**
642         * The true identifier of this task, valid even if it is not running.
643         */
644        public int persistentId;
645
646        /**
647         * The original Intent used to launch the task.  You can use this
648         * Intent to re-launch the task (if it is no longer running) or bring
649         * the current task to the front.
650         */
651        public Intent baseIntent;
652
653        /**
654         * If this task was started from an alias, this is the actual
655         * activity component that was initially started; the component of
656         * the baseIntent in this case is the name of the actual activity
657         * implementation that the alias referred to.  Otherwise, this is null.
658         */
659        public ComponentName origActivity;
660
661        /**
662         * Description of the task's last state.
663         */
664        public CharSequence description;
665
666        /**
667         * The id of the ActivityStack this Task was on most recently.
668         * @hide
669         */
670        public int stackId;
671
672        /**
673         * The id of the user the task was running as.
674         * @hide
675         */
676        public int userId;
677
678        /**
679         * The first time this task was active.
680         * @hide
681         */
682        public long firstActiveTime;
683
684        /**
685         * The last time this task was active.
686         * @hide
687         */
688        public long lastActiveTime;
689
690        /**
691         * The recent activity values for the highest activity in the stack to have set the values.
692         * {@link Activity#setTaskDescription(android.app.ActivityManager.TaskDescription)}.
693         *
694         * @hide
695         */
696        public TaskDescription taskDescription;
697
698        /**
699         * Task affiliation for grouping with other tasks.
700         * @hide
701         */
702        public int affiliatedTaskId;
703
704        public RecentTaskInfo() {
705        }
706
707        @Override
708        public int describeContents() {
709            return 0;
710        }
711
712        @Override
713        public void writeToParcel(Parcel dest, int flags) {
714            dest.writeInt(id);
715            dest.writeInt(persistentId);
716            if (baseIntent != null) {
717                dest.writeInt(1);
718                baseIntent.writeToParcel(dest, 0);
719            } else {
720                dest.writeInt(0);
721            }
722            ComponentName.writeToParcel(origActivity, dest);
723            TextUtils.writeToParcel(description, dest,
724                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
725            if (taskDescription != null) {
726                dest.writeInt(1);
727                taskDescription.writeToParcel(dest, 0);
728            } else {
729                dest.writeInt(0);
730            }
731            dest.writeInt(stackId);
732            dest.writeInt(userId);
733            dest.writeLong(firstActiveTime);
734            dest.writeLong(lastActiveTime);
735            dest.writeInt(affiliatedTaskId);
736        }
737
738        public void readFromParcel(Parcel source) {
739            id = source.readInt();
740            persistentId = source.readInt();
741            baseIntent = source.readInt() > 0 ? Intent.CREATOR.createFromParcel(source) : null;
742            origActivity = ComponentName.readFromParcel(source);
743            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
744            taskDescription = source.readInt() > 0 ?
745                    TaskDescription.CREATOR.createFromParcel(source) : null;
746            stackId = source.readInt();
747            userId = source.readInt();
748            firstActiveTime = source.readLong();
749            lastActiveTime = source.readLong();
750            affiliatedTaskId = source.readInt();
751        }
752
753        public static final Creator<RecentTaskInfo> CREATOR
754                = new Creator<RecentTaskInfo>() {
755            public RecentTaskInfo createFromParcel(Parcel source) {
756                return new RecentTaskInfo(source);
757            }
758            public RecentTaskInfo[] newArray(int size) {
759                return new RecentTaskInfo[size];
760            }
761        };
762
763        private RecentTaskInfo(Parcel source) {
764            readFromParcel(source);
765        }
766    }
767
768    /**
769     * Flag for use with {@link #getRecentTasks}: return all tasks, even those
770     * that have set their
771     * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
772     */
773    public static final int RECENT_WITH_EXCLUDED = 0x0001;
774
775    /**
776     * Provides a list that does not contain any
777     * recent tasks that currently are not available to the user.
778     */
779    public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002;
780
781    /**
782     * Provides a list that contains recent tasks for all
783     * profiles of a user.
784     * @hide
785     */
786    public static final int RECENT_INCLUDE_PROFILES = 0x0004;
787
788    /**
789     * <p></p>Return a list of the tasks that the user has recently launched, with
790     * the most recent being first and older ones after in order.
791     *
792     * <p><b>Note: this method is only intended for debugging and presenting
793     * task management user interfaces</b>.  This should never be used for
794     * core logic in an application, such as deciding between different
795     * behaviors based on the information found here.  Such uses are
796     * <em>not</em> supported, and will likely break in the future.  For
797     * example, if multiple applications can be actively running at the
798     * same time, assumptions made about the meaning of the data here for
799     * purposes of control flow will be incorrect.</p>
800     *
801     * @deprecated As of {@link android.os.Build.VERSION_CODES#L}, this method is
802     * no longer available to third party applications: as the introduction of
803     * document-centric recents means
804     * it can leak personal information to the caller.  For backwards compatibility,
805     * it will still return a small subset of its data: at least the caller's
806     * own tasks (though see {@link #getAppTasks()} for the correct supported
807     * way to retrieve that information), and possibly some other tasks
808     * such as home that are known to not be sensitive.
809     *
810     * @param maxNum The maximum number of entries to return in the list.  The
811     * actual number returned may be smaller, depending on how many tasks the
812     * user has started and the maximum number the system can remember.
813     * @param flags Information about what to return.  May be any combination
814     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
815     *
816     * @return Returns a list of RecentTaskInfo records describing each of
817     * the recent tasks.
818     *
819     * @throws SecurityException Throws SecurityException if the caller does
820     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
821     */
822    @Deprecated
823    public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags)
824            throws SecurityException {
825        try {
826            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
827                    flags, UserHandle.myUserId());
828        } catch (RemoteException e) {
829            // System dead, we will be dead too soon!
830            return null;
831        }
832    }
833
834    /**
835     * Same as {@link #getRecentTasks(int, int)} but returns the recent tasks for a
836     * specific user. It requires holding
837     * the {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
838     * @param maxNum The maximum number of entries to return in the list.  The
839     * actual number returned may be smaller, depending on how many tasks the
840     * user has started and the maximum number the system can remember.
841     * @param flags Information about what to return.  May be any combination
842     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
843     *
844     * @return Returns a list of RecentTaskInfo records describing each of
845     * the recent tasks.
846     *
847     * @throws SecurityException Throws SecurityException if the caller does
848     * not hold the {@link android.Manifest.permission#GET_TASKS} or the
849     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permissions.
850     * @hide
851     */
852    public List<RecentTaskInfo> getRecentTasksForUser(int maxNum, int flags, int userId)
853            throws SecurityException {
854        try {
855            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
856                    flags, userId);
857        } catch (RemoteException e) {
858            // System dead, we will be dead too soon!
859            return null;
860        }
861    }
862
863    /**
864     * Information you can retrieve about a particular task that is currently
865     * "running" in the system.  Note that a running task does not mean the
866     * given task actually has a process it is actively running in; it simply
867     * means that the user has gone to it and never closed it, but currently
868     * the system may have killed its process and is only holding on to its
869     * last state in order to restart it when the user returns.
870     */
871    public static class RunningTaskInfo implements Parcelable {
872        /**
873         * A unique identifier for this task.
874         */
875        public int id;
876
877        /**
878         * The component launched as the first activity in the task.  This can
879         * be considered the "application" of this task.
880         */
881        public ComponentName baseActivity;
882
883        /**
884         * The activity component at the top of the history stack of the task.
885         * This is what the user is currently doing.
886         */
887        public ComponentName topActivity;
888
889        /**
890         * Thumbnail representation of the task's current state.  Currently
891         * always null.
892         */
893        public Bitmap thumbnail;
894
895        /**
896         * Description of the task's current state.
897         */
898        public CharSequence description;
899
900        /**
901         * Number of activities in this task.
902         */
903        public int numActivities;
904
905        /**
906         * Number of activities that are currently running (not stopped
907         * and persisted) in this task.
908         */
909        public int numRunning;
910
911        /**
912         * Last time task was run. For sorting.
913         * @hide
914         */
915        public long lastActiveTime;
916
917        public RunningTaskInfo() {
918        }
919
920        public int describeContents() {
921            return 0;
922        }
923
924        public void writeToParcel(Parcel dest, int flags) {
925            dest.writeInt(id);
926            ComponentName.writeToParcel(baseActivity, dest);
927            ComponentName.writeToParcel(topActivity, dest);
928            if (thumbnail != null) {
929                dest.writeInt(1);
930                thumbnail.writeToParcel(dest, 0);
931            } else {
932                dest.writeInt(0);
933            }
934            TextUtils.writeToParcel(description, dest,
935                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
936            dest.writeInt(numActivities);
937            dest.writeInt(numRunning);
938        }
939
940        public void readFromParcel(Parcel source) {
941            id = source.readInt();
942            baseActivity = ComponentName.readFromParcel(source);
943            topActivity = ComponentName.readFromParcel(source);
944            if (source.readInt() != 0) {
945                thumbnail = Bitmap.CREATOR.createFromParcel(source);
946            } else {
947                thumbnail = null;
948            }
949            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
950            numActivities = source.readInt();
951            numRunning = source.readInt();
952        }
953
954        public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
955            public RunningTaskInfo createFromParcel(Parcel source) {
956                return new RunningTaskInfo(source);
957            }
958            public RunningTaskInfo[] newArray(int size) {
959                return new RunningTaskInfo[size];
960            }
961        };
962
963        private RunningTaskInfo(Parcel source) {
964            readFromParcel(source);
965        }
966    }
967
968    /**
969     * Get the list of tasks associated with the calling application.
970     *
971     * @return The list of tasks associated with the application making this call.
972     * @throws SecurityException
973     */
974    public List<ActivityManager.AppTask> getAppTasks() {
975        ArrayList<AppTask> tasks = new ArrayList<AppTask>();
976        List<IAppTask> appTasks;
977        try {
978            appTasks = ActivityManagerNative.getDefault().getAppTasks();
979        } catch (RemoteException e) {
980            // System dead, we will be dead too soon!
981            return null;
982        }
983        int numAppTasks = appTasks.size();
984        for (int i = 0; i < numAppTasks; i++) {
985            tasks.add(new AppTask(appTasks.get(i)));
986        }
987        return tasks;
988    }
989
990    /**
991     * Return a list of the tasks that are currently running, with
992     * the most recent being first and older ones after in order.  Note that
993     * "running" does not mean any of the task's code is currently loaded or
994     * activity -- the task may have been frozen by the system, so that it
995     * can be restarted in its previous state when next brought to the
996     * foreground.
997     *
998     * <p><b>Note: this method is only intended for debugging and presenting
999     * task management user interfaces</b>.  This should never be used for
1000     * core logic in an application, such as deciding between different
1001     * behaviors based on the information found here.  Such uses are
1002     * <em>not</em> supported, and will likely break in the future.  For
1003     * example, if multiple applications can be actively running at the
1004     * same time, assumptions made about the meaning of the data here for
1005     * purposes of control flow will be incorrect.</p>
1006     *
1007     * @deprecated As of {@link android.os.Build.VERSION_CODES#L}, this method
1008     * is no longer available to third party
1009     * applications: the introduction of document-centric recents means
1010     * it can leak person information to the caller.  For backwards compatibility,
1011     * it will still retu rn a small subset of its data: at least the caller's
1012     * own tasks, and possibly some other tasks
1013     * such as home that are known to not be sensitive.
1014     *
1015     * @param maxNum The maximum number of entries to return in the list.  The
1016     * actual number returned may be smaller, depending on how many tasks the
1017     * user has started.
1018     *
1019     * @return Returns a list of RunningTaskInfo records describing each of
1020     * the running tasks.
1021     *
1022     * @throws SecurityException Throws SecurityException if the caller does
1023     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
1024     */
1025    @Deprecated
1026    public List<RunningTaskInfo> getRunningTasks(int maxNum)
1027            throws SecurityException {
1028        try {
1029            return ActivityManagerNative.getDefault().getTasks(maxNum, 0);
1030        } catch (RemoteException e) {
1031            // System dead, we will be dead too soon!
1032            return null;
1033        }
1034    }
1035
1036    /**
1037     * If set, the process of the root activity of the task will be killed
1038     * as part of removing the task.
1039     * @hide
1040     */
1041    public static final int REMOVE_TASK_KILL_PROCESS = 0x0001;
1042
1043    /**
1044     * Completely remove the given task.
1045     *
1046     * @param taskId Identifier of the task to be removed.
1047     * @param flags Additional operational flags.  May be 0 or
1048     * {@link #REMOVE_TASK_KILL_PROCESS}.
1049     * @return Returns true if the given task was found and removed.
1050     *
1051     * @hide
1052     */
1053    public boolean removeTask(int taskId, int flags)
1054            throws SecurityException {
1055        try {
1056            return ActivityManagerNative.getDefault().removeTask(taskId, flags);
1057        } catch (RemoteException e) {
1058            // System dead, we will be dead too soon!
1059            return false;
1060        }
1061    }
1062
1063    /** @hide */
1064    public static class TaskThumbnail implements Parcelable {
1065        public Bitmap mainThumbnail;
1066        public ParcelFileDescriptor thumbnailFileDescriptor;
1067
1068        public TaskThumbnail() {
1069        }
1070
1071        public int describeContents() {
1072            if (thumbnailFileDescriptor != null) {
1073                return thumbnailFileDescriptor.describeContents();
1074            }
1075            return 0;
1076        }
1077
1078        public void writeToParcel(Parcel dest, int flags) {
1079            if (mainThumbnail != null) {
1080                dest.writeInt(1);
1081                mainThumbnail.writeToParcel(dest, 0);
1082            } else {
1083                dest.writeInt(0);
1084            }
1085            if (thumbnailFileDescriptor != null) {
1086                dest.writeInt(1);
1087                thumbnailFileDescriptor.writeToParcel(dest, 0);
1088            } else {
1089                dest.writeInt(0);
1090            }
1091        }
1092
1093        public void readFromParcel(Parcel source) {
1094            if (source.readInt() != 0) {
1095                mainThumbnail = Bitmap.CREATOR.createFromParcel(source);
1096            } else {
1097                mainThumbnail = null;
1098            }
1099            if (source.readInt() != 0) {
1100                thumbnailFileDescriptor = ParcelFileDescriptor.CREATOR.createFromParcel(source);
1101            } else {
1102                thumbnailFileDescriptor = null;
1103            }
1104        }
1105
1106        public static final Creator<TaskThumbnail> CREATOR = new Creator<TaskThumbnail>() {
1107            public TaskThumbnail createFromParcel(Parcel source) {
1108                return new TaskThumbnail(source);
1109            }
1110            public TaskThumbnail[] newArray(int size) {
1111                return new TaskThumbnail[size];
1112            }
1113        };
1114
1115        private TaskThumbnail(Parcel source) {
1116            readFromParcel(source);
1117        }
1118    }
1119
1120    /** @hide */
1121    public TaskThumbnail getTaskThumbnail(int id) throws SecurityException {
1122        try {
1123            return ActivityManagerNative.getDefault().getTaskThumbnail(id);
1124        } catch (RemoteException e) {
1125            // System dead, we will be dead too soon!
1126            return null;
1127        }
1128    }
1129
1130    /** @hide */
1131    public boolean isInHomeStack(int taskId) {
1132        try {
1133            return ActivityManagerNative.getDefault().isInHomeStack(taskId);
1134        } catch (RemoteException e) {
1135            // System dead, we will be dead too soon!
1136            return false;
1137        }
1138    }
1139
1140    /**
1141     * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
1142     * activity along with the task, so it is positioned immediately behind
1143     * the task.
1144     */
1145    public static final int MOVE_TASK_WITH_HOME = 0x00000001;
1146
1147    /**
1148     * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
1149     * user-instigated action, so the current activity will not receive a
1150     * hint that the user is leaving.
1151     */
1152    public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
1153
1154    /**
1155     * Equivalent to calling {@link #moveTaskToFront(int, int, Bundle)}
1156     * with a null options argument.
1157     *
1158     * @param taskId The identifier of the task to be moved, as found in
1159     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
1160     * @param flags Additional operational flags, 0 or more of
1161     * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
1162     */
1163    public void moveTaskToFront(int taskId, int flags) {
1164        moveTaskToFront(taskId, flags, null);
1165    }
1166
1167    /**
1168     * Ask that the task associated with a given task ID be moved to the
1169     * front of the stack, so it is now visible to the user.  Requires that
1170     * the caller hold permission {@link android.Manifest.permission#REORDER_TASKS}
1171     * or a SecurityException will be thrown.
1172     *
1173     * @param taskId The identifier of the task to be moved, as found in
1174     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
1175     * @param flags Additional operational flags, 0 or more of
1176     * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
1177     * @param options Additional options for the operation, either null or
1178     * as per {@link Context#startActivity(Intent, android.os.Bundle)
1179     * Context.startActivity(Intent, Bundle)}.
1180     */
1181    public void moveTaskToFront(int taskId, int flags, Bundle options) {
1182        try {
1183            ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags, options);
1184        } catch (RemoteException e) {
1185            // System dead, we will be dead too soon!
1186        }
1187    }
1188
1189    /**
1190     * Information you can retrieve about a particular Service that is
1191     * currently running in the system.
1192     */
1193    public static class RunningServiceInfo implements Parcelable {
1194        /**
1195         * The service component.
1196         */
1197        public ComponentName service;
1198
1199        /**
1200         * If non-zero, this is the process the service is running in.
1201         */
1202        public int pid;
1203
1204        /**
1205         * The UID that owns this service.
1206         */
1207        public int uid;
1208
1209        /**
1210         * The name of the process this service runs in.
1211         */
1212        public String process;
1213
1214        /**
1215         * Set to true if the service has asked to run as a foreground process.
1216         */
1217        public boolean foreground;
1218
1219        /**
1220         * The time when the service was first made active, either by someone
1221         * starting or binding to it.  This
1222         * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
1223         */
1224        public long activeSince;
1225
1226        /**
1227         * Set to true if this service has been explicitly started.
1228         */
1229        public boolean started;
1230
1231        /**
1232         * Number of clients connected to the service.
1233         */
1234        public int clientCount;
1235
1236        /**
1237         * Number of times the service's process has crashed while the service
1238         * is running.
1239         */
1240        public int crashCount;
1241
1242        /**
1243         * The time when there was last activity in the service (either
1244         * explicit requests to start it or clients binding to it).  This
1245         * is in units of {@link android.os.SystemClock#uptimeMillis()}.
1246         */
1247        public long lastActivityTime;
1248
1249        /**
1250         * If non-zero, this service is not currently running, but scheduled to
1251         * restart at the given time.
1252         */
1253        public long restarting;
1254
1255        /**
1256         * Bit for {@link #flags}: set if this service has been
1257         * explicitly started.
1258         */
1259        public static final int FLAG_STARTED = 1<<0;
1260
1261        /**
1262         * Bit for {@link #flags}: set if the service has asked to
1263         * run as a foreground process.
1264         */
1265        public static final int FLAG_FOREGROUND = 1<<1;
1266
1267        /**
1268         * Bit for {@link #flags): set if the service is running in a
1269         * core system process.
1270         */
1271        public static final int FLAG_SYSTEM_PROCESS = 1<<2;
1272
1273        /**
1274         * Bit for {@link #flags): set if the service is running in a
1275         * persistent process.
1276         */
1277        public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
1278
1279        /**
1280         * Running flags.
1281         */
1282        public int flags;
1283
1284        /**
1285         * For special services that are bound to by system code, this is
1286         * the package that holds the binding.
1287         */
1288        public String clientPackage;
1289
1290        /**
1291         * For special services that are bound to by system code, this is
1292         * a string resource providing a user-visible label for who the
1293         * client is.
1294         */
1295        public int clientLabel;
1296
1297        public RunningServiceInfo() {
1298        }
1299
1300        public int describeContents() {
1301            return 0;
1302        }
1303
1304        public void writeToParcel(Parcel dest, int flags) {
1305            ComponentName.writeToParcel(service, dest);
1306            dest.writeInt(pid);
1307            dest.writeInt(uid);
1308            dest.writeString(process);
1309            dest.writeInt(foreground ? 1 : 0);
1310            dest.writeLong(activeSince);
1311            dest.writeInt(started ? 1 : 0);
1312            dest.writeInt(clientCount);
1313            dest.writeInt(crashCount);
1314            dest.writeLong(lastActivityTime);
1315            dest.writeLong(restarting);
1316            dest.writeInt(this.flags);
1317            dest.writeString(clientPackage);
1318            dest.writeInt(clientLabel);
1319        }
1320
1321        public void readFromParcel(Parcel source) {
1322            service = ComponentName.readFromParcel(source);
1323            pid = source.readInt();
1324            uid = source.readInt();
1325            process = source.readString();
1326            foreground = source.readInt() != 0;
1327            activeSince = source.readLong();
1328            started = source.readInt() != 0;
1329            clientCount = source.readInt();
1330            crashCount = source.readInt();
1331            lastActivityTime = source.readLong();
1332            restarting = source.readLong();
1333            flags = source.readInt();
1334            clientPackage = source.readString();
1335            clientLabel = source.readInt();
1336        }
1337
1338        public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
1339            public RunningServiceInfo createFromParcel(Parcel source) {
1340                return new RunningServiceInfo(source);
1341            }
1342            public RunningServiceInfo[] newArray(int size) {
1343                return new RunningServiceInfo[size];
1344            }
1345        };
1346
1347        private RunningServiceInfo(Parcel source) {
1348            readFromParcel(source);
1349        }
1350    }
1351
1352    /**
1353     * Return a list of the services that are currently running.
1354     *
1355     * <p><b>Note: this method is only intended for debugging or implementing
1356     * service management type user interfaces.</b></p>
1357     *
1358     * @param maxNum The maximum number of entries to return in the list.  The
1359     * actual number returned may be smaller, depending on how many services
1360     * are running.
1361     *
1362     * @return Returns a list of RunningServiceInfo records describing each of
1363     * the running tasks.
1364     */
1365    public List<RunningServiceInfo> getRunningServices(int maxNum)
1366            throws SecurityException {
1367        try {
1368            return ActivityManagerNative.getDefault()
1369                    .getServices(maxNum, 0);
1370        } catch (RemoteException e) {
1371            // System dead, we will be dead too soon!
1372            return null;
1373        }
1374    }
1375
1376    /**
1377     * Returns a PendingIntent you can start to show a control panel for the
1378     * given running service.  If the service does not have a control panel,
1379     * null is returned.
1380     */
1381    public PendingIntent getRunningServiceControlPanel(ComponentName service)
1382            throws SecurityException {
1383        try {
1384            return ActivityManagerNative.getDefault()
1385                    .getRunningServiceControlPanel(service);
1386        } catch (RemoteException e) {
1387            // System dead, we will be dead too soon!
1388            return null;
1389        }
1390    }
1391
1392    /**
1393     * Information you can retrieve about the available memory through
1394     * {@link ActivityManager#getMemoryInfo}.
1395     */
1396    public static class MemoryInfo implements Parcelable {
1397        /**
1398         * The available memory on the system.  This number should not
1399         * be considered absolute: due to the nature of the kernel, a significant
1400         * portion of this memory is actually in use and needed for the overall
1401         * system to run well.
1402         */
1403        public long availMem;
1404
1405        /**
1406         * The total memory accessible by the kernel.  This is basically the
1407         * RAM size of the device, not including below-kernel fixed allocations
1408         * like DMA buffers, RAM for the baseband CPU, etc.
1409         */
1410        public long totalMem;
1411
1412        /**
1413         * The threshold of {@link #availMem} at which we consider memory to be
1414         * low and start killing background services and other non-extraneous
1415         * processes.
1416         */
1417        public long threshold;
1418
1419        /**
1420         * Set to true if the system considers itself to currently be in a low
1421         * memory situation.
1422         */
1423        public boolean lowMemory;
1424
1425        /** @hide */
1426        public long hiddenAppThreshold;
1427        /** @hide */
1428        public long secondaryServerThreshold;
1429        /** @hide */
1430        public long visibleAppThreshold;
1431        /** @hide */
1432        public long foregroundAppThreshold;
1433
1434        public MemoryInfo() {
1435        }
1436
1437        public int describeContents() {
1438            return 0;
1439        }
1440
1441        public void writeToParcel(Parcel dest, int flags) {
1442            dest.writeLong(availMem);
1443            dest.writeLong(totalMem);
1444            dest.writeLong(threshold);
1445            dest.writeInt(lowMemory ? 1 : 0);
1446            dest.writeLong(hiddenAppThreshold);
1447            dest.writeLong(secondaryServerThreshold);
1448            dest.writeLong(visibleAppThreshold);
1449            dest.writeLong(foregroundAppThreshold);
1450        }
1451
1452        public void readFromParcel(Parcel source) {
1453            availMem = source.readLong();
1454            totalMem = source.readLong();
1455            threshold = source.readLong();
1456            lowMemory = source.readInt() != 0;
1457            hiddenAppThreshold = source.readLong();
1458            secondaryServerThreshold = source.readLong();
1459            visibleAppThreshold = source.readLong();
1460            foregroundAppThreshold = source.readLong();
1461        }
1462
1463        public static final Creator<MemoryInfo> CREATOR
1464                = new Creator<MemoryInfo>() {
1465            public MemoryInfo createFromParcel(Parcel source) {
1466                return new MemoryInfo(source);
1467            }
1468            public MemoryInfo[] newArray(int size) {
1469                return new MemoryInfo[size];
1470            }
1471        };
1472
1473        private MemoryInfo(Parcel source) {
1474            readFromParcel(source);
1475        }
1476    }
1477
1478    /**
1479     * Return general information about the memory state of the system.  This
1480     * can be used to help decide how to manage your own memory, though note
1481     * that polling is not recommended and
1482     * {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1483     * ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this.
1484     * Also see {@link #getMyMemoryState} for how to retrieve the current trim
1485     * level of your process as needed, which gives a better hint for how to
1486     * manage its memory.
1487     */
1488    public void getMemoryInfo(MemoryInfo outInfo) {
1489        try {
1490            ActivityManagerNative.getDefault().getMemoryInfo(outInfo);
1491        } catch (RemoteException e) {
1492        }
1493    }
1494
1495    /**
1496     * Information you can retrieve about an ActivityStack in the system.
1497     * @hide
1498     */
1499    public static class StackInfo implements Parcelable {
1500        public int stackId;
1501        public Rect bounds = new Rect();
1502        public int[] taskIds;
1503        public String[] taskNames;
1504        public int displayId;
1505
1506        @Override
1507        public int describeContents() {
1508            return 0;
1509        }
1510
1511        @Override
1512        public void writeToParcel(Parcel dest, int flags) {
1513            dest.writeInt(stackId);
1514            dest.writeInt(bounds.left);
1515            dest.writeInt(bounds.top);
1516            dest.writeInt(bounds.right);
1517            dest.writeInt(bounds.bottom);
1518            dest.writeIntArray(taskIds);
1519            dest.writeStringArray(taskNames);
1520            dest.writeInt(displayId);
1521        }
1522
1523        public void readFromParcel(Parcel source) {
1524            stackId = source.readInt();
1525            bounds = new Rect(
1526                    source.readInt(), source.readInt(), source.readInt(), source.readInt());
1527            taskIds = source.createIntArray();
1528            taskNames = source.createStringArray();
1529            displayId = source.readInt();
1530        }
1531
1532        public static final Creator<StackInfo> CREATOR = new Creator<StackInfo>() {
1533            @Override
1534            public StackInfo createFromParcel(Parcel source) {
1535                return new StackInfo(source);
1536            }
1537            @Override
1538            public StackInfo[] newArray(int size) {
1539                return new StackInfo[size];
1540            }
1541        };
1542
1543        public StackInfo() {
1544        }
1545
1546        private StackInfo(Parcel source) {
1547            readFromParcel(source);
1548        }
1549
1550        public String toString(String prefix) {
1551            StringBuilder sb = new StringBuilder(256);
1552            sb.append(prefix); sb.append("Stack id="); sb.append(stackId);
1553                    sb.append(" bounds="); sb.append(bounds.toShortString());
1554                    sb.append(" displayId="); sb.append(displayId);
1555                    sb.append("\n");
1556            prefix = prefix + "  ";
1557            for (int i = 0; i < taskIds.length; ++i) {
1558                sb.append(prefix); sb.append("taskId="); sb.append(taskIds[i]);
1559                        sb.append(": "); sb.append(taskNames[i]); sb.append("\n");
1560            }
1561            return sb.toString();
1562        }
1563
1564        @Override
1565        public String toString() {
1566            return toString("");
1567        }
1568    }
1569
1570    /**
1571     * @hide
1572     */
1573    public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
1574        try {
1575            return ActivityManagerNative.getDefault().clearApplicationUserData(packageName,
1576                    observer, UserHandle.myUserId());
1577        } catch (RemoteException e) {
1578            return false;
1579        }
1580    }
1581
1582    /**
1583     * Permits an application to erase its own data from disk.  This is equivalent to
1584     * the user choosing to clear the app's data from within the device settings UI.  It
1585     * erases all dynamic data associated with the app -- its private data and data in its
1586     * private area on external storage -- but does not remove the installed application
1587     * itself, nor any OBB files.
1588     *
1589     * @return {@code true} if the application successfully requested that the application's
1590     *     data be erased; {@code false} otherwise.
1591     */
1592    public boolean clearApplicationUserData() {
1593        return clearApplicationUserData(mContext.getPackageName(), null);
1594    }
1595
1596    /**
1597     * Information you can retrieve about any processes that are in an error condition.
1598     */
1599    public static class ProcessErrorStateInfo implements Parcelable {
1600        /**
1601         * Condition codes
1602         */
1603        public static final int NO_ERROR = 0;
1604        public static final int CRASHED = 1;
1605        public static final int NOT_RESPONDING = 2;
1606
1607        /**
1608         * The condition that the process is in.
1609         */
1610        public int condition;
1611
1612        /**
1613         * The process name in which the crash or error occurred.
1614         */
1615        public String processName;
1616
1617        /**
1618         * The pid of this process; 0 if none
1619         */
1620        public int pid;
1621
1622        /**
1623         * The kernel user-ID that has been assigned to this process;
1624         * currently this is not a unique ID (multiple applications can have
1625         * the same uid).
1626         */
1627        public int uid;
1628
1629        /**
1630         * The activity name associated with the error, if known.  May be null.
1631         */
1632        public String tag;
1633
1634        /**
1635         * A short message describing the error condition.
1636         */
1637        public String shortMsg;
1638
1639        /**
1640         * A long message describing the error condition.
1641         */
1642        public String longMsg;
1643
1644        /**
1645         * The stack trace where the error originated.  May be null.
1646         */
1647        public String stackTrace;
1648
1649        /**
1650         * to be deprecated: This value will always be null.
1651         */
1652        public byte[] crashData = null;
1653
1654        public ProcessErrorStateInfo() {
1655        }
1656
1657        @Override
1658        public int describeContents() {
1659            return 0;
1660        }
1661
1662        @Override
1663        public void writeToParcel(Parcel dest, int flags) {
1664            dest.writeInt(condition);
1665            dest.writeString(processName);
1666            dest.writeInt(pid);
1667            dest.writeInt(uid);
1668            dest.writeString(tag);
1669            dest.writeString(shortMsg);
1670            dest.writeString(longMsg);
1671            dest.writeString(stackTrace);
1672        }
1673
1674        public void readFromParcel(Parcel source) {
1675            condition = source.readInt();
1676            processName = source.readString();
1677            pid = source.readInt();
1678            uid = source.readInt();
1679            tag = source.readString();
1680            shortMsg = source.readString();
1681            longMsg = source.readString();
1682            stackTrace = source.readString();
1683        }
1684
1685        public static final Creator<ProcessErrorStateInfo> CREATOR =
1686                new Creator<ProcessErrorStateInfo>() {
1687            public ProcessErrorStateInfo createFromParcel(Parcel source) {
1688                return new ProcessErrorStateInfo(source);
1689            }
1690            public ProcessErrorStateInfo[] newArray(int size) {
1691                return new ProcessErrorStateInfo[size];
1692            }
1693        };
1694
1695        private ProcessErrorStateInfo(Parcel source) {
1696            readFromParcel(source);
1697        }
1698    }
1699
1700    /**
1701     * Returns a list of any processes that are currently in an error condition.  The result
1702     * will be null if all processes are running properly at this time.
1703     *
1704     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
1705     * current error conditions (it will not return an empty list).  This list ordering is not
1706     * specified.
1707     */
1708    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
1709        try {
1710            return ActivityManagerNative.getDefault().getProcessesInErrorState();
1711        } catch (RemoteException e) {
1712            return null;
1713        }
1714    }
1715
1716    /**
1717     * Information you can retrieve about a running process.
1718     */
1719    public static class RunningAppProcessInfo implements Parcelable {
1720        /**
1721         * The name of the process that this object is associated with
1722         */
1723        public String processName;
1724
1725        /**
1726         * The pid of this process; 0 if none
1727         */
1728        public int pid;
1729
1730        /**
1731         * The user id of this process.
1732         */
1733        public int uid;
1734
1735        /**
1736         * All packages that have been loaded into the process.
1737         */
1738        public String pkgList[];
1739
1740        /**
1741         * Constant for {@link #flags}: this is an app that is unable to
1742         * correctly save its state when going to the background,
1743         * so it can not be killed while in the background.
1744         * @hide
1745         */
1746        public static final int FLAG_CANT_SAVE_STATE = 1<<0;
1747
1748        /**
1749         * Constant for {@link #flags}: this process is associated with a
1750         * persistent system app.
1751         * @hide
1752         */
1753        public static final int FLAG_PERSISTENT = 1<<1;
1754
1755        /**
1756         * Constant for {@link #flags}: this process is associated with a
1757         * persistent system app.
1758         * @hide
1759         */
1760        public static final int FLAG_HAS_ACTIVITIES = 1<<2;
1761
1762        /**
1763         * Flags of information.  May be any of
1764         * {@link #FLAG_CANT_SAVE_STATE}.
1765         * @hide
1766         */
1767        public int flags;
1768
1769        /**
1770         * Last memory trim level reported to the process: corresponds to
1771         * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1772         * ComponentCallbacks2.onTrimMemory(int)}.
1773         */
1774        public int lastTrimLevel;
1775
1776        /**
1777         * Constant for {@link #importance}: this process is running the
1778         * foreground UI.
1779         */
1780        public static final int IMPORTANCE_FOREGROUND = 100;
1781
1782        /**
1783         * Constant for {@link #importance}: this process is running something
1784         * that is actively visible to the user, though not in the immediate
1785         * foreground.
1786         */
1787        public static final int IMPORTANCE_VISIBLE = 200;
1788
1789        /**
1790         * Constant for {@link #importance}: this process is running something
1791         * that is considered to be actively perceptible to the user.  An
1792         * example would be an application performing background music playback.
1793         */
1794        public static final int IMPORTANCE_PERCEPTIBLE = 130;
1795
1796        /**
1797         * Constant for {@link #importance}: this process is running an
1798         * application that can not save its state, and thus can't be killed
1799         * while in the background.
1800         * @hide
1801         */
1802        public static final int IMPORTANCE_CANT_SAVE_STATE = 170;
1803
1804        /**
1805         * Constant for {@link #importance}: this process is contains services
1806         * that should remain running.
1807         */
1808        public static final int IMPORTANCE_SERVICE = 300;
1809
1810        /**
1811         * Constant for {@link #importance}: this process process contains
1812         * background code that is expendable.
1813         */
1814        public static final int IMPORTANCE_BACKGROUND = 400;
1815
1816        /**
1817         * Constant for {@link #importance}: this process is empty of any
1818         * actively running code.
1819         */
1820        public static final int IMPORTANCE_EMPTY = 500;
1821
1822        /**
1823         * Constant for {@link #importance}: this process does not exist.
1824         */
1825        public static final int IMPORTANCE_GONE = 1000;
1826
1827        /** @hide */
1828        public static int procStateToImportance(int procState) {
1829            if (procState >= ActivityManager.PROCESS_STATE_HOME) {
1830                return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
1831            } else if (procState >= ActivityManager.PROCESS_STATE_SERVICE) {
1832                return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
1833            } else if (procState > ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
1834                return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
1835            } else if (procState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) {
1836                return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
1837            } else if (procState >= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
1838                return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
1839            } else {
1840                return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
1841            }
1842        }
1843
1844        /**
1845         * The relative importance level that the system places on this
1846         * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
1847         * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE},
1848         * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}.  These
1849         * constants are numbered so that "more important" values are always
1850         * smaller than "less important" values.
1851         */
1852        public int importance;
1853
1854        /**
1855         * An additional ordering within a particular {@link #importance}
1856         * category, providing finer-grained information about the relative
1857         * utility of processes within a category.  This number means nothing
1858         * except that a smaller values are more recently used (and thus
1859         * more important).  Currently an LRU value is only maintained for
1860         * the {@link #IMPORTANCE_BACKGROUND} category, though others may
1861         * be maintained in the future.
1862         */
1863        public int lru;
1864
1865        /**
1866         * Constant for {@link #importanceReasonCode}: nothing special has
1867         * been specified for the reason for this level.
1868         */
1869        public static final int REASON_UNKNOWN = 0;
1870
1871        /**
1872         * Constant for {@link #importanceReasonCode}: one of the application's
1873         * content providers is being used by another process.  The pid of
1874         * the client process is in {@link #importanceReasonPid} and the
1875         * target provider in this process is in
1876         * {@link #importanceReasonComponent}.
1877         */
1878        public static final int REASON_PROVIDER_IN_USE = 1;
1879
1880        /**
1881         * Constant for {@link #importanceReasonCode}: one of the application's
1882         * content providers is being used by another process.  The pid of
1883         * the client process is in {@link #importanceReasonPid} and the
1884         * target provider in this process is in
1885         * {@link #importanceReasonComponent}.
1886         */
1887        public static final int REASON_SERVICE_IN_USE = 2;
1888
1889        /**
1890         * The reason for {@link #importance}, if any.
1891         */
1892        public int importanceReasonCode;
1893
1894        /**
1895         * For the specified values of {@link #importanceReasonCode}, this
1896         * is the process ID of the other process that is a client of this
1897         * process.  This will be 0 if no other process is using this one.
1898         */
1899        public int importanceReasonPid;
1900
1901        /**
1902         * For the specified values of {@link #importanceReasonCode}, this
1903         * is the name of the component that is being used in this process.
1904         */
1905        public ComponentName importanceReasonComponent;
1906
1907        /**
1908         * When {@link #importanceReasonPid} is non-0, this is the importance
1909         * of the other pid. @hide
1910         */
1911        public int importanceReasonImportance;
1912
1913        /**
1914         * Current process state, as per PROCESS_STATE_* constants.
1915         * @hide
1916         */
1917        public int processState;
1918
1919        public RunningAppProcessInfo() {
1920            importance = IMPORTANCE_FOREGROUND;
1921            importanceReasonCode = REASON_UNKNOWN;
1922            processState = PROCESS_STATE_IMPORTANT_FOREGROUND;
1923        }
1924
1925        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
1926            processName = pProcessName;
1927            pid = pPid;
1928            pkgList = pArr;
1929        }
1930
1931        public int describeContents() {
1932            return 0;
1933        }
1934
1935        public void writeToParcel(Parcel dest, int flags) {
1936            dest.writeString(processName);
1937            dest.writeInt(pid);
1938            dest.writeInt(uid);
1939            dest.writeStringArray(pkgList);
1940            dest.writeInt(this.flags);
1941            dest.writeInt(lastTrimLevel);
1942            dest.writeInt(importance);
1943            dest.writeInt(lru);
1944            dest.writeInt(importanceReasonCode);
1945            dest.writeInt(importanceReasonPid);
1946            ComponentName.writeToParcel(importanceReasonComponent, dest);
1947            dest.writeInt(importanceReasonImportance);
1948            dest.writeInt(processState);
1949        }
1950
1951        public void readFromParcel(Parcel source) {
1952            processName = source.readString();
1953            pid = source.readInt();
1954            uid = source.readInt();
1955            pkgList = source.readStringArray();
1956            flags = source.readInt();
1957            lastTrimLevel = source.readInt();
1958            importance = source.readInt();
1959            lru = source.readInt();
1960            importanceReasonCode = source.readInt();
1961            importanceReasonPid = source.readInt();
1962            importanceReasonComponent = ComponentName.readFromParcel(source);
1963            importanceReasonImportance = source.readInt();
1964            processState = source.readInt();
1965        }
1966
1967        public static final Creator<RunningAppProcessInfo> CREATOR =
1968            new Creator<RunningAppProcessInfo>() {
1969            public RunningAppProcessInfo createFromParcel(Parcel source) {
1970                return new RunningAppProcessInfo(source);
1971            }
1972            public RunningAppProcessInfo[] newArray(int size) {
1973                return new RunningAppProcessInfo[size];
1974            }
1975        };
1976
1977        private RunningAppProcessInfo(Parcel source) {
1978            readFromParcel(source);
1979        }
1980    }
1981
1982    /**
1983     * Returns a list of application processes installed on external media
1984     * that are running on the device.
1985     *
1986     * <p><b>Note: this method is only intended for debugging or building
1987     * a user-facing process management UI.</b></p>
1988     *
1989     * @return Returns a list of ApplicationInfo records, or null if none
1990     * This list ordering is not specified.
1991     * @hide
1992     */
1993    public List<ApplicationInfo> getRunningExternalApplications() {
1994        try {
1995            return ActivityManagerNative.getDefault().getRunningExternalApplications();
1996        } catch (RemoteException e) {
1997            return null;
1998        }
1999    }
2000
2001    /**
2002     * Returns a list of application processes that are running on the device.
2003     *
2004     * <p><b>Note: this method is only intended for debugging or building
2005     * a user-facing process management UI.</b></p>
2006     *
2007     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
2008     * running processes (it will not return an empty list).  This list ordering is not
2009     * specified.
2010     */
2011    public List<RunningAppProcessInfo> getRunningAppProcesses() {
2012        try {
2013            return ActivityManagerNative.getDefault().getRunningAppProcesses();
2014        } catch (RemoteException e) {
2015            return null;
2016        }
2017    }
2018
2019    /**
2020     * Return global memory state information for the calling process.  This
2021     * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
2022     * only fields that will be filled in are
2023     * {@link RunningAppProcessInfo#pid},
2024     * {@link RunningAppProcessInfo#uid},
2025     * {@link RunningAppProcessInfo#lastTrimLevel},
2026     * {@link RunningAppProcessInfo#importance},
2027     * {@link RunningAppProcessInfo#lru}, and
2028     * {@link RunningAppProcessInfo#importanceReasonCode}.
2029     */
2030    static public void getMyMemoryState(RunningAppProcessInfo outState) {
2031        try {
2032            ActivityManagerNative.getDefault().getMyMemoryState(outState);
2033        } catch (RemoteException e) {
2034        }
2035    }
2036
2037    /**
2038     * Return information about the memory usage of one or more processes.
2039     *
2040     * <p><b>Note: this method is only intended for debugging or building
2041     * a user-facing process management UI.</b></p>
2042     *
2043     * @param pids The pids of the processes whose memory usage is to be
2044     * retrieved.
2045     * @return Returns an array of memory information, one for each
2046     * requested pid.
2047     */
2048    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
2049        try {
2050            return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids);
2051        } catch (RemoteException e) {
2052            return null;
2053        }
2054    }
2055
2056    /**
2057     * @deprecated This is now just a wrapper for
2058     * {@link #killBackgroundProcesses(String)}; the previous behavior here
2059     * is no longer available to applications because it allows them to
2060     * break other applications by removing their alarms, stopping their
2061     * services, etc.
2062     */
2063    @Deprecated
2064    public void restartPackage(String packageName) {
2065        killBackgroundProcesses(packageName);
2066    }
2067
2068    /**
2069     * Have the system immediately kill all background processes associated
2070     * with the given package.  This is the same as the kernel killing those
2071     * processes to reclaim memory; the system will take care of restarting
2072     * these processes in the future as needed.
2073     *
2074     * <p>You must hold the permission
2075     * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
2076     * call this method.
2077     *
2078     * @param packageName The name of the package whose processes are to
2079     * be killed.
2080     */
2081    public void killBackgroundProcesses(String packageName) {
2082        try {
2083            ActivityManagerNative.getDefault().killBackgroundProcesses(packageName,
2084                    UserHandle.myUserId());
2085        } catch (RemoteException e) {
2086        }
2087    }
2088
2089    /**
2090     * Have the system perform a force stop of everything associated with
2091     * the given application package.  All processes that share its uid
2092     * will be killed, all services it has running stopped, all activities
2093     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
2094     * broadcast will be sent, so that any of its registered alarms can
2095     * be stopped, notifications removed, etc.
2096     *
2097     * <p>You must hold the permission
2098     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
2099     * call this method.
2100     *
2101     * @param packageName The name of the package to be stopped.
2102     *
2103     * @hide This is not available to third party applications due to
2104     * it allowing them to break other applications by stopping their
2105     * services, removing their alarms, etc.
2106     */
2107    public void forceStopPackage(String packageName) {
2108        try {
2109            ActivityManagerNative.getDefault().forceStopPackage(packageName,
2110                    UserHandle.myUserId());
2111        } catch (RemoteException e) {
2112        }
2113    }
2114
2115    /**
2116     * Get the device configuration attributes.
2117     */
2118    public ConfigurationInfo getDeviceConfigurationInfo() {
2119        try {
2120            return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
2121        } catch (RemoteException e) {
2122        }
2123        return null;
2124    }
2125
2126    /**
2127     * Get the preferred density of icons for the launcher. This is used when
2128     * custom drawables are created (e.g., for shortcuts).
2129     *
2130     * @return density in terms of DPI
2131     */
2132    public int getLauncherLargeIconDensity() {
2133        final Resources res = mContext.getResources();
2134        final int density = res.getDisplayMetrics().densityDpi;
2135        final int sw = res.getConfiguration().smallestScreenWidthDp;
2136
2137        if (sw < 600) {
2138            // Smaller than approx 7" tablets, use the regular icon size.
2139            return density;
2140        }
2141
2142        switch (density) {
2143            case DisplayMetrics.DENSITY_LOW:
2144                return DisplayMetrics.DENSITY_MEDIUM;
2145            case DisplayMetrics.DENSITY_MEDIUM:
2146                return DisplayMetrics.DENSITY_HIGH;
2147            case DisplayMetrics.DENSITY_TV:
2148                return DisplayMetrics.DENSITY_XHIGH;
2149            case DisplayMetrics.DENSITY_HIGH:
2150                return DisplayMetrics.DENSITY_XHIGH;
2151            case DisplayMetrics.DENSITY_XHIGH:
2152                return DisplayMetrics.DENSITY_XXHIGH;
2153            case DisplayMetrics.DENSITY_XXHIGH:
2154                return DisplayMetrics.DENSITY_XHIGH * 2;
2155            default:
2156                // The density is some abnormal value.  Return some other
2157                // abnormal value that is a reasonable scaling of it.
2158                return (int)((density*1.5f)+.5f);
2159        }
2160    }
2161
2162    /**
2163     * Get the preferred launcher icon size. This is used when custom drawables
2164     * are created (e.g., for shortcuts).
2165     *
2166     * @return dimensions of square icons in terms of pixels
2167     */
2168    public int getLauncherLargeIconSize() {
2169        return getLauncherLargeIconSizeInner(mContext);
2170    }
2171
2172    static int getLauncherLargeIconSizeInner(Context context) {
2173        final Resources res = context.getResources();
2174        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
2175        final int sw = res.getConfiguration().smallestScreenWidthDp;
2176
2177        if (sw < 600) {
2178            // Smaller than approx 7" tablets, use the regular icon size.
2179            return size;
2180        }
2181
2182        final int density = res.getDisplayMetrics().densityDpi;
2183
2184        switch (density) {
2185            case DisplayMetrics.DENSITY_LOW:
2186                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
2187            case DisplayMetrics.DENSITY_MEDIUM:
2188                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
2189            case DisplayMetrics.DENSITY_TV:
2190                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
2191            case DisplayMetrics.DENSITY_HIGH:
2192                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
2193            case DisplayMetrics.DENSITY_XHIGH:
2194                return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
2195            case DisplayMetrics.DENSITY_XXHIGH:
2196                return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
2197            default:
2198                // The density is some abnormal value.  Return some other
2199                // abnormal value that is a reasonable scaling of it.
2200                return (int)((size*1.5f) + .5f);
2201        }
2202    }
2203
2204    /**
2205     * Returns "true" if the user interface is currently being messed with
2206     * by a monkey.
2207     */
2208    public static boolean isUserAMonkey() {
2209        try {
2210            return ActivityManagerNative.getDefault().isUserAMonkey();
2211        } catch (RemoteException e) {
2212        }
2213        return false;
2214    }
2215
2216    /**
2217     * Returns "true" if device is running in a test harness.
2218     */
2219    public static boolean isRunningInTestHarness() {
2220        return SystemProperties.getBoolean("ro.test_harness", false);
2221    }
2222
2223    /**
2224     * Returns the launch count of each installed package.
2225     *
2226     * @hide
2227     */
2228    /*public Map<String, Integer> getAllPackageLaunchCounts() {
2229        try {
2230            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
2231                    ServiceManager.getService("usagestats"));
2232            if (usageStatsService == null) {
2233                return new HashMap<String, Integer>();
2234            }
2235
2236            UsageStats.PackageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats(
2237                    ActivityThread.currentPackageName());
2238            if (allPkgUsageStats == null) {
2239                return new HashMap<String, Integer>();
2240            }
2241
2242            Map<String, Integer> launchCounts = new HashMap<String, Integer>();
2243            for (UsageStats.PackageStats pkgUsageStats : allPkgUsageStats) {
2244                launchCounts.put(pkgUsageStats.getPackageName(), pkgUsageStats.getLaunchCount());
2245            }
2246
2247            return launchCounts;
2248        } catch (RemoteException e) {
2249            Log.w(TAG, "Could not query launch counts", e);
2250            return new HashMap<String, Integer>();
2251        }
2252    }*/
2253
2254    /** @hide */
2255    public static int checkComponentPermission(String permission, int uid,
2256            int owningUid, boolean exported) {
2257        // Root, system server get to do everything.
2258        if (uid == 0 || uid == Process.SYSTEM_UID) {
2259            return PackageManager.PERMISSION_GRANTED;
2260        }
2261        // Isolated processes don't get any permissions.
2262        if (UserHandle.isIsolated(uid)) {
2263            return PackageManager.PERMISSION_DENIED;
2264        }
2265        // If there is a uid that owns whatever is being accessed, it has
2266        // blanket access to it regardless of the permissions it requires.
2267        if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
2268            return PackageManager.PERMISSION_GRANTED;
2269        }
2270        // If the target is not exported, then nobody else can get to it.
2271        if (!exported) {
2272            /*
2273            RuntimeException here = new RuntimeException("here");
2274            here.fillInStackTrace();
2275            Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
2276                    here);
2277            */
2278            return PackageManager.PERMISSION_DENIED;
2279        }
2280        if (permission == null) {
2281            return PackageManager.PERMISSION_GRANTED;
2282        }
2283        try {
2284            return AppGlobals.getPackageManager()
2285                    .checkUidPermission(permission, uid);
2286        } catch (RemoteException e) {
2287            // Should never happen, but if it does... deny!
2288            Slog.e(TAG, "PackageManager is dead?!?", e);
2289        }
2290        return PackageManager.PERMISSION_DENIED;
2291    }
2292
2293    /** @hide */
2294    public static int checkUidPermission(String permission, int uid) {
2295        try {
2296            return AppGlobals.getPackageManager()
2297                    .checkUidPermission(permission, uid);
2298        } catch (RemoteException e) {
2299            // Should never happen, but if it does... deny!
2300            Slog.e(TAG, "PackageManager is dead?!?", e);
2301        }
2302        return PackageManager.PERMISSION_DENIED;
2303    }
2304
2305    /**
2306     * @hide
2307     * Helper for dealing with incoming user arguments to system service calls.
2308     * Takes care of checking permissions and converting USER_CURRENT to the
2309     * actual current user.
2310     *
2311     * @param callingPid The pid of the incoming call, as per Binder.getCallingPid().
2312     * @param callingUid The uid of the incoming call, as per Binder.getCallingUid().
2313     * @param userId The user id argument supplied by the caller -- this is the user
2314     * they want to run as.
2315     * @param allowAll If true, we will allow USER_ALL.  This means you must be prepared
2316     * to get a USER_ALL returned and deal with it correctly.  If false,
2317     * an exception will be thrown if USER_ALL is supplied.
2318     * @param requireFull If true, the caller must hold
2319     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a
2320     * different user than their current process; otherwise they must hold
2321     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
2322     * @param name Optional textual name of the incoming call; only for generating error messages.
2323     * @param callerPackage Optional package name of caller; only for error messages.
2324     *
2325     * @return Returns the user ID that the call should run as.  Will always be a concrete
2326     * user number, unless <var>allowAll</var> is true in which case it could also be
2327     * USER_ALL.
2328     */
2329    public static int handleIncomingUser(int callingPid, int callingUid, int userId,
2330            boolean allowAll, boolean requireFull, String name, String callerPackage) {
2331        if (UserHandle.getUserId(callingUid) == userId) {
2332            return userId;
2333        }
2334        try {
2335            return ActivityManagerNative.getDefault().handleIncomingUser(callingPid,
2336                    callingUid, userId, allowAll, requireFull, name, callerPackage);
2337        } catch (RemoteException e) {
2338            throw new SecurityException("Failed calling activity manager", e);
2339        }
2340    }
2341
2342    /** @hide */
2343    public static int getCurrentUser() {
2344        UserInfo ui;
2345        try {
2346            ui = ActivityManagerNative.getDefault().getCurrentUser();
2347            return ui != null ? ui.id : 0;
2348        } catch (RemoteException e) {
2349            return 0;
2350        }
2351    }
2352
2353    /**
2354     * @param userid the user's id. Zero indicates the default user
2355     * @hide
2356     */
2357    public boolean switchUser(int userid) {
2358        try {
2359            return ActivityManagerNative.getDefault().switchUser(userid);
2360        } catch (RemoteException e) {
2361            return false;
2362        }
2363    }
2364
2365    /**
2366     * Return whether the given user is actively running.  This means that
2367     * the user is in the "started" state, not "stopped" -- it is currently
2368     * allowed to run code through scheduled alarms, receiving broadcasts,
2369     * etc.  A started user may be either the current foreground user or a
2370     * background user; the result here does not distinguish between the two.
2371     * @param userid the user's id. Zero indicates the default user.
2372     * @hide
2373     */
2374    public boolean isUserRunning(int userid) {
2375        try {
2376            return ActivityManagerNative.getDefault().isUserRunning(userid, false);
2377        } catch (RemoteException e) {
2378            return false;
2379        }
2380    }
2381
2382    /**
2383     * Perform a system dump of various state associated with the given application
2384     * package name.  This call blocks while the dump is being performed, so should
2385     * not be done on a UI thread.  The data will be written to the given file
2386     * descriptor as text.  An application must hold the
2387     * {@link android.Manifest.permission#DUMP} permission to make this call.
2388     * @param fd The file descriptor that the dump should be written to.  The file
2389     * descriptor is <em>not</em> closed by this function; the caller continues to
2390     * own it.
2391     * @param packageName The name of the package that is to be dumped.
2392     */
2393    public void dumpPackageState(FileDescriptor fd, String packageName) {
2394        dumpPackageStateStatic(fd, packageName);
2395    }
2396
2397    /**
2398     * @hide
2399     */
2400    public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) {
2401        FileOutputStream fout = new FileOutputStream(fd);
2402        PrintWriter pw = new FastPrintWriter(fout);
2403        dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] {
2404                "-a", "package", packageName });
2405        pw.println();
2406        dumpService(pw, fd, "meminfo", new String[] { "--local", packageName });
2407        pw.println();
2408        dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { "-a", packageName });
2409        pw.println();
2410        dumpService(pw, fd, "usagestats", new String[] { "--packages", packageName });
2411        pw.println();
2412        dumpService(pw, fd, "package", new String[] { packageName });
2413        pw.println();
2414        dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName });
2415        pw.flush();
2416    }
2417
2418    private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) {
2419        pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
2420        IBinder service = ServiceManager.checkService(name);
2421        if (service == null) {
2422            pw.println("  (Service not found)");
2423            return;
2424        }
2425        TransferPipe tp = null;
2426        try {
2427            pw.flush();
2428            tp = new TransferPipe();
2429            tp.setBufferPrefix("  ");
2430            service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args);
2431            tp.go(fd);
2432        } catch (Throwable e) {
2433            if (tp != null) {
2434                tp.kill();
2435            }
2436            pw.println("Failure dumping service:");
2437            e.printStackTrace(pw);
2438        }
2439    }
2440
2441    /**
2442     * @hide
2443     */
2444    public void startLockTaskMode(int taskId) {
2445        try {
2446            ActivityManagerNative.getDefault().startLockTaskMode(taskId);
2447        } catch (RemoteException e) {
2448        }
2449    }
2450
2451    /**
2452     * @hide
2453     */
2454    public void stopLockTaskMode() {
2455        try {
2456            ActivityManagerNative.getDefault().stopLockTaskMode();
2457        } catch (RemoteException e) {
2458        }
2459    }
2460
2461    /**
2462     * Return whether currently in lock task mode.  When in this mode
2463     * no new tasks can be created or switched to.
2464     *
2465     * @see Activity#startLockTask()
2466     */
2467    public boolean isInLockTaskMode() {
2468        try {
2469            return ActivityManagerNative.getDefault().isInLockTaskMode();
2470        } catch (RemoteException e) {
2471            return false;
2472        }
2473    }
2474
2475    /**
2476     * The AppTask allows you to manage your own application's tasks.
2477     * See {@link android.app.ActivityManager#getAppTasks()}
2478     */
2479    public static class AppTask {
2480        private IAppTask mAppTaskImpl;
2481
2482        /** @hide */
2483        public AppTask(IAppTask task) {
2484            mAppTaskImpl = task;
2485        }
2486
2487        /**
2488         * Finishes all activities in this task and removes it from the recent tasks list.
2489         */
2490        public void finishAndRemoveTask() {
2491            try {
2492                mAppTaskImpl.finishAndRemoveTask();
2493            } catch (RemoteException e) {
2494                Slog.e(TAG, "Invalid AppTask", e);
2495            }
2496        }
2497
2498        /**
2499         * Get the RecentTaskInfo associated with this task.
2500         *
2501         * @return The RecentTaskInfo for this task, or null if the task no longer exists.
2502         */
2503        public RecentTaskInfo getTaskInfo() {
2504            try {
2505                return mAppTaskImpl.getTaskInfo();
2506            } catch (RemoteException e) {
2507                Slog.e(TAG, "Invalid AppTask", e);
2508                return null;
2509            }
2510        }
2511    }
2512}
2513