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