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