ActivityManager.java revision 22132d7950e57603e14259a337d6461d8478f07a
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         */
701        public int affiliatedTaskId;
702
703        public RecentTaskInfo() {
704        }
705
706        @Override
707        public int describeContents() {
708            return 0;
709        }
710
711        @Override
712        public void writeToParcel(Parcel dest, int flags) {
713            dest.writeInt(id);
714            dest.writeInt(persistentId);
715            if (baseIntent != null) {
716                dest.writeInt(1);
717                baseIntent.writeToParcel(dest, 0);
718            } else {
719                dest.writeInt(0);
720            }
721            ComponentName.writeToParcel(origActivity, dest);
722            TextUtils.writeToParcel(description, dest,
723                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
724            if (taskDescription != null) {
725                dest.writeInt(1);
726                taskDescription.writeToParcel(dest, 0);
727            } else {
728                dest.writeInt(0);
729            }
730            dest.writeInt(stackId);
731            dest.writeInt(userId);
732            dest.writeLong(firstActiveTime);
733            dest.writeLong(lastActiveTime);
734            dest.writeInt(affiliatedTaskId);
735        }
736
737        public void readFromParcel(Parcel source) {
738            id = source.readInt();
739            persistentId = source.readInt();
740            baseIntent = source.readInt() > 0 ? Intent.CREATOR.createFromParcel(source) : null;
741            origActivity = ComponentName.readFromParcel(source);
742            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
743            taskDescription = source.readInt() > 0 ?
744                    TaskDescription.CREATOR.createFromParcel(source) : null;
745            stackId = source.readInt();
746            userId = source.readInt();
747            firstActiveTime = source.readLong();
748            lastActiveTime = source.readLong();
749            affiliatedTaskId = source.readInt();
750        }
751
752        public static final Creator<RecentTaskInfo> CREATOR
753                = new Creator<RecentTaskInfo>() {
754            public RecentTaskInfo createFromParcel(Parcel source) {
755                return new RecentTaskInfo(source);
756            }
757            public RecentTaskInfo[] newArray(int size) {
758                return new RecentTaskInfo[size];
759            }
760        };
761
762        private RecentTaskInfo(Parcel source) {
763            readFromParcel(source);
764        }
765    }
766
767    /**
768     * Flag for use with {@link #getRecentTasks}: return all tasks, even those
769     * that have set their
770     * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
771     */
772    public static final int RECENT_WITH_EXCLUDED = 0x0001;
773
774    /**
775     * Provides a list that does not contain any
776     * recent tasks that currently are not available to the user.
777     */
778    public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002;
779
780    /**
781     * Provides a list that contains recent tasks for all
782     * profiles of a user.
783     * @hide
784     */
785    public static final int RECENT_INCLUDE_PROFILES = 0x0004;
786
787    /**
788     * <p></p>Return a list of the tasks that the user has recently launched, with
789     * the most recent being first and older ones after in order.
790     *
791     * <p><b>Note: this method is only intended for debugging and presenting
792     * task management user interfaces</b>.  This should never be used for
793     * core logic in an application, such as deciding between different
794     * behaviors based on the information found here.  Such uses are
795     * <em>not</em> supported, and will likely break in the future.  For
796     * example, if multiple applications can be actively running at the
797     * same time, assumptions made about the meaning of the data here for
798     * purposes of control flow will be incorrect.</p>
799     *
800     * @deprecated As of {@link android.os.Build.VERSION_CODES#L}, this method is
801     * no longer available to third party applications: as the introduction of
802     * document-centric recents means
803     * it can leak personal information to the caller.  For backwards compatibility,
804     * it will still return a small subset of its data: at least the caller's
805     * own tasks (though see {@link #getAppTasks()} for the correct supported
806     * way to retrieve that information), and possibly some other tasks
807     * such as home that are known to not be sensitive.
808     *
809     * @param maxNum The maximum number of entries to return in the list.  The
810     * actual number returned may be smaller, depending on how many tasks the
811     * user has started and the maximum number the system can remember.
812     * @param flags Information about what to return.  May be any combination
813     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
814     *
815     * @return Returns a list of RecentTaskInfo records describing each of
816     * the recent tasks.
817     *
818     * @throws SecurityException Throws SecurityException if the caller does
819     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
820     */
821    @Deprecated
822    public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags)
823            throws SecurityException {
824        try {
825            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
826                    flags, UserHandle.myUserId());
827        } catch (RemoteException e) {
828            // System dead, we will be dead too soon!
829            return null;
830        }
831    }
832
833    /**
834     * Same as {@link #getRecentTasks(int, int)} but returns the recent tasks for a
835     * specific user. It requires holding
836     * the {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
837     * @param maxNum The maximum number of entries to return in the list.  The
838     * actual number returned may be smaller, depending on how many tasks the
839     * user has started and the maximum number the system can remember.
840     * @param flags Information about what to return.  May be any combination
841     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
842     *
843     * @return Returns a list of RecentTaskInfo records describing each of
844     * the recent tasks.
845     *
846     * @throws SecurityException Throws SecurityException if the caller does
847     * not hold the {@link android.Manifest.permission#GET_TASKS} or the
848     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permissions.
849     * @hide
850     */
851    public List<RecentTaskInfo> getRecentTasksForUser(int maxNum, int flags, int userId)
852            throws SecurityException {
853        try {
854            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
855                    flags, userId);
856        } catch (RemoteException e) {
857            // System dead, we will be dead too soon!
858            return null;
859        }
860    }
861
862    /**
863     * Information you can retrieve about a particular task that is currently
864     * "running" in the system.  Note that a running task does not mean the
865     * given task actually has a process it is actively running in; it simply
866     * means that the user has gone to it and never closed it, but currently
867     * the system may have killed its process and is only holding on to its
868     * last state in order to restart it when the user returns.
869     */
870    public static class RunningTaskInfo implements Parcelable {
871        /**
872         * A unique identifier for this task.
873         */
874        public int id;
875
876        /**
877         * The component launched as the first activity in the task.  This can
878         * be considered the "application" of this task.
879         */
880        public ComponentName baseActivity;
881
882        /**
883         * The activity component at the top of the history stack of the task.
884         * This is what the user is currently doing.
885         */
886        public ComponentName topActivity;
887
888        /**
889         * Thumbnail representation of the task's current state.  Currently
890         * always null.
891         */
892        public Bitmap thumbnail;
893
894        /**
895         * Description of the task's current state.
896         */
897        public CharSequence description;
898
899        /**
900         * Number of activities in this task.
901         */
902        public int numActivities;
903
904        /**
905         * Number of activities that are currently running (not stopped
906         * and persisted) in this task.
907         */
908        public int numRunning;
909
910        /**
911         * Last time task was run. For sorting.
912         * @hide
913         */
914        public long lastActiveTime;
915
916        public RunningTaskInfo() {
917        }
918
919        public int describeContents() {
920            return 0;
921        }
922
923        public void writeToParcel(Parcel dest, int flags) {
924            dest.writeInt(id);
925            ComponentName.writeToParcel(baseActivity, dest);
926            ComponentName.writeToParcel(topActivity, dest);
927            if (thumbnail != null) {
928                dest.writeInt(1);
929                thumbnail.writeToParcel(dest, 0);
930            } else {
931                dest.writeInt(0);
932            }
933            TextUtils.writeToParcel(description, dest,
934                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
935            dest.writeInt(numActivities);
936            dest.writeInt(numRunning);
937        }
938
939        public void readFromParcel(Parcel source) {
940            id = source.readInt();
941            baseActivity = ComponentName.readFromParcel(source);
942            topActivity = ComponentName.readFromParcel(source);
943            if (source.readInt() != 0) {
944                thumbnail = Bitmap.CREATOR.createFromParcel(source);
945            } else {
946                thumbnail = null;
947            }
948            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
949            numActivities = source.readInt();
950            numRunning = source.readInt();
951        }
952
953        public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
954            public RunningTaskInfo createFromParcel(Parcel source) {
955                return new RunningTaskInfo(source);
956            }
957            public RunningTaskInfo[] newArray(int size) {
958                return new RunningTaskInfo[size];
959            }
960        };
961
962        private RunningTaskInfo(Parcel source) {
963            readFromParcel(source);
964        }
965    }
966
967    /**
968     * Get the list of tasks associated with the calling application.
969     *
970     * @return The list of tasks associated with the application making this call.
971     * @throws SecurityException
972     */
973    public List<ActivityManager.AppTask> getAppTasks() {
974        ArrayList<AppTask> tasks = new ArrayList<AppTask>();
975        List<IAppTask> appTasks;
976        try {
977            appTasks = ActivityManagerNative.getDefault().getAppTasks();
978        } catch (RemoteException e) {
979            // System dead, we will be dead too soon!
980            return null;
981        }
982        int numAppTasks = appTasks.size();
983        for (int i = 0; i < numAppTasks; i++) {
984            tasks.add(new AppTask(appTasks.get(i)));
985        }
986        return tasks;
987    }
988
989    /**
990     * Return a list of the tasks that are currently running, with
991     * the most recent being first and older ones after in order.  Note that
992     * "running" does not mean any of the task's code is currently loaded or
993     * activity -- the task may have been frozen by the system, so that it
994     * can be restarted in its previous state when next brought to the
995     * foreground.
996     *
997     * <p><b>Note: this method is only intended for debugging and presenting
998     * task management user interfaces</b>.  This should never be used for
999     * core logic in an application, such as deciding between different
1000     * behaviors based on the information found here.  Such uses are
1001     * <em>not</em> supported, and will likely break in the future.  For
1002     * example, if multiple applications can be actively running at the
1003     * same time, assumptions made about the meaning of the data here for
1004     * purposes of control flow will be incorrect.</p>
1005     *
1006     * @deprecated As of {@link android.os.Build.VERSION_CODES#L}, this method
1007     * is no longer available to third party
1008     * applications: the introduction of document-centric recents means
1009     * it can leak person information to the caller.  For backwards compatibility,
1010     * it will still retu rn a small subset of its data: at least the caller's
1011     * own tasks, and possibly some other tasks
1012     * such as home that are known to not be sensitive.
1013     *
1014     * @param maxNum The maximum number of entries to return in the list.  The
1015     * actual number returned may be smaller, depending on how many tasks the
1016     * user has started.
1017     *
1018     * @return Returns a list of RunningTaskInfo records describing each of
1019     * the running tasks.
1020     *
1021     * @throws SecurityException Throws SecurityException if the caller does
1022     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
1023     */
1024    @Deprecated
1025    public List<RunningTaskInfo> getRunningTasks(int maxNum)
1026            throws SecurityException {
1027        try {
1028            return ActivityManagerNative.getDefault().getTasks(maxNum, 0);
1029        } catch (RemoteException e) {
1030            // System dead, we will be dead too soon!
1031            return null;
1032        }
1033    }
1034
1035    /**
1036     * If set, the process of the root activity of the task will be killed
1037     * as part of removing the task.
1038     * @hide
1039     */
1040    public static final int REMOVE_TASK_KILL_PROCESS = 0x0001;
1041
1042    /**
1043     * Completely remove the given task.
1044     *
1045     * @param taskId Identifier of the task to be removed.
1046     * @param flags Additional operational flags.  May be 0 or
1047     * {@link #REMOVE_TASK_KILL_PROCESS}.
1048     * @return Returns true if the given task was found and removed.
1049     *
1050     * @hide
1051     */
1052    public boolean removeTask(int taskId, int flags)
1053            throws SecurityException {
1054        try {
1055            return ActivityManagerNative.getDefault().removeTask(taskId, flags);
1056        } catch (RemoteException e) {
1057            // System dead, we will be dead too soon!
1058            return false;
1059        }
1060    }
1061
1062    /** @hide */
1063    public static class TaskThumbnail implements Parcelable {
1064        public Bitmap mainThumbnail;
1065        public ParcelFileDescriptor thumbnailFileDescriptor;
1066
1067        public TaskThumbnail() {
1068        }
1069
1070        public int describeContents() {
1071            if (thumbnailFileDescriptor != null) {
1072                return thumbnailFileDescriptor.describeContents();
1073            }
1074            return 0;
1075        }
1076
1077        public void writeToParcel(Parcel dest, int flags) {
1078            if (mainThumbnail != null) {
1079                dest.writeInt(1);
1080                mainThumbnail.writeToParcel(dest, 0);
1081            } else {
1082                dest.writeInt(0);
1083            }
1084            if (thumbnailFileDescriptor != null) {
1085                dest.writeInt(1);
1086                thumbnailFileDescriptor.writeToParcel(dest, 0);
1087            } else {
1088                dest.writeInt(0);
1089            }
1090        }
1091
1092        public void readFromParcel(Parcel source) {
1093            if (source.readInt() != 0) {
1094                mainThumbnail = Bitmap.CREATOR.createFromParcel(source);
1095            } else {
1096                mainThumbnail = null;
1097            }
1098            if (source.readInt() != 0) {
1099                thumbnailFileDescriptor = ParcelFileDescriptor.CREATOR.createFromParcel(source);
1100            } else {
1101                thumbnailFileDescriptor = null;
1102            }
1103        }
1104
1105        public static final Creator<TaskThumbnail> CREATOR = new Creator<TaskThumbnail>() {
1106            public TaskThumbnail createFromParcel(Parcel source) {
1107                return new TaskThumbnail(source);
1108            }
1109            public TaskThumbnail[] newArray(int size) {
1110                return new TaskThumbnail[size];
1111            }
1112        };
1113
1114        private TaskThumbnail(Parcel source) {
1115            readFromParcel(source);
1116        }
1117    }
1118
1119    /** @hide */
1120    public TaskThumbnail getTaskThumbnail(int id) throws SecurityException {
1121        try {
1122            return ActivityManagerNative.getDefault().getTaskThumbnail(id);
1123        } catch (RemoteException e) {
1124            // System dead, we will be dead too soon!
1125            return null;
1126        }
1127    }
1128
1129    /** @hide */
1130    public boolean isInHomeStack(int taskId) {
1131        try {
1132            return ActivityManagerNative.getDefault().isInHomeStack(taskId);
1133        } catch (RemoteException e) {
1134            // System dead, we will be dead too soon!
1135            return false;
1136        }
1137    }
1138
1139    /**
1140     * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
1141     * activity along with the task, so it is positioned immediately behind
1142     * the task.
1143     */
1144    public static final int MOVE_TASK_WITH_HOME = 0x00000001;
1145
1146    /**
1147     * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
1148     * user-instigated action, so the current activity will not receive a
1149     * hint that the user is leaving.
1150     */
1151    public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
1152
1153    /**
1154     * Equivalent to calling {@link #moveTaskToFront(int, int, Bundle)}
1155     * with a null options argument.
1156     *
1157     * @param taskId The identifier of the task to be moved, as found in
1158     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
1159     * @param flags Additional operational flags, 0 or more of
1160     * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
1161     */
1162    public void moveTaskToFront(int taskId, int flags) {
1163        moveTaskToFront(taskId, flags, null);
1164    }
1165
1166    /**
1167     * Ask that the task associated with a given task ID be moved to the
1168     * front of the stack, so it is now visible to the user.  Requires that
1169     * the caller hold permission {@link android.Manifest.permission#REORDER_TASKS}
1170     * or a SecurityException will be thrown.
1171     *
1172     * @param taskId The identifier of the task to be moved, as found in
1173     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
1174     * @param flags Additional operational flags, 0 or more of
1175     * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
1176     * @param options Additional options for the operation, either null or
1177     * as per {@link Context#startActivity(Intent, android.os.Bundle)
1178     * Context.startActivity(Intent, Bundle)}.
1179     */
1180    public void moveTaskToFront(int taskId, int flags, Bundle options) {
1181        try {
1182            ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags, options);
1183        } catch (RemoteException e) {
1184            // System dead, we will be dead too soon!
1185        }
1186    }
1187
1188    /**
1189     * Information you can retrieve about a particular Service that is
1190     * currently running in the system.
1191     */
1192    public static class RunningServiceInfo implements Parcelable {
1193        /**
1194         * The service component.
1195         */
1196        public ComponentName service;
1197
1198        /**
1199         * If non-zero, this is the process the service is running in.
1200         */
1201        public int pid;
1202
1203        /**
1204         * The UID that owns this service.
1205         */
1206        public int uid;
1207
1208        /**
1209         * The name of the process this service runs in.
1210         */
1211        public String process;
1212
1213        /**
1214         * Set to true if the service has asked to run as a foreground process.
1215         */
1216        public boolean foreground;
1217
1218        /**
1219         * The time when the service was first made active, either by someone
1220         * starting or binding to it.  This
1221         * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
1222         */
1223        public long activeSince;
1224
1225        /**
1226         * Set to true if this service has been explicitly started.
1227         */
1228        public boolean started;
1229
1230        /**
1231         * Number of clients connected to the service.
1232         */
1233        public int clientCount;
1234
1235        /**
1236         * Number of times the service's process has crashed while the service
1237         * is running.
1238         */
1239        public int crashCount;
1240
1241        /**
1242         * The time when there was last activity in the service (either
1243         * explicit requests to start it or clients binding to it).  This
1244         * is in units of {@link android.os.SystemClock#uptimeMillis()}.
1245         */
1246        public long lastActivityTime;
1247
1248        /**
1249         * If non-zero, this service is not currently running, but scheduled to
1250         * restart at the given time.
1251         */
1252        public long restarting;
1253
1254        /**
1255         * Bit for {@link #flags}: set if this service has been
1256         * explicitly started.
1257         */
1258        public static final int FLAG_STARTED = 1<<0;
1259
1260        /**
1261         * Bit for {@link #flags}: set if the service has asked to
1262         * run as a foreground process.
1263         */
1264        public static final int FLAG_FOREGROUND = 1<<1;
1265
1266        /**
1267         * Bit for {@link #flags): set if the service is running in a
1268         * core system process.
1269         */
1270        public static final int FLAG_SYSTEM_PROCESS = 1<<2;
1271
1272        /**
1273         * Bit for {@link #flags): set if the service is running in a
1274         * persistent process.
1275         */
1276        public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
1277
1278        /**
1279         * Running flags.
1280         */
1281        public int flags;
1282
1283        /**
1284         * For special services that are bound to by system code, this is
1285         * the package that holds the binding.
1286         */
1287        public String clientPackage;
1288
1289        /**
1290         * For special services that are bound to by system code, this is
1291         * a string resource providing a user-visible label for who the
1292         * client is.
1293         */
1294        public int clientLabel;
1295
1296        public RunningServiceInfo() {
1297        }
1298
1299        public int describeContents() {
1300            return 0;
1301        }
1302
1303        public void writeToParcel(Parcel dest, int flags) {
1304            ComponentName.writeToParcel(service, dest);
1305            dest.writeInt(pid);
1306            dest.writeInt(uid);
1307            dest.writeString(process);
1308            dest.writeInt(foreground ? 1 : 0);
1309            dest.writeLong(activeSince);
1310            dest.writeInt(started ? 1 : 0);
1311            dest.writeInt(clientCount);
1312            dest.writeInt(crashCount);
1313            dest.writeLong(lastActivityTime);
1314            dest.writeLong(restarting);
1315            dest.writeInt(this.flags);
1316            dest.writeString(clientPackage);
1317            dest.writeInt(clientLabel);
1318        }
1319
1320        public void readFromParcel(Parcel source) {
1321            service = ComponentName.readFromParcel(source);
1322            pid = source.readInt();
1323            uid = source.readInt();
1324            process = source.readString();
1325            foreground = source.readInt() != 0;
1326            activeSince = source.readLong();
1327            started = source.readInt() != 0;
1328            clientCount = source.readInt();
1329            crashCount = source.readInt();
1330            lastActivityTime = source.readLong();
1331            restarting = source.readLong();
1332            flags = source.readInt();
1333            clientPackage = source.readString();
1334            clientLabel = source.readInt();
1335        }
1336
1337        public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
1338            public RunningServiceInfo createFromParcel(Parcel source) {
1339                return new RunningServiceInfo(source);
1340            }
1341            public RunningServiceInfo[] newArray(int size) {
1342                return new RunningServiceInfo[size];
1343            }
1344        };
1345
1346        private RunningServiceInfo(Parcel source) {
1347            readFromParcel(source);
1348        }
1349    }
1350
1351    /**
1352     * Return a list of the services that are currently running.
1353     *
1354     * <p><b>Note: this method is only intended for debugging or implementing
1355     * service management type user interfaces.</b></p>
1356     *
1357     * @param maxNum The maximum number of entries to return in the list.  The
1358     * actual number returned may be smaller, depending on how many services
1359     * are running.
1360     *
1361     * @return Returns a list of RunningServiceInfo records describing each of
1362     * the running tasks.
1363     */
1364    public List<RunningServiceInfo> getRunningServices(int maxNum)
1365            throws SecurityException {
1366        try {
1367            return ActivityManagerNative.getDefault()
1368                    .getServices(maxNum, 0);
1369        } catch (RemoteException e) {
1370            // System dead, we will be dead too soon!
1371            return null;
1372        }
1373    }
1374
1375    /**
1376     * Returns a PendingIntent you can start to show a control panel for the
1377     * given running service.  If the service does not have a control panel,
1378     * null is returned.
1379     */
1380    public PendingIntent getRunningServiceControlPanel(ComponentName service)
1381            throws SecurityException {
1382        try {
1383            return ActivityManagerNative.getDefault()
1384                    .getRunningServiceControlPanel(service);
1385        } catch (RemoteException e) {
1386            // System dead, we will be dead too soon!
1387            return null;
1388        }
1389    }
1390
1391    /**
1392     * Information you can retrieve about the available memory through
1393     * {@link ActivityManager#getMemoryInfo}.
1394     */
1395    public static class MemoryInfo implements Parcelable {
1396        /**
1397         * The available memory on the system.  This number should not
1398         * be considered absolute: due to the nature of the kernel, a significant
1399         * portion of this memory is actually in use and needed for the overall
1400         * system to run well.
1401         */
1402        public long availMem;
1403
1404        /**
1405         * The total memory accessible by the kernel.  This is basically the
1406         * RAM size of the device, not including below-kernel fixed allocations
1407         * like DMA buffers, RAM for the baseband CPU, etc.
1408         */
1409        public long totalMem;
1410
1411        /**
1412         * The threshold of {@link #availMem} at which we consider memory to be
1413         * low and start killing background services and other non-extraneous
1414         * processes.
1415         */
1416        public long threshold;
1417
1418        /**
1419         * Set to true if the system considers itself to currently be in a low
1420         * memory situation.
1421         */
1422        public boolean lowMemory;
1423
1424        /** @hide */
1425        public long hiddenAppThreshold;
1426        /** @hide */
1427        public long secondaryServerThreshold;
1428        /** @hide */
1429        public long visibleAppThreshold;
1430        /** @hide */
1431        public long foregroundAppThreshold;
1432
1433        public MemoryInfo() {
1434        }
1435
1436        public int describeContents() {
1437            return 0;
1438        }
1439
1440        public void writeToParcel(Parcel dest, int flags) {
1441            dest.writeLong(availMem);
1442            dest.writeLong(totalMem);
1443            dest.writeLong(threshold);
1444            dest.writeInt(lowMemory ? 1 : 0);
1445            dest.writeLong(hiddenAppThreshold);
1446            dest.writeLong(secondaryServerThreshold);
1447            dest.writeLong(visibleAppThreshold);
1448            dest.writeLong(foregroundAppThreshold);
1449        }
1450
1451        public void readFromParcel(Parcel source) {
1452            availMem = source.readLong();
1453            totalMem = source.readLong();
1454            threshold = source.readLong();
1455            lowMemory = source.readInt() != 0;
1456            hiddenAppThreshold = source.readLong();
1457            secondaryServerThreshold = source.readLong();
1458            visibleAppThreshold = source.readLong();
1459            foregroundAppThreshold = source.readLong();
1460        }
1461
1462        public static final Creator<MemoryInfo> CREATOR
1463                = new Creator<MemoryInfo>() {
1464            public MemoryInfo createFromParcel(Parcel source) {
1465                return new MemoryInfo(source);
1466            }
1467            public MemoryInfo[] newArray(int size) {
1468                return new MemoryInfo[size];
1469            }
1470        };
1471
1472        private MemoryInfo(Parcel source) {
1473            readFromParcel(source);
1474        }
1475    }
1476
1477    /**
1478     * Return general information about the memory state of the system.  This
1479     * can be used to help decide how to manage your own memory, though note
1480     * that polling is not recommended and
1481     * {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1482     * ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this.
1483     * Also see {@link #getMyMemoryState} for how to retrieve the current trim
1484     * level of your process as needed, which gives a better hint for how to
1485     * manage its memory.
1486     */
1487    public void getMemoryInfo(MemoryInfo outInfo) {
1488        try {
1489            ActivityManagerNative.getDefault().getMemoryInfo(outInfo);
1490        } catch (RemoteException e) {
1491        }
1492    }
1493
1494    /**
1495     * Information you can retrieve about an ActivityStack in the system.
1496     * @hide
1497     */
1498    public static class StackInfo implements Parcelable {
1499        public int stackId;
1500        public Rect bounds = new Rect();
1501        public int[] taskIds;
1502        public String[] taskNames;
1503        public int displayId;
1504
1505        @Override
1506        public int describeContents() {
1507            return 0;
1508        }
1509
1510        @Override
1511        public void writeToParcel(Parcel dest, int flags) {
1512            dest.writeInt(stackId);
1513            dest.writeInt(bounds.left);
1514            dest.writeInt(bounds.top);
1515            dest.writeInt(bounds.right);
1516            dest.writeInt(bounds.bottom);
1517            dest.writeIntArray(taskIds);
1518            dest.writeStringArray(taskNames);
1519            dest.writeInt(displayId);
1520        }
1521
1522        public void readFromParcel(Parcel source) {
1523            stackId = source.readInt();
1524            bounds = new Rect(
1525                    source.readInt(), source.readInt(), source.readInt(), source.readInt());
1526            taskIds = source.createIntArray();
1527            taskNames = source.createStringArray();
1528            displayId = source.readInt();
1529        }
1530
1531        public static final Creator<StackInfo> CREATOR = new Creator<StackInfo>() {
1532            @Override
1533            public StackInfo createFromParcel(Parcel source) {
1534                return new StackInfo(source);
1535            }
1536            @Override
1537            public StackInfo[] newArray(int size) {
1538                return new StackInfo[size];
1539            }
1540        };
1541
1542        public StackInfo() {
1543        }
1544
1545        private StackInfo(Parcel source) {
1546            readFromParcel(source);
1547        }
1548
1549        public String toString(String prefix) {
1550            StringBuilder sb = new StringBuilder(256);
1551            sb.append(prefix); sb.append("Stack id="); sb.append(stackId);
1552                    sb.append(" bounds="); sb.append(bounds.toShortString());
1553                    sb.append(" displayId="); sb.append(displayId);
1554                    sb.append("\n");
1555            prefix = prefix + "  ";
1556            for (int i = 0; i < taskIds.length; ++i) {
1557                sb.append(prefix); sb.append("taskId="); sb.append(taskIds[i]);
1558                        sb.append(": "); sb.append(taskNames[i]); sb.append("\n");
1559            }
1560            return sb.toString();
1561        }
1562
1563        @Override
1564        public String toString() {
1565            return toString("");
1566        }
1567    }
1568
1569    /**
1570     * @hide
1571     */
1572    public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
1573        try {
1574            return ActivityManagerNative.getDefault().clearApplicationUserData(packageName,
1575                    observer, UserHandle.myUserId());
1576        } catch (RemoteException e) {
1577            return false;
1578        }
1579    }
1580
1581    /**
1582     * Permits an application to erase its own data from disk.  This is equivalent to
1583     * the user choosing to clear the app's data from within the device settings UI.  It
1584     * erases all dynamic data associated with the app -- its private data and data in its
1585     * private area on external storage -- but does not remove the installed application
1586     * itself, nor any OBB files.
1587     *
1588     * @return {@code true} if the application successfully requested that the application's
1589     *     data be erased; {@code false} otherwise.
1590     */
1591    public boolean clearApplicationUserData() {
1592        return clearApplicationUserData(mContext.getPackageName(), null);
1593    }
1594
1595    /**
1596     * Information you can retrieve about any processes that are in an error condition.
1597     */
1598    public static class ProcessErrorStateInfo implements Parcelable {
1599        /**
1600         * Condition codes
1601         */
1602        public static final int NO_ERROR = 0;
1603        public static final int CRASHED = 1;
1604        public static final int NOT_RESPONDING = 2;
1605
1606        /**
1607         * The condition that the process is in.
1608         */
1609        public int condition;
1610
1611        /**
1612         * The process name in which the crash or error occurred.
1613         */
1614        public String processName;
1615
1616        /**
1617         * The pid of this process; 0 if none
1618         */
1619        public int pid;
1620
1621        /**
1622         * The kernel user-ID that has been assigned to this process;
1623         * currently this is not a unique ID (multiple applications can have
1624         * the same uid).
1625         */
1626        public int uid;
1627
1628        /**
1629         * The activity name associated with the error, if known.  May be null.
1630         */
1631        public String tag;
1632
1633        /**
1634         * A short message describing the error condition.
1635         */
1636        public String shortMsg;
1637
1638        /**
1639         * A long message describing the error condition.
1640         */
1641        public String longMsg;
1642
1643        /**
1644         * The stack trace where the error originated.  May be null.
1645         */
1646        public String stackTrace;
1647
1648        /**
1649         * to be deprecated: This value will always be null.
1650         */
1651        public byte[] crashData = null;
1652
1653        public ProcessErrorStateInfo() {
1654        }
1655
1656        @Override
1657        public int describeContents() {
1658            return 0;
1659        }
1660
1661        @Override
1662        public void writeToParcel(Parcel dest, int flags) {
1663            dest.writeInt(condition);
1664            dest.writeString(processName);
1665            dest.writeInt(pid);
1666            dest.writeInt(uid);
1667            dest.writeString(tag);
1668            dest.writeString(shortMsg);
1669            dest.writeString(longMsg);
1670            dest.writeString(stackTrace);
1671        }
1672
1673        public void readFromParcel(Parcel source) {
1674            condition = source.readInt();
1675            processName = source.readString();
1676            pid = source.readInt();
1677            uid = source.readInt();
1678            tag = source.readString();
1679            shortMsg = source.readString();
1680            longMsg = source.readString();
1681            stackTrace = source.readString();
1682        }
1683
1684        public static final Creator<ProcessErrorStateInfo> CREATOR =
1685                new Creator<ProcessErrorStateInfo>() {
1686            public ProcessErrorStateInfo createFromParcel(Parcel source) {
1687                return new ProcessErrorStateInfo(source);
1688            }
1689            public ProcessErrorStateInfo[] newArray(int size) {
1690                return new ProcessErrorStateInfo[size];
1691            }
1692        };
1693
1694        private ProcessErrorStateInfo(Parcel source) {
1695            readFromParcel(source);
1696        }
1697    }
1698
1699    /**
1700     * Returns a list of any processes that are currently in an error condition.  The result
1701     * will be null if all processes are running properly at this time.
1702     *
1703     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
1704     * current error conditions (it will not return an empty list).  This list ordering is not
1705     * specified.
1706     */
1707    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
1708        try {
1709            return ActivityManagerNative.getDefault().getProcessesInErrorState();
1710        } catch (RemoteException e) {
1711            return null;
1712        }
1713    }
1714
1715    /**
1716     * Information you can retrieve about a running process.
1717     */
1718    public static class RunningAppProcessInfo implements Parcelable {
1719        /**
1720         * The name of the process that this object is associated with
1721         */
1722        public String processName;
1723
1724        /**
1725         * The pid of this process; 0 if none
1726         */
1727        public int pid;
1728
1729        /**
1730         * The user id of this process.
1731         */
1732        public int uid;
1733
1734        /**
1735         * All packages that have been loaded into the process.
1736         */
1737        public String pkgList[];
1738
1739        /**
1740         * Constant for {@link #flags}: this is an app that is unable to
1741         * correctly save its state when going to the background,
1742         * so it can not be killed while in the background.
1743         * @hide
1744         */
1745        public static final int FLAG_CANT_SAVE_STATE = 1<<0;
1746
1747        /**
1748         * Constant for {@link #flags}: this process is associated with a
1749         * persistent system app.
1750         * @hide
1751         */
1752        public static final int FLAG_PERSISTENT = 1<<1;
1753
1754        /**
1755         * Constant for {@link #flags}: this process is associated with a
1756         * persistent system app.
1757         * @hide
1758         */
1759        public static final int FLAG_HAS_ACTIVITIES = 1<<2;
1760
1761        /**
1762         * Flags of information.  May be any of
1763         * {@link #FLAG_CANT_SAVE_STATE}.
1764         * @hide
1765         */
1766        public int flags;
1767
1768        /**
1769         * Last memory trim level reported to the process: corresponds to
1770         * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1771         * ComponentCallbacks2.onTrimMemory(int)}.
1772         */
1773        public int lastTrimLevel;
1774
1775        /**
1776         * Constant for {@link #importance}: this process is running the
1777         * foreground UI.
1778         */
1779        public static final int IMPORTANCE_FOREGROUND = 100;
1780
1781        /**
1782         * Constant for {@link #importance}: this process is running something
1783         * that is actively visible to the user, though not in the immediate
1784         * foreground.
1785         */
1786        public static final int IMPORTANCE_VISIBLE = 200;
1787
1788        /**
1789         * Constant for {@link #importance}: this process is running something
1790         * that is considered to be actively perceptible to the user.  An
1791         * example would be an application performing background music playback.
1792         */
1793        public static final int IMPORTANCE_PERCEPTIBLE = 130;
1794
1795        /**
1796         * Constant for {@link #importance}: this process is running an
1797         * application that can not save its state, and thus can't be killed
1798         * while in the background.
1799         * @hide
1800         */
1801        public static final int IMPORTANCE_CANT_SAVE_STATE = 170;
1802
1803        /**
1804         * Constant for {@link #importance}: this process is contains services
1805         * that should remain running.
1806         */
1807        public static final int IMPORTANCE_SERVICE = 300;
1808
1809        /**
1810         * Constant for {@link #importance}: this process process contains
1811         * background code that is expendable.
1812         */
1813        public static final int IMPORTANCE_BACKGROUND = 400;
1814
1815        /**
1816         * Constant for {@link #importance}: this process is empty of any
1817         * actively running code.
1818         */
1819        public static final int IMPORTANCE_EMPTY = 500;
1820
1821        /**
1822         * Constant for {@link #importance}: this process does not exist.
1823         */
1824        public static final int IMPORTANCE_GONE = 1000;
1825
1826        /** @hide */
1827        public static int procStateToImportance(int procState) {
1828            if (procState >= ActivityManager.PROCESS_STATE_HOME) {
1829                return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
1830            } else if (procState >= ActivityManager.PROCESS_STATE_SERVICE) {
1831                return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
1832            } else if (procState > ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
1833                return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
1834            } else if (procState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) {
1835                return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
1836            } else if (procState >= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
1837                return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
1838            } else {
1839                return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
1840            }
1841        }
1842
1843        /**
1844         * The relative importance level that the system places on this
1845         * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
1846         * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE},
1847         * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}.  These
1848         * constants are numbered so that "more important" values are always
1849         * smaller than "less important" values.
1850         */
1851        public int importance;
1852
1853        /**
1854         * An additional ordering within a particular {@link #importance}
1855         * category, providing finer-grained information about the relative
1856         * utility of processes within a category.  This number means nothing
1857         * except that a smaller values are more recently used (and thus
1858         * more important).  Currently an LRU value is only maintained for
1859         * the {@link #IMPORTANCE_BACKGROUND} category, though others may
1860         * be maintained in the future.
1861         */
1862        public int lru;
1863
1864        /**
1865         * Constant for {@link #importanceReasonCode}: nothing special has
1866         * been specified for the reason for this level.
1867         */
1868        public static final int REASON_UNKNOWN = 0;
1869
1870        /**
1871         * Constant for {@link #importanceReasonCode}: one of the application's
1872         * content providers is being used by another process.  The pid of
1873         * the client process is in {@link #importanceReasonPid} and the
1874         * target provider in this process is in
1875         * {@link #importanceReasonComponent}.
1876         */
1877        public static final int REASON_PROVIDER_IN_USE = 1;
1878
1879        /**
1880         * Constant for {@link #importanceReasonCode}: one of the application's
1881         * content providers is being used by another process.  The pid of
1882         * the client process is in {@link #importanceReasonPid} and the
1883         * target provider in this process is in
1884         * {@link #importanceReasonComponent}.
1885         */
1886        public static final int REASON_SERVICE_IN_USE = 2;
1887
1888        /**
1889         * The reason for {@link #importance}, if any.
1890         */
1891        public int importanceReasonCode;
1892
1893        /**
1894         * For the specified values of {@link #importanceReasonCode}, this
1895         * is the process ID of the other process that is a client of this
1896         * process.  This will be 0 if no other process is using this one.
1897         */
1898        public int importanceReasonPid;
1899
1900        /**
1901         * For the specified values of {@link #importanceReasonCode}, this
1902         * is the name of the component that is being used in this process.
1903         */
1904        public ComponentName importanceReasonComponent;
1905
1906        /**
1907         * When {@link #importanceReasonPid} is non-0, this is the importance
1908         * of the other pid. @hide
1909         */
1910        public int importanceReasonImportance;
1911
1912        /**
1913         * Current process state, as per PROCESS_STATE_* constants.
1914         * @hide
1915         */
1916        public int processState;
1917
1918        public RunningAppProcessInfo() {
1919            importance = IMPORTANCE_FOREGROUND;
1920            importanceReasonCode = REASON_UNKNOWN;
1921            processState = PROCESS_STATE_IMPORTANT_FOREGROUND;
1922        }
1923
1924        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
1925            processName = pProcessName;
1926            pid = pPid;
1927            pkgList = pArr;
1928        }
1929
1930        public int describeContents() {
1931            return 0;
1932        }
1933
1934        public void writeToParcel(Parcel dest, int flags) {
1935            dest.writeString(processName);
1936            dest.writeInt(pid);
1937            dest.writeInt(uid);
1938            dest.writeStringArray(pkgList);
1939            dest.writeInt(this.flags);
1940            dest.writeInt(lastTrimLevel);
1941            dest.writeInt(importance);
1942            dest.writeInt(lru);
1943            dest.writeInt(importanceReasonCode);
1944            dest.writeInt(importanceReasonPid);
1945            ComponentName.writeToParcel(importanceReasonComponent, dest);
1946            dest.writeInt(importanceReasonImportance);
1947            dest.writeInt(processState);
1948        }
1949
1950        public void readFromParcel(Parcel source) {
1951            processName = source.readString();
1952            pid = source.readInt();
1953            uid = source.readInt();
1954            pkgList = source.readStringArray();
1955            flags = source.readInt();
1956            lastTrimLevel = source.readInt();
1957            importance = source.readInt();
1958            lru = source.readInt();
1959            importanceReasonCode = source.readInt();
1960            importanceReasonPid = source.readInt();
1961            importanceReasonComponent = ComponentName.readFromParcel(source);
1962            importanceReasonImportance = source.readInt();
1963            processState = source.readInt();
1964        }
1965
1966        public static final Creator<RunningAppProcessInfo> CREATOR =
1967            new Creator<RunningAppProcessInfo>() {
1968            public RunningAppProcessInfo createFromParcel(Parcel source) {
1969                return new RunningAppProcessInfo(source);
1970            }
1971            public RunningAppProcessInfo[] newArray(int size) {
1972                return new RunningAppProcessInfo[size];
1973            }
1974        };
1975
1976        private RunningAppProcessInfo(Parcel source) {
1977            readFromParcel(source);
1978        }
1979    }
1980
1981    /**
1982     * Returns a list of application processes installed on external media
1983     * that are running on the device.
1984     *
1985     * <p><b>Note: this method is only intended for debugging or building
1986     * a user-facing process management UI.</b></p>
1987     *
1988     * @return Returns a list of ApplicationInfo records, or null if none
1989     * This list ordering is not specified.
1990     * @hide
1991     */
1992    public List<ApplicationInfo> getRunningExternalApplications() {
1993        try {
1994            return ActivityManagerNative.getDefault().getRunningExternalApplications();
1995        } catch (RemoteException e) {
1996            return null;
1997        }
1998    }
1999
2000    /**
2001     * Returns a list of application processes that are running on the device.
2002     *
2003     * <p><b>Note: this method is only intended for debugging or building
2004     * a user-facing process management UI.</b></p>
2005     *
2006     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
2007     * running processes (it will not return an empty list).  This list ordering is not
2008     * specified.
2009     */
2010    public List<RunningAppProcessInfo> getRunningAppProcesses() {
2011        try {
2012            return ActivityManagerNative.getDefault().getRunningAppProcesses();
2013        } catch (RemoteException e) {
2014            return null;
2015        }
2016    }
2017
2018    /**
2019     * Return global memory state information for the calling process.  This
2020     * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
2021     * only fields that will be filled in are
2022     * {@link RunningAppProcessInfo#pid},
2023     * {@link RunningAppProcessInfo#uid},
2024     * {@link RunningAppProcessInfo#lastTrimLevel},
2025     * {@link RunningAppProcessInfo#importance},
2026     * {@link RunningAppProcessInfo#lru}, and
2027     * {@link RunningAppProcessInfo#importanceReasonCode}.
2028     */
2029    static public void getMyMemoryState(RunningAppProcessInfo outState) {
2030        try {
2031            ActivityManagerNative.getDefault().getMyMemoryState(outState);
2032        } catch (RemoteException e) {
2033        }
2034    }
2035
2036    /**
2037     * Return information about the memory usage of one or more processes.
2038     *
2039     * <p><b>Note: this method is only intended for debugging or building
2040     * a user-facing process management UI.</b></p>
2041     *
2042     * @param pids The pids of the processes whose memory usage is to be
2043     * retrieved.
2044     * @return Returns an array of memory information, one for each
2045     * requested pid.
2046     */
2047    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
2048        try {
2049            return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids);
2050        } catch (RemoteException e) {
2051            return null;
2052        }
2053    }
2054
2055    /**
2056     * @deprecated This is now just a wrapper for
2057     * {@link #killBackgroundProcesses(String)}; the previous behavior here
2058     * is no longer available to applications because it allows them to
2059     * break other applications by removing their alarms, stopping their
2060     * services, etc.
2061     */
2062    @Deprecated
2063    public void restartPackage(String packageName) {
2064        killBackgroundProcesses(packageName);
2065    }
2066
2067    /**
2068     * Have the system immediately kill all background processes associated
2069     * with the given package.  This is the same as the kernel killing those
2070     * processes to reclaim memory; the system will take care of restarting
2071     * these processes in the future as needed.
2072     *
2073     * <p>You must hold the permission
2074     * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
2075     * call this method.
2076     *
2077     * @param packageName The name of the package whose processes are to
2078     * be killed.
2079     */
2080    public void killBackgroundProcesses(String packageName) {
2081        try {
2082            ActivityManagerNative.getDefault().killBackgroundProcesses(packageName,
2083                    UserHandle.myUserId());
2084        } catch (RemoteException e) {
2085        }
2086    }
2087
2088    /**
2089     * Have the system perform a force stop of everything associated with
2090     * the given application package.  All processes that share its uid
2091     * will be killed, all services it has running stopped, all activities
2092     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
2093     * broadcast will be sent, so that any of its registered alarms can
2094     * be stopped, notifications removed, etc.
2095     *
2096     * <p>You must hold the permission
2097     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
2098     * call this method.
2099     *
2100     * @param packageName The name of the package to be stopped.
2101     *
2102     * @hide This is not available to third party applications due to
2103     * it allowing them to break other applications by stopping their
2104     * services, removing their alarms, etc.
2105     */
2106    public void forceStopPackage(String packageName) {
2107        try {
2108            ActivityManagerNative.getDefault().forceStopPackage(packageName,
2109                    UserHandle.myUserId());
2110        } catch (RemoteException e) {
2111        }
2112    }
2113
2114    /**
2115     * Get the device configuration attributes.
2116     */
2117    public ConfigurationInfo getDeviceConfigurationInfo() {
2118        try {
2119            return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
2120        } catch (RemoteException e) {
2121        }
2122        return null;
2123    }
2124
2125    /**
2126     * Get the preferred density of icons for the launcher. This is used when
2127     * custom drawables are created (e.g., for shortcuts).
2128     *
2129     * @return density in terms of DPI
2130     */
2131    public int getLauncherLargeIconDensity() {
2132        final Resources res = mContext.getResources();
2133        final int density = res.getDisplayMetrics().densityDpi;
2134        final int sw = res.getConfiguration().smallestScreenWidthDp;
2135
2136        if (sw < 600) {
2137            // Smaller than approx 7" tablets, use the regular icon size.
2138            return density;
2139        }
2140
2141        switch (density) {
2142            case DisplayMetrics.DENSITY_LOW:
2143                return DisplayMetrics.DENSITY_MEDIUM;
2144            case DisplayMetrics.DENSITY_MEDIUM:
2145                return DisplayMetrics.DENSITY_HIGH;
2146            case DisplayMetrics.DENSITY_TV:
2147                return DisplayMetrics.DENSITY_XHIGH;
2148            case DisplayMetrics.DENSITY_HIGH:
2149                return DisplayMetrics.DENSITY_XHIGH;
2150            case DisplayMetrics.DENSITY_XHIGH:
2151                return DisplayMetrics.DENSITY_XXHIGH;
2152            case DisplayMetrics.DENSITY_XXHIGH:
2153                return DisplayMetrics.DENSITY_XHIGH * 2;
2154            default:
2155                // The density is some abnormal value.  Return some other
2156                // abnormal value that is a reasonable scaling of it.
2157                return (int)((density*1.5f)+.5f);
2158        }
2159    }
2160
2161    /**
2162     * Get the preferred launcher icon size. This is used when custom drawables
2163     * are created (e.g., for shortcuts).
2164     *
2165     * @return dimensions of square icons in terms of pixels
2166     */
2167    public int getLauncherLargeIconSize() {
2168        return getLauncherLargeIconSizeInner(mContext);
2169    }
2170
2171    static int getLauncherLargeIconSizeInner(Context context) {
2172        final Resources res = context.getResources();
2173        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
2174        final int sw = res.getConfiguration().smallestScreenWidthDp;
2175
2176        if (sw < 600) {
2177            // Smaller than approx 7" tablets, use the regular icon size.
2178            return size;
2179        }
2180
2181        final int density = res.getDisplayMetrics().densityDpi;
2182
2183        switch (density) {
2184            case DisplayMetrics.DENSITY_LOW:
2185                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
2186            case DisplayMetrics.DENSITY_MEDIUM:
2187                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
2188            case DisplayMetrics.DENSITY_TV:
2189                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
2190            case DisplayMetrics.DENSITY_HIGH:
2191                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
2192            case DisplayMetrics.DENSITY_XHIGH:
2193                return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
2194            case DisplayMetrics.DENSITY_XXHIGH:
2195                return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
2196            default:
2197                // The density is some abnormal value.  Return some other
2198                // abnormal value that is a reasonable scaling of it.
2199                return (int)((size*1.5f) + .5f);
2200        }
2201    }
2202
2203    /**
2204     * Returns "true" if the user interface is currently being messed with
2205     * by a monkey.
2206     */
2207    public static boolean isUserAMonkey() {
2208        try {
2209            return ActivityManagerNative.getDefault().isUserAMonkey();
2210        } catch (RemoteException e) {
2211        }
2212        return false;
2213    }
2214
2215    /**
2216     * Returns "true" if device is running in a test harness.
2217     */
2218    public static boolean isRunningInTestHarness() {
2219        return SystemProperties.getBoolean("ro.test_harness", false);
2220    }
2221
2222    /**
2223     * Returns the launch count of each installed package.
2224     *
2225     * @hide
2226     */
2227    /*public Map<String, Integer> getAllPackageLaunchCounts() {
2228        try {
2229            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
2230                    ServiceManager.getService("usagestats"));
2231            if (usageStatsService == null) {
2232                return new HashMap<String, Integer>();
2233            }
2234
2235            UsageStats.PackageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats(
2236                    ActivityThread.currentPackageName());
2237            if (allPkgUsageStats == null) {
2238                return new HashMap<String, Integer>();
2239            }
2240
2241            Map<String, Integer> launchCounts = new HashMap<String, Integer>();
2242            for (UsageStats.PackageStats pkgUsageStats : allPkgUsageStats) {
2243                launchCounts.put(pkgUsageStats.getPackageName(), pkgUsageStats.getLaunchCount());
2244            }
2245
2246            return launchCounts;
2247        } catch (RemoteException e) {
2248            Log.w(TAG, "Could not query launch counts", e);
2249            return new HashMap<String, Integer>();
2250        }
2251    }*/
2252
2253    /** @hide */
2254    public static int checkComponentPermission(String permission, int uid,
2255            int owningUid, boolean exported) {
2256        // Root, system server get to do everything.
2257        if (uid == 0 || uid == Process.SYSTEM_UID) {
2258            return PackageManager.PERMISSION_GRANTED;
2259        }
2260        // Isolated processes don't get any permissions.
2261        if (UserHandle.isIsolated(uid)) {
2262            return PackageManager.PERMISSION_DENIED;
2263        }
2264        // If there is a uid that owns whatever is being accessed, it has
2265        // blanket access to it regardless of the permissions it requires.
2266        if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
2267            return PackageManager.PERMISSION_GRANTED;
2268        }
2269        // If the target is not exported, then nobody else can get to it.
2270        if (!exported) {
2271            /*
2272            RuntimeException here = new RuntimeException("here");
2273            here.fillInStackTrace();
2274            Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
2275                    here);
2276            */
2277            return PackageManager.PERMISSION_DENIED;
2278        }
2279        if (permission == null) {
2280            return PackageManager.PERMISSION_GRANTED;
2281        }
2282        try {
2283            return AppGlobals.getPackageManager()
2284                    .checkUidPermission(permission, uid);
2285        } catch (RemoteException e) {
2286            // Should never happen, but if it does... deny!
2287            Slog.e(TAG, "PackageManager is dead?!?", e);
2288        }
2289        return PackageManager.PERMISSION_DENIED;
2290    }
2291
2292    /** @hide */
2293    public static int checkUidPermission(String permission, int uid) {
2294        try {
2295            return AppGlobals.getPackageManager()
2296                    .checkUidPermission(permission, uid);
2297        } catch (RemoteException e) {
2298            // Should never happen, but if it does... deny!
2299            Slog.e(TAG, "PackageManager is dead?!?", e);
2300        }
2301        return PackageManager.PERMISSION_DENIED;
2302    }
2303
2304    /**
2305     * @hide
2306     * Helper for dealing with incoming user arguments to system service calls.
2307     * Takes care of checking permissions and converting USER_CURRENT to the
2308     * actual current user.
2309     *
2310     * @param callingPid The pid of the incoming call, as per Binder.getCallingPid().
2311     * @param callingUid The uid of the incoming call, as per Binder.getCallingUid().
2312     * @param userId The user id argument supplied by the caller -- this is the user
2313     * they want to run as.
2314     * @param allowAll If true, we will allow USER_ALL.  This means you must be prepared
2315     * to get a USER_ALL returned and deal with it correctly.  If false,
2316     * an exception will be thrown if USER_ALL is supplied.
2317     * @param requireFull If true, the caller must hold
2318     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a
2319     * different user than their current process; otherwise they must hold
2320     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
2321     * @param name Optional textual name of the incoming call; only for generating error messages.
2322     * @param callerPackage Optional package name of caller; only for error messages.
2323     *
2324     * @return Returns the user ID that the call should run as.  Will always be a concrete
2325     * user number, unless <var>allowAll</var> is true in which case it could also be
2326     * USER_ALL.
2327     */
2328    public static int handleIncomingUser(int callingPid, int callingUid, int userId,
2329            boolean allowAll, boolean requireFull, String name, String callerPackage) {
2330        if (UserHandle.getUserId(callingUid) == userId) {
2331            return userId;
2332        }
2333        try {
2334            return ActivityManagerNative.getDefault().handleIncomingUser(callingPid,
2335                    callingUid, userId, allowAll, requireFull, name, callerPackage);
2336        } catch (RemoteException e) {
2337            throw new SecurityException("Failed calling activity manager", e);
2338        }
2339    }
2340
2341    /** @hide */
2342    public static int getCurrentUser() {
2343        UserInfo ui;
2344        try {
2345            ui = ActivityManagerNative.getDefault().getCurrentUser();
2346            return ui != null ? ui.id : 0;
2347        } catch (RemoteException e) {
2348            return 0;
2349        }
2350    }
2351
2352    /**
2353     * @param userid the user's id. Zero indicates the default user
2354     * @hide
2355     */
2356    public boolean switchUser(int userid) {
2357        try {
2358            return ActivityManagerNative.getDefault().switchUser(userid);
2359        } catch (RemoteException e) {
2360            return false;
2361        }
2362    }
2363
2364    /**
2365     * Return whether the given user is actively running.  This means that
2366     * the user is in the "started" state, not "stopped" -- it is currently
2367     * allowed to run code through scheduled alarms, receiving broadcasts,
2368     * etc.  A started user may be either the current foreground user or a
2369     * background user; the result here does not distinguish between the two.
2370     * @param userid the user's id. Zero indicates the default user.
2371     * @hide
2372     */
2373    public boolean isUserRunning(int userid) {
2374        try {
2375            return ActivityManagerNative.getDefault().isUserRunning(userid, false);
2376        } catch (RemoteException e) {
2377            return false;
2378        }
2379    }
2380
2381    /**
2382     * Perform a system dump of various state associated with the given application
2383     * package name.  This call blocks while the dump is being performed, so should
2384     * not be done on a UI thread.  The data will be written to the given file
2385     * descriptor as text.  An application must hold the
2386     * {@link android.Manifest.permission#DUMP} permission to make this call.
2387     * @param fd The file descriptor that the dump should be written to.  The file
2388     * descriptor is <em>not</em> closed by this function; the caller continues to
2389     * own it.
2390     * @param packageName The name of the package that is to be dumped.
2391     */
2392    public void dumpPackageState(FileDescriptor fd, String packageName) {
2393        dumpPackageStateStatic(fd, packageName);
2394    }
2395
2396    /**
2397     * @hide
2398     */
2399    public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) {
2400        FileOutputStream fout = new FileOutputStream(fd);
2401        PrintWriter pw = new FastPrintWriter(fout);
2402        dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] {
2403                "-a", "package", packageName });
2404        pw.println();
2405        dumpService(pw, fd, "meminfo", new String[] { "--local", packageName });
2406        pw.println();
2407        dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { "-a", packageName });
2408        pw.println();
2409        dumpService(pw, fd, "usagestats", new String[] { "--packages", packageName });
2410        pw.println();
2411        dumpService(pw, fd, "package", new String[] { packageName });
2412        pw.println();
2413        dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName });
2414        pw.flush();
2415    }
2416
2417    private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) {
2418        pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
2419        IBinder service = ServiceManager.checkService(name);
2420        if (service == null) {
2421            pw.println("  (Service not found)");
2422            return;
2423        }
2424        TransferPipe tp = null;
2425        try {
2426            pw.flush();
2427            tp = new TransferPipe();
2428            tp.setBufferPrefix("  ");
2429            service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args);
2430            tp.go(fd);
2431        } catch (Throwable e) {
2432            if (tp != null) {
2433                tp.kill();
2434            }
2435            pw.println("Failure dumping service:");
2436            e.printStackTrace(pw);
2437        }
2438    }
2439
2440    /**
2441     * @hide
2442     */
2443    public void startLockTaskMode(int taskId) {
2444        try {
2445            ActivityManagerNative.getDefault().startLockTaskMode(taskId);
2446        } catch (RemoteException e) {
2447        }
2448    }
2449
2450    /**
2451     * @hide
2452     */
2453    public void stopLockTaskMode() {
2454        try {
2455            ActivityManagerNative.getDefault().stopLockTaskMode();
2456        } catch (RemoteException e) {
2457        }
2458    }
2459
2460    /**
2461     * Return whether currently in lock task mode.  When in this mode
2462     * no new tasks can be created or switched to.
2463     *
2464     * @see Activity#startLockTask()
2465     */
2466    public boolean isInLockTaskMode() {
2467        try {
2468            return ActivityManagerNative.getDefault().isInLockTaskMode();
2469        } catch (RemoteException e) {
2470            return false;
2471        }
2472    }
2473
2474    /**
2475     * The AppTask allows you to manage your own application's tasks.
2476     * See {@link android.app.ActivityManager#getAppTasks()}
2477     */
2478    public static class AppTask {
2479        private IAppTask mAppTaskImpl;
2480
2481        /** @hide */
2482        public AppTask(IAppTask task) {
2483            mAppTaskImpl = task;
2484        }
2485
2486        /**
2487         * Finishes all activities in this task and removes it from the recent tasks list.
2488         */
2489        public void finishAndRemoveTask() {
2490            try {
2491                mAppTaskImpl.finishAndRemoveTask();
2492            } catch (RemoteException e) {
2493                Slog.e(TAG, "Invalid AppTask", e);
2494            }
2495        }
2496
2497        /**
2498         * Get the RecentTaskInfo associated with this task.
2499         *
2500         * @return The RecentTaskInfo for this task, or null if the task no longer exists.
2501         */
2502        public RecentTaskInfo getTaskInfo() {
2503            try {
2504                return mAppTaskImpl.getTaskInfo();
2505            } catch (RemoteException e) {
2506                Slog.e(TAG, "Invalid AppTask", e);
2507                return null;
2508            }
2509        }
2510    }
2511}
2512