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