ActivityManager.java revision 2ced3d531c6c5d82db59db79bf8f890fb7acf200
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.Manifest;
20import android.annotation.IntDef;
21import android.annotation.NonNull;
22import android.annotation.Nullable;
23import android.annotation.RequiresPermission;
24import android.annotation.SystemApi;
25import android.graphics.Canvas;
26import android.graphics.Matrix;
27import android.graphics.Point;
28import android.os.BatteryStats;
29import android.os.IBinder;
30import android.os.ParcelFileDescriptor;
31
32import android.util.Log;
33import com.android.internal.app.ProcessStats;
34import com.android.internal.os.TransferPipe;
35import com.android.internal.util.FastPrintWriter;
36
37import android.content.ComponentName;
38import android.content.Context;
39import android.content.Intent;
40import android.content.UriPermission;
41import android.content.pm.ApplicationInfo;
42import android.content.pm.ConfigurationInfo;
43import android.content.pm.IPackageDataObserver;
44import android.content.pm.PackageManager;
45import android.content.pm.ParceledListSlice;
46import android.content.pm.UserInfo;
47import android.content.res.Resources;
48import android.graphics.Bitmap;
49import android.graphics.Color;
50import android.graphics.Rect;
51import android.os.Bundle;
52import android.os.Debug;
53import android.os.Handler;
54import android.os.Parcel;
55import android.os.Parcelable;
56import android.os.Process;
57import android.os.RemoteException;
58import android.os.ServiceManager;
59import android.os.SystemProperties;
60import android.os.UserHandle;
61import android.text.TextUtils;
62import android.util.DisplayMetrics;
63import android.util.Size;
64import android.util.Slog;
65
66import org.xmlpull.v1.XmlSerializer;
67
68import java.io.FileDescriptor;
69import java.io.FileOutputStream;
70import java.io.IOException;
71import java.io.PrintWriter;
72import java.lang.annotation.Retention;
73import java.lang.annotation.RetentionPolicy;
74import java.util.ArrayList;
75import java.util.List;
76
77/**
78 * Interact with the overall activities running in the system.
79 */
80public class ActivityManager {
81    private static String TAG = "ActivityManager";
82
83    private static int gMaxRecentTasks = -1;
84
85    private final Context mContext;
86    private final Handler mHandler;
87
88    /**
89     * Defines acceptable types of bugreports.
90     * @hide
91     */
92    @Retention(RetentionPolicy.SOURCE)
93    @IntDef({
94            BUGREPORT_OPTION_FULL,
95            BUGREPORT_OPTION_INTERACTIVE,
96            BUGREPORT_OPTION_REMOTE
97    })
98    public @interface BugreportMode {}
99    /**
100     * Takes a bugreport without user interference (and hence causing less
101     * interference to the system), but includes all sections.
102     * @hide
103     */
104    public static final int BUGREPORT_OPTION_FULL = 0;
105    /**
106     * Allows user to monitor progress and enter additional data; might not include all
107     * sections.
108     * @hide
109     */
110    public static final int BUGREPORT_OPTION_INTERACTIVE = 1;
111    /**
112     * Takes a bugreport requested remotely by administrator of the Device Owner app,
113     * not the device's user.
114     * @hide
115     */
116    public static final int BUGREPORT_OPTION_REMOTE = 2;
117
118    /**
119     * <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code
120     * <meta-data>}</a> name for a 'home' Activity that declares a package that is to be
121     * uninstalled in lieu of the declaring one.  The package named here must be
122     * signed with the same certificate as the one declaring the {@code <meta-data>}.
123     */
124    public static final String META_HOME_ALTERNATE = "android.app.home.alternate";
125
126    /**
127     * Result for IActivityManager.startActivity: trying to start a background user
128     * activity that shouldn't be displayed for all users.
129     * @hide
130     */
131    public static final int START_NOT_CURRENT_USER_ACTIVITY = -8;
132
133    /**
134     * Result for IActivityManager.startActivity: trying to start an activity under voice
135     * control when that activity does not support the VOICE category.
136     * @hide
137     */
138    public static final int START_NOT_VOICE_COMPATIBLE = -7;
139
140    /**
141     * Result for IActivityManager.startActivity: an error where the
142     * start had to be canceled.
143     * @hide
144     */
145    public static final int START_CANCELED = -6;
146
147    /**
148     * Result for IActivityManager.startActivity: an error where the
149     * thing being started is not an activity.
150     * @hide
151     */
152    public static final int START_NOT_ACTIVITY = -5;
153
154    /**
155     * Result for IActivityManager.startActivity: an error where the
156     * caller does not have permission to start the activity.
157     * @hide
158     */
159    public static final int START_PERMISSION_DENIED = -4;
160
161    /**
162     * Result for IActivityManager.startActivity: an error where the
163     * caller has requested both to forward a result and to receive
164     * a result.
165     * @hide
166     */
167    public static final int START_FORWARD_AND_REQUEST_CONFLICT = -3;
168
169    /**
170     * Result for IActivityManager.startActivity: an error where the
171     * requested class is not found.
172     * @hide
173     */
174    public static final int START_CLASS_NOT_FOUND = -2;
175
176    /**
177     * Result for IActivityManager.startActivity: an error where the
178     * given Intent could not be resolved to an activity.
179     * @hide
180     */
181    public static final int START_INTENT_NOT_RESOLVED = -1;
182
183    /**
184     * Result for IActivityManaqer.startActivity: the activity was started
185     * successfully as normal.
186     * @hide
187     */
188    public static final int START_SUCCESS = 0;
189
190    /**
191     * Result for IActivityManaqer.startActivity: the caller asked that the Intent not
192     * be executed if it is the recipient, and that is indeed the case.
193     * @hide
194     */
195    public static final int START_RETURN_INTENT_TO_CALLER = 1;
196
197    /**
198     * Result for IActivityManaqer.startActivity: activity wasn't really started, but
199     * a task was simply brought to the foreground.
200     * @hide
201     */
202    public static final int START_TASK_TO_FRONT = 2;
203
204    /**
205     * Result for IActivityManaqer.startActivity: activity wasn't really started, but
206     * the given Intent was given to the existing top activity.
207     * @hide
208     */
209    public static final int START_DELIVERED_TO_TOP = 3;
210
211    /**
212     * Result for IActivityManaqer.startActivity: request was canceled because
213     * app switches are temporarily canceled to ensure the user's last request
214     * (such as pressing home) is performed.
215     * @hide
216     */
217    public static final int START_SWITCHES_CANCELED = 4;
218
219    /**
220     * Result for IActivityManaqer.startActivity: a new activity was attempted to be started
221     * while in Lock Task Mode.
222     * @hide
223     */
224    public static final int START_RETURN_LOCK_TASK_MODE_VIOLATION = 5;
225
226    /**
227     * Flag for IActivityManaqer.startActivity: do special start mode where
228     * a new activity is launched only if it is needed.
229     * @hide
230     */
231    public static final int START_FLAG_ONLY_IF_NEEDED = 1<<0;
232
233    /**
234     * Flag for IActivityManaqer.startActivity: launch the app for
235     * debugging.
236     * @hide
237     */
238    public static final int START_FLAG_DEBUG = 1<<1;
239
240    /**
241     * Flag for IActivityManaqer.startActivity: launch the app for
242     * allocation tracking.
243     * @hide
244     */
245    public static final int START_FLAG_TRACK_ALLOCATION = 1<<2;
246
247    /**
248     * Result for IActivityManaqer.broadcastIntent: success!
249     * @hide
250     */
251    public static final int BROADCAST_SUCCESS = 0;
252
253    /**
254     * Result for IActivityManaqer.broadcastIntent: attempt to broadcast
255     * a sticky intent without appropriate permission.
256     * @hide
257     */
258    public static final int BROADCAST_STICKY_CANT_HAVE_PERMISSION = -1;
259
260    /**
261     * Result for IActivityManager.broadcastIntent: trying to send a broadcast
262     * to a stopped user. Fail.
263     * @hide
264     */
265    public static final int BROADCAST_FAILED_USER_STOPPED = -2;
266
267    /**
268     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
269     * for a sendBroadcast operation.
270     * @hide
271     */
272    public static final int INTENT_SENDER_BROADCAST = 1;
273
274    /**
275     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
276     * for a startActivity operation.
277     * @hide
278     */
279    public static final int INTENT_SENDER_ACTIVITY = 2;
280
281    /**
282     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
283     * for an activity result operation.
284     * @hide
285     */
286    public static final int INTENT_SENDER_ACTIVITY_RESULT = 3;
287
288    /**
289     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
290     * for a startService operation.
291     * @hide
292     */
293    public static final int INTENT_SENDER_SERVICE = 4;
294
295    /** @hide User operation call: success! */
296    public static final int USER_OP_SUCCESS = 0;
297
298    /** @hide User operation call: given user id is not known. */
299    public static final int USER_OP_UNKNOWN_USER = -1;
300
301    /** @hide User operation call: given user id is the current user, can't be stopped. */
302    public static final int USER_OP_IS_CURRENT = -2;
303
304    /** @hide User operation call: system user can't be stopped. */
305    public static final int USER_OP_ERROR_IS_SYSTEM = -3;
306
307    /** @hide User operation call: one of related users cannot be stopped. */
308    public static final int USER_OP_ERROR_RELATED_USERS_CANNOT_STOP = -4;
309
310    /** @hide Process does not exist. */
311    public static final int PROCESS_STATE_NONEXISTENT = -1;
312
313    /** @hide Process is a persistent system process. */
314    public static final int PROCESS_STATE_PERSISTENT = 0;
315
316    /** @hide Process is a persistent system process and is doing UI. */
317    public static final int PROCESS_STATE_PERSISTENT_UI = 1;
318
319    /** @hide Process is hosting the current top activities.  Note that this covers
320     * all activities that are visible to the user. */
321    public static final int PROCESS_STATE_TOP = 2;
322
323    /** @hide Process is hosting a foreground service due to a system binding. */
324    public static final int PROCESS_STATE_BOUND_FOREGROUND_SERVICE = 3;
325
326    /** @hide Process is hosting a foreground service. */
327    public static final int PROCESS_STATE_FOREGROUND_SERVICE = 4;
328
329    /** @hide Same as {@link #PROCESS_STATE_TOP} but while device is sleeping. */
330    public static final int PROCESS_STATE_TOP_SLEEPING = 5;
331
332    /** @hide Process is important to the user, and something they are aware of. */
333    public static final int PROCESS_STATE_IMPORTANT_FOREGROUND = 6;
334
335    /** @hide Process is important to the user, but not something they are aware of. */
336    public static final int PROCESS_STATE_IMPORTANT_BACKGROUND = 7;
337
338    /** @hide Process is in the background running a backup/restore operation. */
339    public static final int PROCESS_STATE_BACKUP = 8;
340
341    /** @hide Process is in the background, but it can't restore its state so we want
342     * to try to avoid killing it. */
343    public static final int PROCESS_STATE_HEAVY_WEIGHT = 9;
344
345    /** @hide Process is in the background running a service.  Unlike oom_adj, this level
346     * is used for both the normal running in background state and the executing
347     * operations state. */
348    public static final int PROCESS_STATE_SERVICE = 10;
349
350    /** @hide Process is in the background running a receiver.   Note that from the
351     * perspective of oom_adj receivers run at a higher foreground level, but for our
352     * prioritization here that is not necessary and putting them below services means
353     * many fewer changes in some process states as they receive broadcasts. */
354    public static final int PROCESS_STATE_RECEIVER = 11;
355
356    /** @hide Process is in the background but hosts the home activity. */
357    public static final int PROCESS_STATE_HOME = 12;
358
359    /** @hide Process is in the background but hosts the last shown activity. */
360    public static final int PROCESS_STATE_LAST_ACTIVITY = 13;
361
362    /** @hide Process is being cached for later use and contains activities. */
363    public static final int PROCESS_STATE_CACHED_ACTIVITY = 14;
364
365    /** @hide Process is being cached for later use and is a client of another cached
366     * process that contains activities. */
367    public static final int PROCESS_STATE_CACHED_ACTIVITY_CLIENT = 15;
368
369    /** @hide Process is being cached for later use and is empty. */
370    public static final int PROCESS_STATE_CACHED_EMPTY = 16;
371
372    /** @hide Should this process state be considered a background state? */
373    public static final boolean isProcStateBackground(int procState) {
374        return procState >= PROCESS_STATE_BACKUP;
375    }
376
377    /** @hide requestType for assist context: only basic information. */
378    public static final int ASSIST_CONTEXT_BASIC = 0;
379
380    /** @hide requestType for assist context: generate full AssistStructure. */
381    public static final int ASSIST_CONTEXT_FULL = 1;
382
383    /** @hide Flag for registerUidObserver: report changes in process state. */
384    public static final int UID_OBSERVER_PROCSTATE = 1<<0;
385
386    /** @hide Flag for registerUidObserver: report uid gone. */
387    public static final int UID_OBSERVER_GONE = 1<<1;
388
389    /** @hide Flag for registerUidObserver: report uid has become idle. */
390    public static final int UID_OBSERVER_IDLE = 1<<2;
391
392    /** @hide Flag for registerUidObserver: report uid has become active. */
393    public static final int UID_OBSERVER_ACTIVE = 1<<3;
394
395    /** @hide Mode for {@link IActivityManager#getAppStartMode}: normal free-to-run operation. */
396    public static final int APP_START_MODE_NORMAL = 0;
397
398    /** @hide Mode for {@link IActivityManager#getAppStartMode}: delay running until later. */
399    public static final int APP_START_MODE_DELAYED = 1;
400
401    /** @hide Mode for {@link IActivityManager#getAppStartMode}: disable/cancel pending
402     * launches. */
403    public static final int APP_START_MODE_DISABLED = 2;
404
405    /**
406     * Lock task mode is not active.
407     */
408    public static final int LOCK_TASK_MODE_NONE = 0;
409
410    /**
411     * Full lock task mode is active.
412     */
413    public static final int LOCK_TASK_MODE_LOCKED = 1;
414
415    /**
416     * App pinning mode is active.
417     */
418    public static final int LOCK_TASK_MODE_PINNED = 2;
419
420    Point mAppTaskThumbnailSize;
421
422    /*package*/ ActivityManager(Context context, Handler handler) {
423        mContext = context;
424        mHandler = handler;
425    }
426
427    /**
428     * Screen compatibility mode: the application most always run in
429     * compatibility mode.
430     * @hide
431     */
432    public static final int COMPAT_MODE_ALWAYS = -1;
433
434    /**
435     * Screen compatibility mode: the application can never run in
436     * compatibility mode.
437     * @hide
438     */
439    public static final int COMPAT_MODE_NEVER = -2;
440
441    /**
442     * Screen compatibility mode: unknown.
443     * @hide
444     */
445    public static final int COMPAT_MODE_UNKNOWN = -3;
446
447    /**
448     * Screen compatibility mode: the application currently has compatibility
449     * mode disabled.
450     * @hide
451     */
452    public static final int COMPAT_MODE_DISABLED = 0;
453
454    /**
455     * Screen compatibility mode: the application currently has compatibility
456     * mode enabled.
457     * @hide
458     */
459    public static final int COMPAT_MODE_ENABLED = 1;
460
461    /**
462     * Screen compatibility mode: request to toggle the application's
463     * compatibility mode.
464     * @hide
465     */
466    public static final int COMPAT_MODE_TOGGLE = 2;
467
468    /** @hide */
469    public static class StackId {
470        /** Invalid stack ID. */
471        public static final int INVALID_STACK_ID = -1;
472
473        /** First static stack ID. */
474        public static final int FIRST_STATIC_STACK_ID = 0;
475
476        /** Home activity stack ID. */
477        public static final int HOME_STACK_ID = FIRST_STATIC_STACK_ID;
478
479        /** ID of stack where fullscreen activities are normally launched into. */
480        public static final int FULLSCREEN_WORKSPACE_STACK_ID = 1;
481
482        /** ID of stack where freeform/resized activities are normally launched into. */
483        public static final int FREEFORM_WORKSPACE_STACK_ID = FULLSCREEN_WORKSPACE_STACK_ID + 1;
484
485        /** ID of stack that occupies a dedicated region of the screen. */
486        public static final int DOCKED_STACK_ID = FREEFORM_WORKSPACE_STACK_ID + 1;
487
488        /** ID of stack that always on top (always visible) when it exist. */
489        public static final int PINNED_STACK_ID = DOCKED_STACK_ID + 1;
490
491        /** Last static stack stack ID. */
492        public static final int LAST_STATIC_STACK_ID = PINNED_STACK_ID;
493
494        /** Start of ID range used by stacks that are created dynamically. */
495        public static final int FIRST_DYNAMIC_STACK_ID = LAST_STATIC_STACK_ID + 1;
496
497        public static boolean isStaticStack(int stackId) {
498            return stackId >= FIRST_STATIC_STACK_ID && stackId <= LAST_STATIC_STACK_ID;
499        }
500
501        /**
502         * Returns true if the activities contained in the input stack display a shadow around
503         * their border.
504         */
505        public static boolean hasWindowShadow(int stackId) {
506            return stackId == FREEFORM_WORKSPACE_STACK_ID || stackId == PINNED_STACK_ID;
507        }
508
509        /**
510         * Returns true if the activities contained in the input stack display a decor view.
511         */
512        public static boolean hasWindowDecor(int stackId) {
513            return stackId == FREEFORM_WORKSPACE_STACK_ID;
514        }
515
516        /**
517         * Returns true if the tasks contained in the stack can be resized independently of the
518         * stack.
519         */
520        public static boolean isTaskResizeAllowed(int stackId) {
521            return stackId == FREEFORM_WORKSPACE_STACK_ID;
522        }
523
524        /** Returns true if the task bounds should persist across power cycles. */
525        public static boolean persistTaskBounds(int stackId) {
526            return stackId == FREEFORM_WORKSPACE_STACK_ID;
527        }
528
529        /**
530         * Returns true if dynamic stacks are allowed to be visible behind the input stack.
531         */
532        public static boolean isDynamicStacksVisibleBehindAllowed(int stackId) {
533            return stackId == PINNED_STACK_ID;
534        }
535
536        /**
537         * Returns true if we try to maintain focus in the current stack when the top activity
538         * finishes.
539         */
540        public static boolean keepFocusInStackIfPossible(int stackId) {
541            return stackId == FREEFORM_WORKSPACE_STACK_ID
542                    || stackId == DOCKED_STACK_ID || stackId == PINNED_STACK_ID;
543        }
544
545        /**
546         * Returns true if Stack size is affected by the docked stack changing size.
547         */
548        public static boolean isResizeableByDockedStack(int stackId) {
549            return isStaticStack(stackId) &&
550                    stackId != DOCKED_STACK_ID && stackId != PINNED_STACK_ID;
551        }
552
553        /**
554         * Returns true if the size of tasks in the input stack are affected by the docked stack
555         * changing size.
556         */
557        public static boolean isTaskResizeableByDockedStack(int stackId) {
558            return isStaticStack(stackId) && stackId != FREEFORM_WORKSPACE_STACK_ID
559                    && stackId != DOCKED_STACK_ID && stackId != PINNED_STACK_ID;
560        }
561
562        /**
563         * Returns true if the windows of tasks being moved to this stack should be preserved so
564         * there isn't a display gap.
565         */
566        public static boolean preserveWindowOnTaskMove(int stackId) {
567            return stackId == FULLSCREEN_WORKSPACE_STACK_ID
568                    || stackId == DOCKED_STACK_ID || stackId == PINNED_STACK_ID;
569        }
570
571        /**
572         * Returns true if animation specs should be constructed for app transition that moves
573         * the task to the specified stack.
574         */
575        public static boolean useAnimationSpecForAppTransition(int stackId) {
576            return stackId == FREEFORM_WORKSPACE_STACK_ID
577                    || stackId == FULLSCREEN_WORKSPACE_STACK_ID || stackId == DOCKED_STACK_ID;
578        }
579
580        /** Returns true if the windows in the stack can receive input keys. */
581        public static boolean canReceiveKeys(int stackId) {
582            return stackId != PINNED_STACK_ID;
583        }
584
585        /**
586         * Returns true if the stack can be visible above lockscreen.
587         */
588        public static boolean isAllowedOverLockscreen(int stackId) {
589            return stackId == HOME_STACK_ID || stackId == FULLSCREEN_WORKSPACE_STACK_ID;
590        }
591
592        public static boolean isAlwaysOnTop(int stackId) {
593            return stackId == PINNED_STACK_ID;
594        }
595
596        /**
597         * Returns true if the top task in the task is allowed to return home when finished and
598         * there are other tasks in the stack.
599         */
600        public static boolean allowTopTaskToReturnHome(int stackId) {
601            return stackId != PINNED_STACK_ID;
602        }
603
604        /**
605         * Returns true if the stack should be resized to match the bounds specified by
606         * {@link ActivityOptions#setLaunchBounds} when launching an activity into the stack.
607         */
608        public static boolean resizeStackWithLaunchBounds(int stackId) {
609            return stackId == PINNED_STACK_ID;
610        }
611
612        /**
613         * Returns true if any visible windows belonging to apps in this stack should be kept on
614         * screen when the app is killed due to something like the low memory killer.
615         */
616        public static boolean keepVisibleDeadAppWindowOnScreen(int stackId) {
617            return stackId != PINNED_STACK_ID;
618        }
619    }
620
621    /**
622     * Input parameter to {@link android.app.IActivityManager#moveTaskToDockedStack} which
623     * specifies the position of the created docked stack at the top half of the screen if
624     * in portrait mode or at the left half of the screen if in landscape mode.
625     * @hide
626     */
627    public static final int DOCKED_STACK_CREATE_MODE_TOP_OR_LEFT = 0;
628
629    /**
630     * Input parameter to {@link android.app.IActivityManager#moveTaskToDockedStack} which
631     * specifies the position of the created docked stack at the bottom half of the screen if
632     * in portrait mode or at the right half of the screen if in landscape mode.
633     * @hide
634     */
635    public static final int DOCKED_STACK_CREATE_MODE_BOTTOM_OR_RIGHT = 1;
636
637    /**
638     * Input parameter to {@link android.app.IActivityManager#resizeTask} which indicates
639     * that the resize doesn't need to preserve the window, and can be skipped if bounds
640     * is unchanged. This mode is used by window manager in most cases.
641     * @hide
642     */
643    public static final int RESIZE_MODE_SYSTEM = 0;
644
645    /**
646     * Input parameter to {@link android.app.IActivityManager#resizeTask} which indicates
647     * that the resize should preserve the window if possible.
648     * @hide
649     */
650    public static final int RESIZE_MODE_PRESERVE_WINDOW   = (0x1 << 0);
651
652    /**
653     * Input parameter to {@link android.app.IActivityManager#resizeTask} which indicates
654     * that the resize should be performed even if the bounds appears unchanged.
655     * @hide
656     */
657    public static final int RESIZE_MODE_FORCED = (0x1 << 1);
658
659    /**
660     * Input parameter to {@link android.app.IActivityManager#resizeTask} used by window
661     * manager during a screen rotation.
662     * @hide
663     */
664    public static final int RESIZE_MODE_SYSTEM_SCREEN_ROTATION = RESIZE_MODE_PRESERVE_WINDOW;
665
666    /**
667     * Input parameter to {@link android.app.IActivityManager#resizeTask} used when the
668     * resize is due to a drag action.
669     * @hide
670     */
671    public static final int RESIZE_MODE_USER = RESIZE_MODE_PRESERVE_WINDOW;
672
673    /**
674     * Input parameter to {@link android.app.IActivityManager#resizeTask} which indicates
675     * that the resize should preserve the window if possible, and should not be skipped
676     * even if the bounds is unchanged. Usually used to force a resizing when a drag action
677     * is ending.
678     * @hide
679     */
680    public static final int RESIZE_MODE_USER_FORCED =
681            RESIZE_MODE_PRESERVE_WINDOW | RESIZE_MODE_FORCED;
682
683    /** @hide */
684    public int getFrontActivityScreenCompatMode() {
685        try {
686            return ActivityManagerNative.getDefault().getFrontActivityScreenCompatMode();
687        } catch (RemoteException e) {
688            // System dead, we will be dead too soon!
689            return 0;
690        }
691    }
692
693    /** @hide */
694    public void setFrontActivityScreenCompatMode(int mode) {
695        try {
696            ActivityManagerNative.getDefault().setFrontActivityScreenCompatMode(mode);
697        } catch (RemoteException e) {
698            // System dead, we will be dead too soon!
699        }
700    }
701
702    /** @hide */
703    public int getPackageScreenCompatMode(String packageName) {
704        try {
705            return ActivityManagerNative.getDefault().getPackageScreenCompatMode(packageName);
706        } catch (RemoteException e) {
707            // System dead, we will be dead too soon!
708            return 0;
709        }
710    }
711
712    /** @hide */
713    public void setPackageScreenCompatMode(String packageName, int mode) {
714        try {
715            ActivityManagerNative.getDefault().setPackageScreenCompatMode(packageName, mode);
716        } catch (RemoteException e) {
717            // System dead, we will be dead too soon!
718        }
719    }
720
721    /** @hide */
722    public boolean getPackageAskScreenCompat(String packageName) {
723        try {
724            return ActivityManagerNative.getDefault().getPackageAskScreenCompat(packageName);
725        } catch (RemoteException e) {
726            // System dead, we will be dead too soon!
727            return false;
728        }
729    }
730
731    /** @hide */
732    public void setPackageAskScreenCompat(String packageName, boolean ask) {
733        try {
734            ActivityManagerNative.getDefault().setPackageAskScreenCompat(packageName, ask);
735        } catch (RemoteException e) {
736            // System dead, we will be dead too soon!
737        }
738    }
739
740    /**
741     * Return the approximate per-application memory class of the current
742     * device.  This gives you an idea of how hard a memory limit you should
743     * impose on your application to let the overall system work best.  The
744     * returned value is in megabytes; the baseline Android memory class is
745     * 16 (which happens to be the Java heap limit of those devices); some
746     * device with more memory may return 24 or even higher numbers.
747     */
748    public int getMemoryClass() {
749        return staticGetMemoryClass();
750    }
751
752    /** @hide */
753    static public int staticGetMemoryClass() {
754        // Really brain dead right now -- just take this from the configured
755        // vm heap size, and assume it is in megabytes and thus ends with "m".
756        String vmHeapSize = SystemProperties.get("dalvik.vm.heapgrowthlimit", "");
757        if (vmHeapSize != null && !"".equals(vmHeapSize)) {
758            return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
759        }
760        return staticGetLargeMemoryClass();
761    }
762
763    /**
764     * Return the approximate per-application memory class of the current
765     * device when an application is running with a large heap.  This is the
766     * space available for memory-intensive applications; most applications
767     * should not need this amount of memory, and should instead stay with the
768     * {@link #getMemoryClass()} limit.  The returned value is in megabytes.
769     * This may be the same size as {@link #getMemoryClass()} on memory
770     * constrained devices, or it may be significantly larger on devices with
771     * a large amount of available RAM.
772     *
773     * <p>The is the size of the application's Dalvik heap if it has
774     * specified <code>android:largeHeap="true"</code> in its manifest.
775     */
776    public int getLargeMemoryClass() {
777        return staticGetLargeMemoryClass();
778    }
779
780    /** @hide */
781    static public int staticGetLargeMemoryClass() {
782        // Really brain dead right now -- just take this from the configured
783        // vm heap size, and assume it is in megabytes and thus ends with "m".
784        String vmHeapSize = SystemProperties.get("dalvik.vm.heapsize", "16m");
785        return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length() - 1));
786    }
787
788    /**
789     * Returns true if this is a low-RAM device.  Exactly whether a device is low-RAM
790     * is ultimately up to the device configuration, but currently it generally means
791     * something in the class of a 512MB device with about a 800x480 or less screen.
792     * This is mostly intended to be used by apps to determine whether they should turn
793     * off certain features that require more RAM.
794     */
795    public boolean isLowRamDevice() {
796        return isLowRamDeviceStatic();
797    }
798
799    /** @hide */
800    public static boolean isLowRamDeviceStatic() {
801        return "true".equals(SystemProperties.get("ro.config.low_ram", "false"));
802    }
803
804    /**
805     * Used by persistent processes to determine if they are running on a
806     * higher-end device so should be okay using hardware drawing acceleration
807     * (which tends to consume a lot more RAM).
808     * @hide
809     */
810    static public boolean isHighEndGfx() {
811        return !isLowRamDeviceStatic() &&
812                !Resources.getSystem().getBoolean(com.android.internal.R.bool.config_avoidGfxAccel);
813    }
814
815    /**
816     * Return the maximum number of recents entries that we will maintain and show.
817     * @hide
818     */
819    static public int getMaxRecentTasksStatic() {
820        if (gMaxRecentTasks < 0) {
821            return gMaxRecentTasks = isLowRamDeviceStatic() ? 50 : 100;
822        }
823        return gMaxRecentTasks;
824    }
825
826    /**
827     * Return the default limit on the number of recents that an app can make.
828     * @hide
829     */
830    static public int getDefaultAppRecentsLimitStatic() {
831        return getMaxRecentTasksStatic() / 6;
832    }
833
834    /**
835     * Return the maximum limit on the number of recents that an app can make.
836     * @hide
837     */
838    static public int getMaxAppRecentsLimitStatic() {
839        return getMaxRecentTasksStatic() / 2;
840    }
841
842    /**
843     * Information you can set and retrieve about the current activity within the recent task list.
844     */
845    public static class TaskDescription implements Parcelable {
846        /** @hide */
847        public static final String ATTR_TASKDESCRIPTION_PREFIX = "task_description_";
848        private static final String ATTR_TASKDESCRIPTIONLABEL =
849                ATTR_TASKDESCRIPTION_PREFIX + "label";
850        private static final String ATTR_TASKDESCRIPTIONCOLOR =
851                ATTR_TASKDESCRIPTION_PREFIX + "color";
852        private static final String ATTR_TASKDESCRIPTIONICONFILENAME =
853                ATTR_TASKDESCRIPTION_PREFIX + "icon_filename";
854
855        private String mLabel;
856        private Bitmap mIcon;
857        private String mIconFilename;
858        private int mColorPrimary;
859
860        /**
861         * Creates the TaskDescription to the specified values.
862         *
863         * @param label A label and description of the current state of this task.
864         * @param icon An icon that represents the current state of this task.
865         * @param colorPrimary A color to override the theme's primary color.  This color must be opaque.
866         */
867        public TaskDescription(String label, Bitmap icon, int colorPrimary) {
868            if ((colorPrimary != 0) && (Color.alpha(colorPrimary) != 255)) {
869                throw new RuntimeException("A TaskDescription's primary color should be opaque");
870            }
871
872            mLabel = label;
873            mIcon = icon;
874            mColorPrimary = colorPrimary;
875        }
876
877        /** @hide */
878        public TaskDescription(String label, int colorPrimary, String iconFilename) {
879            this(label, null, colorPrimary);
880            mIconFilename = iconFilename;
881        }
882
883        /**
884         * Creates the TaskDescription to the specified values.
885         *
886         * @param label A label and description of the current state of this activity.
887         * @param icon An icon that represents the current state of this activity.
888         */
889        public TaskDescription(String label, Bitmap icon) {
890            this(label, icon, 0);
891        }
892
893        /**
894         * Creates the TaskDescription to the specified values.
895         *
896         * @param label A label and description of the current state of this activity.
897         */
898        public TaskDescription(String label) {
899            this(label, null, 0);
900        }
901
902        /**
903         * Creates an empty TaskDescription.
904         */
905        public TaskDescription() {
906            this(null, null, 0);
907        }
908
909        /**
910         * Creates a copy of another TaskDescription.
911         */
912        public TaskDescription(TaskDescription td) {
913            mLabel = td.mLabel;
914            mIcon = td.mIcon;
915            mColorPrimary = td.mColorPrimary;
916            mIconFilename = td.mIconFilename;
917        }
918
919        private TaskDescription(Parcel source) {
920            readFromParcel(source);
921        }
922
923        /**
924         * Sets the label for this task description.
925         * @hide
926         */
927        public void setLabel(String label) {
928            mLabel = label;
929        }
930
931        /**
932         * Sets the primary color for this task description.
933         * @hide
934         */
935        public void setPrimaryColor(int primaryColor) {
936            // Ensure that the given color is valid
937            if ((primaryColor != 0) && (Color.alpha(primaryColor) != 255)) {
938                throw new RuntimeException("A TaskDescription's primary color should be opaque");
939            }
940            mColorPrimary = primaryColor;
941        }
942
943        /**
944         * Sets the icon for this task description.
945         * @hide
946         */
947        public void setIcon(Bitmap icon) {
948            mIcon = icon;
949        }
950
951        /**
952         * Moves the icon bitmap reference from an actual Bitmap to a file containing the
953         * bitmap.
954         * @hide
955         */
956        public void setIconFilename(String iconFilename) {
957            mIconFilename = iconFilename;
958            mIcon = null;
959        }
960
961        /**
962         * @return The label and description of the current state of this task.
963         */
964        public String getLabel() {
965            return mLabel;
966        }
967
968        /**
969         * @return The icon that represents the current state of this task.
970         */
971        public Bitmap getIcon() {
972            if (mIcon != null) {
973                return mIcon;
974            }
975            return loadTaskDescriptionIcon(mIconFilename, UserHandle.myUserId());
976        }
977
978        /** @hide */
979        public String getIconFilename() {
980            return mIconFilename;
981        }
982
983        /** @hide */
984        public Bitmap getInMemoryIcon() {
985            return mIcon;
986        }
987
988        /** @hide */
989        public static Bitmap loadTaskDescriptionIcon(String iconFilename, int userId) {
990            if (iconFilename != null) {
991                try {
992                    return ActivityManagerNative.getDefault().
993                            getTaskDescriptionIcon(iconFilename, userId);
994                } catch (RemoteException e) {
995                }
996            }
997            return null;
998        }
999
1000        /**
1001         * @return The color override on the theme's primary color.
1002         */
1003        public int getPrimaryColor() {
1004            return mColorPrimary;
1005        }
1006
1007        /** @hide */
1008        public void saveToXml(XmlSerializer out) throws IOException {
1009            if (mLabel != null) {
1010                out.attribute(null, ATTR_TASKDESCRIPTIONLABEL, mLabel);
1011            }
1012            if (mColorPrimary != 0) {
1013                out.attribute(null, ATTR_TASKDESCRIPTIONCOLOR, Integer.toHexString(mColorPrimary));
1014            }
1015            if (mIconFilename != null) {
1016                out.attribute(null, ATTR_TASKDESCRIPTIONICONFILENAME, mIconFilename);
1017            }
1018        }
1019
1020        /** @hide */
1021        public void restoreFromXml(String attrName, String attrValue) {
1022            if (ATTR_TASKDESCRIPTIONLABEL.equals(attrName)) {
1023                setLabel(attrValue);
1024            } else if (ATTR_TASKDESCRIPTIONCOLOR.equals(attrName)) {
1025                setPrimaryColor((int) Long.parseLong(attrValue, 16));
1026            } else if (ATTR_TASKDESCRIPTIONICONFILENAME.equals(attrName)) {
1027                setIconFilename(attrValue);
1028            }
1029        }
1030
1031        @Override
1032        public int describeContents() {
1033            return 0;
1034        }
1035
1036        @Override
1037        public void writeToParcel(Parcel dest, int flags) {
1038            if (mLabel == null) {
1039                dest.writeInt(0);
1040            } else {
1041                dest.writeInt(1);
1042                dest.writeString(mLabel);
1043            }
1044            if (mIcon == null) {
1045                dest.writeInt(0);
1046            } else {
1047                dest.writeInt(1);
1048                mIcon.writeToParcel(dest, 0);
1049            }
1050            dest.writeInt(mColorPrimary);
1051            if (mIconFilename == null) {
1052                dest.writeInt(0);
1053            } else {
1054                dest.writeInt(1);
1055                dest.writeString(mIconFilename);
1056            }
1057        }
1058
1059        public void readFromParcel(Parcel source) {
1060            mLabel = source.readInt() > 0 ? source.readString() : null;
1061            mIcon = source.readInt() > 0 ? Bitmap.CREATOR.createFromParcel(source) : null;
1062            mColorPrimary = source.readInt();
1063            mIconFilename = source.readInt() > 0 ? source.readString() : null;
1064        }
1065
1066        public static final Creator<TaskDescription> CREATOR
1067                = new Creator<TaskDescription>() {
1068            public TaskDescription createFromParcel(Parcel source) {
1069                return new TaskDescription(source);
1070            }
1071            public TaskDescription[] newArray(int size) {
1072                return new TaskDescription[size];
1073            }
1074        };
1075
1076        @Override
1077        public String toString() {
1078            return "TaskDescription Label: " + mLabel + " Icon: " + mIcon +
1079                    " colorPrimary: " + mColorPrimary;
1080        }
1081    }
1082
1083    /**
1084     * Information you can retrieve about tasks that the user has most recently
1085     * started or visited.
1086     */
1087    public static class RecentTaskInfo implements Parcelable {
1088        /**
1089         * If this task is currently running, this is the identifier for it.
1090         * If it is not running, this will be -1.
1091         */
1092        public int id;
1093
1094        /**
1095         * The true identifier of this task, valid even if it is not running.
1096         */
1097        public int persistentId;
1098
1099        /**
1100         * The original Intent used to launch the task.  You can use this
1101         * Intent to re-launch the task (if it is no longer running) or bring
1102         * the current task to the front.
1103         */
1104        public Intent baseIntent;
1105
1106        /**
1107         * If this task was started from an alias, this is the actual
1108         * activity component that was initially started; the component of
1109         * the baseIntent in this case is the name of the actual activity
1110         * implementation that the alias referred to.  Otherwise, this is null.
1111         */
1112        public ComponentName origActivity;
1113
1114        /**
1115         * The actual activity component that started the task.
1116         * @hide
1117         */
1118        @Nullable
1119        public ComponentName realActivity;
1120
1121        /**
1122         * Description of the task's last state.
1123         */
1124        public CharSequence description;
1125
1126        /**
1127         * The id of the ActivityStack this Task was on most recently.
1128         * @hide
1129         */
1130        public int stackId;
1131
1132        /**
1133         * The id of the user the task was running as.
1134         * @hide
1135         */
1136        public int userId;
1137
1138        /**
1139         * The first time this task was active.
1140         * @hide
1141         */
1142        public long firstActiveTime;
1143
1144        /**
1145         * The last time this task was active.
1146         * @hide
1147         */
1148        public long lastActiveTime;
1149
1150        /**
1151         * The recent activity values for the highest activity in the stack to have set the values.
1152         * {@link Activity#setTaskDescription(android.app.ActivityManager.TaskDescription)}.
1153         */
1154        public TaskDescription taskDescription;
1155
1156        /**
1157         * Task affiliation for grouping with other tasks.
1158         */
1159        public int affiliatedTaskId;
1160
1161        /**
1162         * Task affiliation color of the source task with the affiliated task id.
1163         *
1164         * @hide
1165         */
1166        public int affiliatedTaskColor;
1167
1168        /**
1169         * The component launched as the first activity in the task.
1170         * This can be considered the "application" of this task.
1171         */
1172        public ComponentName baseActivity;
1173
1174        /**
1175         * The activity component at the top of the history stack of the task.
1176         * This is what the user is currently doing.
1177         */
1178        public ComponentName topActivity;
1179
1180        /**
1181         * Number of activities in this task.
1182         */
1183        public int numActivities;
1184
1185        /**
1186         * The bounds of the task.
1187         * @hide
1188         */
1189        public Rect bounds;
1190
1191        public RecentTaskInfo() {
1192        }
1193
1194        @Override
1195        public int describeContents() {
1196            return 0;
1197        }
1198
1199        @Override
1200        public void writeToParcel(Parcel dest, int flags) {
1201            dest.writeInt(id);
1202            dest.writeInt(persistentId);
1203            if (baseIntent != null) {
1204                dest.writeInt(1);
1205                baseIntent.writeToParcel(dest, 0);
1206            } else {
1207                dest.writeInt(0);
1208            }
1209            ComponentName.writeToParcel(origActivity, dest);
1210            ComponentName.writeToParcel(realActivity, dest);
1211            TextUtils.writeToParcel(description, dest,
1212                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1213            if (taskDescription != null) {
1214                dest.writeInt(1);
1215                taskDescription.writeToParcel(dest, 0);
1216            } else {
1217                dest.writeInt(0);
1218            }
1219            dest.writeInt(stackId);
1220            dest.writeInt(userId);
1221            dest.writeLong(firstActiveTime);
1222            dest.writeLong(lastActiveTime);
1223            dest.writeInt(affiliatedTaskId);
1224            dest.writeInt(affiliatedTaskColor);
1225            ComponentName.writeToParcel(baseActivity, dest);
1226            ComponentName.writeToParcel(topActivity, dest);
1227            dest.writeInt(numActivities);
1228            if (bounds != null) {
1229                dest.writeInt(1);
1230                bounds.writeToParcel(dest, 0);
1231            } else {
1232                dest.writeInt(0);
1233            }
1234        }
1235
1236        public void readFromParcel(Parcel source) {
1237            id = source.readInt();
1238            persistentId = source.readInt();
1239            baseIntent = source.readInt() > 0 ? Intent.CREATOR.createFromParcel(source) : null;
1240            origActivity = ComponentName.readFromParcel(source);
1241            realActivity = ComponentName.readFromParcel(source);
1242            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
1243            taskDescription = source.readInt() > 0 ?
1244                    TaskDescription.CREATOR.createFromParcel(source) : null;
1245            stackId = source.readInt();
1246            userId = source.readInt();
1247            firstActiveTime = source.readLong();
1248            lastActiveTime = source.readLong();
1249            affiliatedTaskId = source.readInt();
1250            affiliatedTaskColor = source.readInt();
1251            baseActivity = ComponentName.readFromParcel(source);
1252            topActivity = ComponentName.readFromParcel(source);
1253            numActivities = source.readInt();
1254            bounds = source.readInt() > 0 ?
1255                    Rect.CREATOR.createFromParcel(source) : null;
1256        }
1257
1258        public static final Creator<RecentTaskInfo> CREATOR
1259                = new Creator<RecentTaskInfo>() {
1260            public RecentTaskInfo createFromParcel(Parcel source) {
1261                return new RecentTaskInfo(source);
1262            }
1263            public RecentTaskInfo[] newArray(int size) {
1264                return new RecentTaskInfo[size];
1265            }
1266        };
1267
1268        private RecentTaskInfo(Parcel source) {
1269            readFromParcel(source);
1270        }
1271    }
1272
1273    /**
1274     * Flag for use with {@link #getRecentTasks}: return all tasks, even those
1275     * that have set their
1276     * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
1277     */
1278    public static final int RECENT_WITH_EXCLUDED = 0x0001;
1279
1280    /**
1281     * Provides a list that does not contain any
1282     * recent tasks that currently are not available to the user.
1283     */
1284    public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002;
1285
1286    /**
1287     * Provides a list that contains recent tasks for all
1288     * profiles of a user.
1289     * @hide
1290     */
1291    public static final int RECENT_INCLUDE_PROFILES = 0x0004;
1292
1293    /**
1294     * Ignores all tasks that are on the home stack.
1295     * @hide
1296     */
1297    public static final int RECENT_IGNORE_HOME_STACK_TASKS = 0x0008;
1298
1299    /**
1300     * Ignores all tasks that are on the docked stack.
1301     * @hide
1302     */
1303    public static final int RECENT_INGORE_DOCKED_STACK_TASKS = 0x0010;
1304
1305    /**
1306     * Ignores all tasks that are on the pinned stack.
1307     * @hide
1308     */
1309    public static final int RECENT_INGORE_PINNED_STACK_TASKS = 0x0020;
1310
1311    /**
1312     * <p></p>Return a list of the tasks that the user has recently launched, with
1313     * the most recent being first and older ones after in order.
1314     *
1315     * <p><b>Note: this method is only intended for debugging and presenting
1316     * task management user interfaces</b>.  This should never be used for
1317     * core logic in an application, such as deciding between different
1318     * behaviors based on the information found here.  Such uses are
1319     * <em>not</em> supported, and will likely break in the future.  For
1320     * example, if multiple applications can be actively running at the
1321     * same time, assumptions made about the meaning of the data here for
1322     * purposes of control flow will be incorrect.</p>
1323     *
1324     * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method is
1325     * no longer available to third party applications: the introduction of
1326     * document-centric recents means
1327     * it can leak personal information to the caller.  For backwards compatibility,
1328     * it will still return a small subset of its data: at least the caller's
1329     * own tasks (though see {@link #getAppTasks()} for the correct supported
1330     * way to retrieve that information), and possibly some other tasks
1331     * such as home that are known to not be sensitive.
1332     *
1333     * @param maxNum The maximum number of entries to return in the list.  The
1334     * actual number returned may be smaller, depending on how many tasks the
1335     * user has started and the maximum number the system can remember.
1336     * @param flags Information about what to return.  May be any combination
1337     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
1338     *
1339     * @return Returns a list of RecentTaskInfo records describing each of
1340     * the recent tasks.
1341     */
1342    @Deprecated
1343    public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags)
1344            throws SecurityException {
1345        try {
1346            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
1347                    flags, UserHandle.myUserId());
1348        } catch (RemoteException e) {
1349            // System dead, we will be dead too soon!
1350            return null;
1351        }
1352    }
1353
1354    /**
1355     * Same as {@link #getRecentTasks(int, int)} but returns the recent tasks for a
1356     * specific user. It requires holding
1357     * the {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
1358     * @param maxNum The maximum number of entries to return in the list.  The
1359     * actual number returned may be smaller, depending on how many tasks the
1360     * user has started and the maximum number the system can remember.
1361     * @param flags Information about what to return.  May be any combination
1362     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
1363     *
1364     * @return Returns a list of RecentTaskInfo records describing each of
1365     * the recent tasks. Most recently activated tasks go first.
1366     *
1367     * @hide
1368     */
1369    public List<RecentTaskInfo> getRecentTasksForUser(int maxNum, int flags, int userId)
1370            throws SecurityException {
1371        try {
1372            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
1373                    flags, userId);
1374        } catch (RemoteException e) {
1375            // System dead, we will be dead too soon!
1376            return null;
1377        }
1378    }
1379
1380    /**
1381     * Information you can retrieve about a particular task that is currently
1382     * "running" in the system.  Note that a running task does not mean the
1383     * given task actually has a process it is actively running in; it simply
1384     * means that the user has gone to it and never closed it, but currently
1385     * the system may have killed its process and is only holding on to its
1386     * last state in order to restart it when the user returns.
1387     */
1388    public static class RunningTaskInfo implements Parcelable {
1389        /**
1390         * A unique identifier for this task.
1391         */
1392        public int id;
1393
1394        /**
1395         * The stack that currently contains this task.
1396         * @hide
1397         */
1398        public int stackId;
1399
1400        /**
1401         * The component launched as the first activity in the task.  This can
1402         * be considered the "application" of this task.
1403         */
1404        public ComponentName baseActivity;
1405
1406        /**
1407         * The activity component at the top of the history stack of the task.
1408         * This is what the user is currently doing.
1409         */
1410        public ComponentName topActivity;
1411
1412        /**
1413         * Thumbnail representation of the task's current state.  Currently
1414         * always null.
1415         */
1416        public Bitmap thumbnail;
1417
1418        /**
1419         * Description of the task's current state.
1420         */
1421        public CharSequence description;
1422
1423        /**
1424         * Number of activities in this task.
1425         */
1426        public int numActivities;
1427
1428        /**
1429         * Number of activities that are currently running (not stopped
1430         * and persisted) in this task.
1431         */
1432        public int numRunning;
1433
1434        /**
1435         * Last time task was run. For sorting.
1436         * @hide
1437         */
1438        public long lastActiveTime;
1439
1440        public RunningTaskInfo() {
1441        }
1442
1443        public int describeContents() {
1444            return 0;
1445        }
1446
1447        public void writeToParcel(Parcel dest, int flags) {
1448            dest.writeInt(id);
1449            dest.writeInt(stackId);
1450            ComponentName.writeToParcel(baseActivity, dest);
1451            ComponentName.writeToParcel(topActivity, dest);
1452            if (thumbnail != null) {
1453                dest.writeInt(1);
1454                thumbnail.writeToParcel(dest, 0);
1455            } else {
1456                dest.writeInt(0);
1457            }
1458            TextUtils.writeToParcel(description, dest,
1459                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1460            dest.writeInt(numActivities);
1461            dest.writeInt(numRunning);
1462        }
1463
1464        public void readFromParcel(Parcel source) {
1465            id = source.readInt();
1466            stackId = source.readInt();
1467            baseActivity = ComponentName.readFromParcel(source);
1468            topActivity = ComponentName.readFromParcel(source);
1469            if (source.readInt() != 0) {
1470                thumbnail = Bitmap.CREATOR.createFromParcel(source);
1471            } else {
1472                thumbnail = null;
1473            }
1474            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
1475            numActivities = source.readInt();
1476            numRunning = source.readInt();
1477        }
1478
1479        public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
1480            public RunningTaskInfo createFromParcel(Parcel source) {
1481                return new RunningTaskInfo(source);
1482            }
1483            public RunningTaskInfo[] newArray(int size) {
1484                return new RunningTaskInfo[size];
1485            }
1486        };
1487
1488        private RunningTaskInfo(Parcel source) {
1489            readFromParcel(source);
1490        }
1491    }
1492
1493    /**
1494     * Get the list of tasks associated with the calling application.
1495     *
1496     * @return The list of tasks associated with the application making this call.
1497     * @throws SecurityException
1498     */
1499    public List<ActivityManager.AppTask> getAppTasks() {
1500        ArrayList<AppTask> tasks = new ArrayList<AppTask>();
1501        List<IAppTask> appTasks;
1502        try {
1503            appTasks = ActivityManagerNative.getDefault().getAppTasks(mContext.getPackageName());
1504        } catch (RemoteException e) {
1505            // System dead, we will be dead too soon!
1506            return null;
1507        }
1508        int numAppTasks = appTasks.size();
1509        for (int i = 0; i < numAppTasks; i++) {
1510            tasks.add(new AppTask(appTasks.get(i)));
1511        }
1512        return tasks;
1513    }
1514
1515    /**
1516     * Return the current design dimensions for {@link AppTask} thumbnails, for use
1517     * with {@link #addAppTask}.
1518     */
1519    public Size getAppTaskThumbnailSize() {
1520        synchronized (this) {
1521            ensureAppTaskThumbnailSizeLocked();
1522            return new Size(mAppTaskThumbnailSize.x, mAppTaskThumbnailSize.y);
1523        }
1524    }
1525
1526    private void ensureAppTaskThumbnailSizeLocked() {
1527        if (mAppTaskThumbnailSize == null) {
1528            try {
1529                mAppTaskThumbnailSize = ActivityManagerNative.getDefault().getAppTaskThumbnailSize();
1530            } catch (RemoteException e) {
1531                throw new IllegalStateException("System dead?", e);
1532            }
1533        }
1534    }
1535
1536    /**
1537     * Add a new {@link AppTask} for the calling application.  This will create a new
1538     * recents entry that is added to the <b>end</b> of all existing recents.
1539     *
1540     * @param activity The activity that is adding the entry.   This is used to help determine
1541     * the context that the new recents entry will be in.
1542     * @param intent The Intent that describes the recents entry.  This is the same Intent that
1543     * you would have used to launch the activity for it.  In generally you will want to set
1544     * both {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT} and
1545     * {@link Intent#FLAG_ACTIVITY_RETAIN_IN_RECENTS}; the latter is required since this recents
1546     * entry will exist without an activity, so it doesn't make sense to not retain it when
1547     * its activity disappears.  The given Intent here also must have an explicit ComponentName
1548     * set on it.
1549     * @param description Optional additional description information.
1550     * @param thumbnail Thumbnail to use for the recents entry.  Should be the size given by
1551     * {@link #getAppTaskThumbnailSize()}.  If the bitmap is not that exact size, it will be
1552     * recreated in your process, probably in a way you don't like, before the recents entry
1553     * is added.
1554     *
1555     * @return Returns the task id of the newly added app task, or -1 if the add failed.  The
1556     * most likely cause of failure is that there is no more room for more tasks for your app.
1557     */
1558    public int addAppTask(@NonNull Activity activity, @NonNull Intent intent,
1559            @Nullable TaskDescription description, @NonNull Bitmap thumbnail) {
1560        Point size;
1561        synchronized (this) {
1562            ensureAppTaskThumbnailSizeLocked();
1563            size = mAppTaskThumbnailSize;
1564        }
1565        final int tw = thumbnail.getWidth();
1566        final int th = thumbnail.getHeight();
1567        if (tw != size.x || th != size.y) {
1568            Bitmap bm = Bitmap.createBitmap(size.x, size.y, thumbnail.getConfig());
1569
1570            // Use ScaleType.CENTER_CROP, except we leave the top edge at the top.
1571            float scale;
1572            float dx = 0, dy = 0;
1573            if (tw * size.x > size.y * th) {
1574                scale = (float) size.x / (float) th;
1575                dx = (size.y - tw * scale) * 0.5f;
1576            } else {
1577                scale = (float) size.y / (float) tw;
1578                dy = (size.x - th * scale) * 0.5f;
1579            }
1580            Matrix matrix = new Matrix();
1581            matrix.setScale(scale, scale);
1582            matrix.postTranslate((int) (dx + 0.5f), 0);
1583
1584            Canvas canvas = new Canvas(bm);
1585            canvas.drawBitmap(thumbnail, matrix, null);
1586            canvas.setBitmap(null);
1587
1588            thumbnail = bm;
1589        }
1590        if (description == null) {
1591            description = new TaskDescription();
1592        }
1593        try {
1594            return ActivityManagerNative.getDefault().addAppTask(activity.getActivityToken(),
1595                    intent, description, thumbnail);
1596        } catch (RemoteException e) {
1597            throw new IllegalStateException("System dead?", e);
1598        }
1599    }
1600
1601    /**
1602     * Return a list of the tasks that are currently running, with
1603     * the most recent being first and older ones after in order.  Note that
1604     * "running" does not mean any of the task's code is currently loaded or
1605     * activity -- the task may have been frozen by the system, so that it
1606     * can be restarted in its previous state when next brought to the
1607     * foreground.
1608     *
1609     * <p><b>Note: this method is only intended for debugging and presenting
1610     * task management user interfaces</b>.  This should never be used for
1611     * core logic in an application, such as deciding between different
1612     * behaviors based on the information found here.  Such uses are
1613     * <em>not</em> supported, and will likely break in the future.  For
1614     * example, if multiple applications can be actively running at the
1615     * same time, assumptions made about the meaning of the data here for
1616     * purposes of control flow will be incorrect.</p>
1617     *
1618     * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method
1619     * is no longer available to third party
1620     * applications: the introduction of document-centric recents means
1621     * it can leak person information to the caller.  For backwards compatibility,
1622     * it will still retu rn a small subset of its data: at least the caller's
1623     * own tasks, and possibly some other tasks
1624     * such as home that are known to not be sensitive.
1625     *
1626     * @param maxNum The maximum number of entries to return in the list.  The
1627     * actual number returned may be smaller, depending on how many tasks the
1628     * user has started.
1629     *
1630     * @return Returns a list of RunningTaskInfo records describing each of
1631     * the running tasks.
1632     */
1633    @Deprecated
1634    public List<RunningTaskInfo> getRunningTasks(int maxNum)
1635            throws SecurityException {
1636        try {
1637            return ActivityManagerNative.getDefault().getTasks(maxNum, 0);
1638        } catch (RemoteException e) {
1639            // System dead, we will be dead too soon!
1640            return null;
1641        }
1642    }
1643
1644    /**
1645     * Completely remove the given task.
1646     *
1647     * @param taskId Identifier of the task to be removed.
1648     * @return Returns true if the given task was found and removed.
1649     *
1650     * @hide
1651     */
1652    public boolean removeTask(int taskId) throws SecurityException {
1653        try {
1654            return ActivityManagerNative.getDefault().removeTask(taskId);
1655        } catch (RemoteException e) {
1656            // System dead, we will be dead too soon!
1657            return false;
1658        }
1659    }
1660
1661    /**
1662     * Metadata related to the {@link TaskThumbnail}.
1663     *
1664     * @hide
1665     */
1666    public static class TaskThumbnailInfo implements Parcelable {
1667        /** @hide */
1668        public static final String ATTR_TASK_THUMBNAILINFO_PREFIX = "task_thumbnailinfo_";
1669        private static final String ATTR_TASK_WIDTH =
1670                ATTR_TASK_THUMBNAILINFO_PREFIX + "task_width";
1671        private static final String ATTR_TASK_HEIGHT =
1672                ATTR_TASK_THUMBNAILINFO_PREFIX + "task_height";
1673        private static final String ATTR_SCREEN_ORIENTATION =
1674                ATTR_TASK_THUMBNAILINFO_PREFIX + "screen_orientation";
1675
1676        public int taskWidth;
1677        public int taskHeight;
1678        public int screenOrientation;
1679
1680        public TaskThumbnailInfo() {
1681            // Do nothing
1682        }
1683
1684        private TaskThumbnailInfo(Parcel source) {
1685            readFromParcel(source);
1686        }
1687
1688        /**
1689         * Resets this info state to the initial state.
1690         * @hide
1691         */
1692        public void reset() {
1693            taskWidth = 0;
1694            taskHeight = 0;
1695            screenOrientation = 0;
1696        }
1697
1698        /** @hide */
1699        public void saveToXml(XmlSerializer out) throws IOException {
1700            out.attribute(null, ATTR_TASK_WIDTH, Integer.toString(taskWidth));
1701            out.attribute(null, ATTR_TASK_HEIGHT, Integer.toString(taskHeight));
1702            out.attribute(null, ATTR_SCREEN_ORIENTATION, Integer.toString(screenOrientation));
1703        }
1704
1705        /** @hide */
1706        public void restoreFromXml(String attrName, String attrValue) {
1707            if (ATTR_TASK_WIDTH.equals(attrName)) {
1708                taskWidth = Integer.parseInt(attrValue);
1709            } else if (ATTR_TASK_HEIGHT.equals(attrName)) {
1710                taskHeight = Integer.parseInt(attrValue);
1711            } else if (ATTR_SCREEN_ORIENTATION.equals(attrName)) {
1712                screenOrientation = Integer.parseInt(attrValue);
1713            }
1714        }
1715
1716        public int describeContents() {
1717            return 0;
1718        }
1719
1720        public void writeToParcel(Parcel dest, int flags) {
1721            dest.writeInt(taskWidth);
1722            dest.writeInt(taskHeight);
1723            dest.writeInt(screenOrientation);
1724        }
1725
1726        public void readFromParcel(Parcel source) {
1727            taskWidth = source.readInt();
1728            taskHeight = source.readInt();
1729            screenOrientation = source.readInt();
1730        }
1731
1732        public static final Creator<TaskThumbnailInfo> CREATOR = new Creator<TaskThumbnailInfo>() {
1733            public TaskThumbnailInfo createFromParcel(Parcel source) {
1734                return new TaskThumbnailInfo(source);
1735            }
1736            public TaskThumbnailInfo[] newArray(int size) {
1737                return new TaskThumbnailInfo[size];
1738            }
1739        };
1740    }
1741
1742    /** @hide */
1743    public static class TaskThumbnail implements Parcelable {
1744        public Bitmap mainThumbnail;
1745        public ParcelFileDescriptor thumbnailFileDescriptor;
1746        public TaskThumbnailInfo thumbnailInfo;
1747
1748        public TaskThumbnail() {
1749        }
1750
1751        private TaskThumbnail(Parcel source) {
1752            readFromParcel(source);
1753        }
1754
1755        public int describeContents() {
1756            if (thumbnailFileDescriptor != null) {
1757                return thumbnailFileDescriptor.describeContents();
1758            }
1759            return 0;
1760        }
1761
1762        public void writeToParcel(Parcel dest, int flags) {
1763            if (mainThumbnail != null) {
1764                dest.writeInt(1);
1765                mainThumbnail.writeToParcel(dest, flags);
1766            } else {
1767                dest.writeInt(0);
1768            }
1769            if (thumbnailFileDescriptor != null) {
1770                dest.writeInt(1);
1771                thumbnailFileDescriptor.writeToParcel(dest, flags);
1772            } else {
1773                dest.writeInt(0);
1774            }
1775            if (thumbnailInfo != null) {
1776                dest.writeInt(1);
1777                thumbnailInfo.writeToParcel(dest, flags);
1778            } else {
1779                dest.writeInt(0);
1780            }
1781        }
1782
1783        public void readFromParcel(Parcel source) {
1784            if (source.readInt() != 0) {
1785                mainThumbnail = Bitmap.CREATOR.createFromParcel(source);
1786            } else {
1787                mainThumbnail = null;
1788            }
1789            if (source.readInt() != 0) {
1790                thumbnailFileDescriptor = ParcelFileDescriptor.CREATOR.createFromParcel(source);
1791            } else {
1792                thumbnailFileDescriptor = null;
1793            }
1794            if (source.readInt() != 0) {
1795                thumbnailInfo = TaskThumbnailInfo.CREATOR.createFromParcel(source);
1796            } else {
1797                thumbnailInfo = null;
1798            }
1799        }
1800
1801        public static final Creator<TaskThumbnail> CREATOR = new Creator<TaskThumbnail>() {
1802            public TaskThumbnail createFromParcel(Parcel source) {
1803                return new TaskThumbnail(source);
1804            }
1805            public TaskThumbnail[] newArray(int size) {
1806                return new TaskThumbnail[size];
1807            }
1808        };
1809    }
1810
1811    /** @hide */
1812    public TaskThumbnail getTaskThumbnail(int id) throws SecurityException {
1813        try {
1814            return ActivityManagerNative.getDefault().getTaskThumbnail(id);
1815        } catch (RemoteException e) {
1816            // System dead, we will be dead too soon!
1817            return null;
1818        }
1819    }
1820
1821    /** @hide */
1822    public boolean isInHomeStack(int taskId) {
1823        try {
1824            return ActivityManagerNative.getDefault().isInHomeStack(taskId);
1825        } catch (RemoteException e) {
1826            // System dead, we will be dead too soon!
1827            return false;
1828        }
1829    }
1830
1831    /**
1832     * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
1833     * activity along with the task, so it is positioned immediately behind
1834     * the task.
1835     */
1836    public static final int MOVE_TASK_WITH_HOME = 0x00000001;
1837
1838    /**
1839     * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
1840     * user-instigated action, so the current activity will not receive a
1841     * hint that the user is leaving.
1842     */
1843    public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
1844
1845    /**
1846     * Equivalent to calling {@link #moveTaskToFront(int, int, Bundle)}
1847     * with a null options argument.
1848     *
1849     * @param taskId The identifier of the task to be moved, as found in
1850     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
1851     * @param flags Additional operational flags, 0 or more of
1852     * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
1853     */
1854    public void moveTaskToFront(int taskId, int flags) {
1855        moveTaskToFront(taskId, flags, null);
1856    }
1857
1858    /**
1859     * Ask that the task associated with a given task ID be moved to the
1860     * front of the stack, so it is now visible to the user.  Requires that
1861     * the caller hold permission {@link android.Manifest.permission#REORDER_TASKS}
1862     * or a SecurityException will be thrown.
1863     *
1864     * @param taskId The identifier of the task to be moved, as found in
1865     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
1866     * @param flags Additional operational flags, 0 or more of
1867     * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
1868     * @param options Additional options for the operation, either null or
1869     * as per {@link Context#startActivity(Intent, android.os.Bundle)
1870     * Context.startActivity(Intent, Bundle)}.
1871     */
1872    public void moveTaskToFront(int taskId, int flags, Bundle options) {
1873        try {
1874            ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags, options);
1875        } catch (RemoteException e) {
1876            // System dead, we will be dead too soon!
1877        }
1878    }
1879
1880    /**
1881     * Information you can retrieve about a particular Service that is
1882     * currently running in the system.
1883     */
1884    public static class RunningServiceInfo implements Parcelable {
1885        /**
1886         * The service component.
1887         */
1888        public ComponentName service;
1889
1890        /**
1891         * If non-zero, this is the process the service is running in.
1892         */
1893        public int pid;
1894
1895        /**
1896         * The UID that owns this service.
1897         */
1898        public int uid;
1899
1900        /**
1901         * The name of the process this service runs in.
1902         */
1903        public String process;
1904
1905        /**
1906         * Set to true if the service has asked to run as a foreground process.
1907         */
1908        public boolean foreground;
1909
1910        /**
1911         * The time when the service was first made active, either by someone
1912         * starting or binding to it.  This
1913         * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
1914         */
1915        public long activeSince;
1916
1917        /**
1918         * Set to true if this service has been explicitly started.
1919         */
1920        public boolean started;
1921
1922        /**
1923         * Number of clients connected to the service.
1924         */
1925        public int clientCount;
1926
1927        /**
1928         * Number of times the service's process has crashed while the service
1929         * is running.
1930         */
1931        public int crashCount;
1932
1933        /**
1934         * The time when there was last activity in the service (either
1935         * explicit requests to start it or clients binding to it).  This
1936         * is in units of {@link android.os.SystemClock#uptimeMillis()}.
1937         */
1938        public long lastActivityTime;
1939
1940        /**
1941         * If non-zero, this service is not currently running, but scheduled to
1942         * restart at the given time.
1943         */
1944        public long restarting;
1945
1946        /**
1947         * Bit for {@link #flags}: set if this service has been
1948         * explicitly started.
1949         */
1950        public static final int FLAG_STARTED = 1<<0;
1951
1952        /**
1953         * Bit for {@link #flags}: set if the service has asked to
1954         * run as a foreground process.
1955         */
1956        public static final int FLAG_FOREGROUND = 1<<1;
1957
1958        /**
1959         * Bit for {@link #flags): set if the service is running in a
1960         * core system process.
1961         */
1962        public static final int FLAG_SYSTEM_PROCESS = 1<<2;
1963
1964        /**
1965         * Bit for {@link #flags): set if the service is running in a
1966         * persistent process.
1967         */
1968        public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
1969
1970        /**
1971         * Running flags.
1972         */
1973        public int flags;
1974
1975        /**
1976         * For special services that are bound to by system code, this is
1977         * the package that holds the binding.
1978         */
1979        public String clientPackage;
1980
1981        /**
1982         * For special services that are bound to by system code, this is
1983         * a string resource providing a user-visible label for who the
1984         * client is.
1985         */
1986        public int clientLabel;
1987
1988        public RunningServiceInfo() {
1989        }
1990
1991        public int describeContents() {
1992            return 0;
1993        }
1994
1995        public void writeToParcel(Parcel dest, int flags) {
1996            ComponentName.writeToParcel(service, dest);
1997            dest.writeInt(pid);
1998            dest.writeInt(uid);
1999            dest.writeString(process);
2000            dest.writeInt(foreground ? 1 : 0);
2001            dest.writeLong(activeSince);
2002            dest.writeInt(started ? 1 : 0);
2003            dest.writeInt(clientCount);
2004            dest.writeInt(crashCount);
2005            dest.writeLong(lastActivityTime);
2006            dest.writeLong(restarting);
2007            dest.writeInt(this.flags);
2008            dest.writeString(clientPackage);
2009            dest.writeInt(clientLabel);
2010        }
2011
2012        public void readFromParcel(Parcel source) {
2013            service = ComponentName.readFromParcel(source);
2014            pid = source.readInt();
2015            uid = source.readInt();
2016            process = source.readString();
2017            foreground = source.readInt() != 0;
2018            activeSince = source.readLong();
2019            started = source.readInt() != 0;
2020            clientCount = source.readInt();
2021            crashCount = source.readInt();
2022            lastActivityTime = source.readLong();
2023            restarting = source.readLong();
2024            flags = source.readInt();
2025            clientPackage = source.readString();
2026            clientLabel = source.readInt();
2027        }
2028
2029        public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
2030            public RunningServiceInfo createFromParcel(Parcel source) {
2031                return new RunningServiceInfo(source);
2032            }
2033            public RunningServiceInfo[] newArray(int size) {
2034                return new RunningServiceInfo[size];
2035            }
2036        };
2037
2038        private RunningServiceInfo(Parcel source) {
2039            readFromParcel(source);
2040        }
2041    }
2042
2043    /**
2044     * Return a list of the services that are currently running.
2045     *
2046     * <p><b>Note: this method is only intended for debugging or implementing
2047     * service management type user interfaces.</b></p>
2048     *
2049     * @param maxNum The maximum number of entries to return in the list.  The
2050     * actual number returned may be smaller, depending on how many services
2051     * are running.
2052     *
2053     * @return Returns a list of RunningServiceInfo records describing each of
2054     * the running tasks.
2055     */
2056    public List<RunningServiceInfo> getRunningServices(int maxNum)
2057            throws SecurityException {
2058        try {
2059            return ActivityManagerNative.getDefault()
2060                    .getServices(maxNum, 0);
2061        } catch (RemoteException e) {
2062            // System dead, we will be dead too soon!
2063            return null;
2064        }
2065    }
2066
2067    /**
2068     * Returns a PendingIntent you can start to show a control panel for the
2069     * given running service.  If the service does not have a control panel,
2070     * null is returned.
2071     */
2072    public PendingIntent getRunningServiceControlPanel(ComponentName service)
2073            throws SecurityException {
2074        try {
2075            return ActivityManagerNative.getDefault()
2076                    .getRunningServiceControlPanel(service);
2077        } catch (RemoteException e) {
2078            // System dead, we will be dead too soon!
2079            return null;
2080        }
2081    }
2082
2083    /**
2084     * Information you can retrieve about the available memory through
2085     * {@link ActivityManager#getMemoryInfo}.
2086     */
2087    public static class MemoryInfo implements Parcelable {
2088        /**
2089         * The available memory on the system.  This number should not
2090         * be considered absolute: due to the nature of the kernel, a significant
2091         * portion of this memory is actually in use and needed for the overall
2092         * system to run well.
2093         */
2094        public long availMem;
2095
2096        /**
2097         * The total memory accessible by the kernel.  This is basically the
2098         * RAM size of the device, not including below-kernel fixed allocations
2099         * like DMA buffers, RAM for the baseband CPU, etc.
2100         */
2101        public long totalMem;
2102
2103        /**
2104         * The threshold of {@link #availMem} at which we consider memory to be
2105         * low and start killing background services and other non-extraneous
2106         * processes.
2107         */
2108        public long threshold;
2109
2110        /**
2111         * Set to true if the system considers itself to currently be in a low
2112         * memory situation.
2113         */
2114        public boolean lowMemory;
2115
2116        /** @hide */
2117        public long hiddenAppThreshold;
2118        /** @hide */
2119        public long secondaryServerThreshold;
2120        /** @hide */
2121        public long visibleAppThreshold;
2122        /** @hide */
2123        public long foregroundAppThreshold;
2124
2125        public MemoryInfo() {
2126        }
2127
2128        public int describeContents() {
2129            return 0;
2130        }
2131
2132        public void writeToParcel(Parcel dest, int flags) {
2133            dest.writeLong(availMem);
2134            dest.writeLong(totalMem);
2135            dest.writeLong(threshold);
2136            dest.writeInt(lowMemory ? 1 : 0);
2137            dest.writeLong(hiddenAppThreshold);
2138            dest.writeLong(secondaryServerThreshold);
2139            dest.writeLong(visibleAppThreshold);
2140            dest.writeLong(foregroundAppThreshold);
2141        }
2142
2143        public void readFromParcel(Parcel source) {
2144            availMem = source.readLong();
2145            totalMem = source.readLong();
2146            threshold = source.readLong();
2147            lowMemory = source.readInt() != 0;
2148            hiddenAppThreshold = source.readLong();
2149            secondaryServerThreshold = source.readLong();
2150            visibleAppThreshold = source.readLong();
2151            foregroundAppThreshold = source.readLong();
2152        }
2153
2154        public static final Creator<MemoryInfo> CREATOR
2155                = new Creator<MemoryInfo>() {
2156            public MemoryInfo createFromParcel(Parcel source) {
2157                return new MemoryInfo(source);
2158            }
2159            public MemoryInfo[] newArray(int size) {
2160                return new MemoryInfo[size];
2161            }
2162        };
2163
2164        private MemoryInfo(Parcel source) {
2165            readFromParcel(source);
2166        }
2167    }
2168
2169    /**
2170     * Return general information about the memory state of the system.  This
2171     * can be used to help decide how to manage your own memory, though note
2172     * that polling is not recommended and
2173     * {@link android.content.ComponentCallbacks2#onTrimMemory(int)
2174     * ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this.
2175     * Also see {@link #getMyMemoryState} for how to retrieve the current trim
2176     * level of your process as needed, which gives a better hint for how to
2177     * manage its memory.
2178     */
2179    public void getMemoryInfo(MemoryInfo outInfo) {
2180        try {
2181            ActivityManagerNative.getDefault().getMemoryInfo(outInfo);
2182        } catch (RemoteException e) {
2183        }
2184    }
2185
2186    /**
2187     * Information you can retrieve about an ActivityStack in the system.
2188     * @hide
2189     */
2190    public static class StackInfo implements Parcelable {
2191        public int stackId;
2192        public Rect bounds = new Rect();
2193        public int[] taskIds;
2194        public String[] taskNames;
2195        public Rect[] taskBounds;
2196        public int[] taskUserIds;
2197        public int displayId;
2198        public int userId;
2199
2200        @Override
2201        public int describeContents() {
2202            return 0;
2203        }
2204
2205        @Override
2206        public void writeToParcel(Parcel dest, int flags) {
2207            dest.writeInt(stackId);
2208            dest.writeInt(bounds.left);
2209            dest.writeInt(bounds.top);
2210            dest.writeInt(bounds.right);
2211            dest.writeInt(bounds.bottom);
2212            dest.writeIntArray(taskIds);
2213            dest.writeStringArray(taskNames);
2214            final int boundsCount = taskBounds == null ? 0 : taskBounds.length;
2215            dest.writeInt(boundsCount);
2216            for (int i = 0; i < boundsCount; i++) {
2217                dest.writeInt(taskBounds[i].left);
2218                dest.writeInt(taskBounds[i].top);
2219                dest.writeInt(taskBounds[i].right);
2220                dest.writeInt(taskBounds[i].bottom);
2221            }
2222            dest.writeIntArray(taskUserIds);
2223            dest.writeInt(displayId);
2224            dest.writeInt(userId);
2225        }
2226
2227        public void readFromParcel(Parcel source) {
2228            stackId = source.readInt();
2229            bounds = new Rect(
2230                    source.readInt(), source.readInt(), source.readInt(), source.readInt());
2231            taskIds = source.createIntArray();
2232            taskNames = source.createStringArray();
2233            final int boundsCount = source.readInt();
2234            if (boundsCount > 0) {
2235                taskBounds = new Rect[boundsCount];
2236                for (int i = 0; i < boundsCount; i++) {
2237                    taskBounds[i] = new Rect();
2238                    taskBounds[i].set(
2239                            source.readInt(), source.readInt(), source.readInt(), source.readInt());
2240                }
2241            } else {
2242                taskBounds = null;
2243            }
2244            taskUserIds = source.createIntArray();
2245            displayId = source.readInt();
2246            userId = source.readInt();
2247        }
2248
2249        public static final Creator<StackInfo> CREATOR = new Creator<StackInfo>() {
2250            @Override
2251            public StackInfo createFromParcel(Parcel source) {
2252                return new StackInfo(source);
2253            }
2254            @Override
2255            public StackInfo[] newArray(int size) {
2256                return new StackInfo[size];
2257            }
2258        };
2259
2260        public StackInfo() {
2261        }
2262
2263        private StackInfo(Parcel source) {
2264            readFromParcel(source);
2265        }
2266
2267        public String toString(String prefix) {
2268            StringBuilder sb = new StringBuilder(256);
2269            sb.append(prefix); sb.append("Stack id="); sb.append(stackId);
2270                    sb.append(" bounds="); sb.append(bounds.toShortString());
2271                    sb.append(" displayId="); sb.append(displayId);
2272                    sb.append(" userId="); sb.append(userId);
2273                    sb.append("\n");
2274            prefix = prefix + "  ";
2275            for (int i = 0; i < taskIds.length; ++i) {
2276                sb.append(prefix); sb.append("taskId="); sb.append(taskIds[i]);
2277                        sb.append(": "); sb.append(taskNames[i]);
2278                        if (taskBounds != null) {
2279                            sb.append(" bounds="); sb.append(taskBounds[i].toShortString());
2280                        }
2281                        sb.append(" userId=").append(taskUserIds[i]);
2282                        sb.append("\n");
2283            }
2284            return sb.toString();
2285        }
2286
2287        @Override
2288        public String toString() {
2289            return toString("");
2290        }
2291    }
2292
2293    /**
2294     * @hide
2295     */
2296    public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
2297        try {
2298            return ActivityManagerNative.getDefault().clearApplicationUserData(packageName,
2299                    observer, UserHandle.myUserId());
2300        } catch (RemoteException e) {
2301            return false;
2302        }
2303    }
2304
2305    /**
2306     * Permits an application to erase its own data from disk.  This is equivalent to
2307     * the user choosing to clear the app's data from within the device settings UI.  It
2308     * erases all dynamic data associated with the app -- its private data and data in its
2309     * private area on external storage -- but does not remove the installed application
2310     * itself, nor any OBB files.
2311     *
2312     * @return {@code true} if the application successfully requested that the application's
2313     *     data be erased; {@code false} otherwise.
2314     */
2315    public boolean clearApplicationUserData() {
2316        return clearApplicationUserData(mContext.getPackageName(), null);
2317    }
2318
2319
2320    /**
2321     * Permits an application to get the persistent URI permissions granted to another.
2322     *
2323     * <p>Typically called by Settings.
2324     *
2325     * @param packageName application to look for the granted permissions
2326     * @return list of granted URI permissions
2327     *
2328     * @hide
2329     */
2330    public ParceledListSlice<UriPermission> getGrantedUriPermissions(String packageName) {
2331        try {
2332            return ActivityManagerNative.getDefault().getGrantedUriPermissions(packageName,
2333                    UserHandle.myUserId());
2334        } catch (RemoteException e) {
2335            Log.e(TAG, "Couldn't get granted URI permissions for :" + packageName, e);
2336            return ParceledListSlice.emptyList();
2337        }
2338    }
2339
2340    /**
2341     * Permits an application to clear the persistent URI permissions granted to another.
2342     *
2343     * <p>Typically called by Settings.
2344     *
2345     * @param packageName application to clear its granted permissions
2346     *
2347     * @hide
2348     */
2349    public void clearGrantedUriPermissions(String packageName) {
2350        try {
2351            ActivityManagerNative.getDefault().clearGrantedUriPermissions(packageName,
2352                    UserHandle.myUserId());
2353        } catch (RemoteException e) {
2354            Log.e(TAG, "Couldn't clear granted URI permissions for :" + packageName, e);
2355        }
2356    }
2357
2358    /**
2359     * Information you can retrieve about any processes that are in an error condition.
2360     */
2361    public static class ProcessErrorStateInfo implements Parcelable {
2362        /**
2363         * Condition codes
2364         */
2365        public static final int NO_ERROR = 0;
2366        public static final int CRASHED = 1;
2367        public static final int NOT_RESPONDING = 2;
2368
2369        /**
2370         * The condition that the process is in.
2371         */
2372        public int condition;
2373
2374        /**
2375         * The process name in which the crash or error occurred.
2376         */
2377        public String processName;
2378
2379        /**
2380         * The pid of this process; 0 if none
2381         */
2382        public int pid;
2383
2384        /**
2385         * The kernel user-ID that has been assigned to this process;
2386         * currently this is not a unique ID (multiple applications can have
2387         * the same uid).
2388         */
2389        public int uid;
2390
2391        /**
2392         * The activity name associated with the error, if known.  May be null.
2393         */
2394        public String tag;
2395
2396        /**
2397         * A short message describing the error condition.
2398         */
2399        public String shortMsg;
2400
2401        /**
2402         * A long message describing the error condition.
2403         */
2404        public String longMsg;
2405
2406        /**
2407         * The stack trace where the error originated.  May be null.
2408         */
2409        public String stackTrace;
2410
2411        /**
2412         * to be deprecated: This value will always be null.
2413         */
2414        public byte[] crashData = null;
2415
2416        public ProcessErrorStateInfo() {
2417        }
2418
2419        @Override
2420        public int describeContents() {
2421            return 0;
2422        }
2423
2424        @Override
2425        public void writeToParcel(Parcel dest, int flags) {
2426            dest.writeInt(condition);
2427            dest.writeString(processName);
2428            dest.writeInt(pid);
2429            dest.writeInt(uid);
2430            dest.writeString(tag);
2431            dest.writeString(shortMsg);
2432            dest.writeString(longMsg);
2433            dest.writeString(stackTrace);
2434        }
2435
2436        public void readFromParcel(Parcel source) {
2437            condition = source.readInt();
2438            processName = source.readString();
2439            pid = source.readInt();
2440            uid = source.readInt();
2441            tag = source.readString();
2442            shortMsg = source.readString();
2443            longMsg = source.readString();
2444            stackTrace = source.readString();
2445        }
2446
2447        public static final Creator<ProcessErrorStateInfo> CREATOR =
2448                new Creator<ProcessErrorStateInfo>() {
2449            public ProcessErrorStateInfo createFromParcel(Parcel source) {
2450                return new ProcessErrorStateInfo(source);
2451            }
2452            public ProcessErrorStateInfo[] newArray(int size) {
2453                return new ProcessErrorStateInfo[size];
2454            }
2455        };
2456
2457        private ProcessErrorStateInfo(Parcel source) {
2458            readFromParcel(source);
2459        }
2460    }
2461
2462    /**
2463     * Returns a list of any processes that are currently in an error condition.  The result
2464     * will be null if all processes are running properly at this time.
2465     *
2466     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
2467     * current error conditions (it will not return an empty list).  This list ordering is not
2468     * specified.
2469     */
2470    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
2471        try {
2472            return ActivityManagerNative.getDefault().getProcessesInErrorState();
2473        } catch (RemoteException e) {
2474            return null;
2475        }
2476    }
2477
2478    /**
2479     * Information you can retrieve about a running process.
2480     */
2481    public static class RunningAppProcessInfo implements Parcelable {
2482        /**
2483         * The name of the process that this object is associated with
2484         */
2485        public String processName;
2486
2487        /**
2488         * The pid of this process; 0 if none
2489         */
2490        public int pid;
2491
2492        /**
2493         * The user id of this process.
2494         */
2495        public int uid;
2496
2497        /**
2498         * All packages that have been loaded into the process.
2499         */
2500        public String pkgList[];
2501
2502        /**
2503         * Constant for {@link #flags}: this is an app that is unable to
2504         * correctly save its state when going to the background,
2505         * so it can not be killed while in the background.
2506         * @hide
2507         */
2508        public static final int FLAG_CANT_SAVE_STATE = 1<<0;
2509
2510        /**
2511         * Constant for {@link #flags}: this process is associated with a
2512         * persistent system app.
2513         * @hide
2514         */
2515        public static final int FLAG_PERSISTENT = 1<<1;
2516
2517        /**
2518         * Constant for {@link #flags}: this process is associated with a
2519         * persistent system app.
2520         * @hide
2521         */
2522        public static final int FLAG_HAS_ACTIVITIES = 1<<2;
2523
2524        /**
2525         * Flags of information.  May be any of
2526         * {@link #FLAG_CANT_SAVE_STATE}.
2527         * @hide
2528         */
2529        public int flags;
2530
2531        /**
2532         * Last memory trim level reported to the process: corresponds to
2533         * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
2534         * ComponentCallbacks2.onTrimMemory(int)}.
2535         */
2536        public int lastTrimLevel;
2537
2538        /**
2539         * Constant for {@link #importance}: This process is running the
2540         * foreground UI; that is, it is the thing currently at the top of the screen
2541         * that the user is interacting with.
2542         */
2543        public static final int IMPORTANCE_FOREGROUND = 100;
2544
2545        /**
2546         * Constant for {@link #importance}: This process is running a foreground
2547         * service, for example to perform music playback even while the user is
2548         * not immediately in the app.  This generally indicates that the process
2549         * is doing something the user actively cares about.
2550         */
2551        public static final int IMPORTANCE_FOREGROUND_SERVICE = 125;
2552
2553        /**
2554         * Constant for {@link #importance}: This process is running the foreground
2555         * UI, but the device is asleep so it is not visible to the user.  This means
2556         * the user is not really aware of the process, because they can not see or
2557         * interact with it, but it is quite important because it what they expect to
2558         * return to once unlocking the device.
2559         */
2560        public static final int IMPORTANCE_TOP_SLEEPING = 150;
2561
2562        /**
2563         * Constant for {@link #importance}: This process is running something
2564         * that is actively visible to the user, though not in the immediate
2565         * foreground.  This may be running a window that is behind the current
2566         * foreground (so paused and with its state saved, not interacting with
2567         * the user, but visible to them to some degree); it may also be running
2568         * other services under the system's control that it inconsiders important.
2569         */
2570        public static final int IMPORTANCE_VISIBLE = 200;
2571
2572        /**
2573         * Constant for {@link #importance}: This process is not something the user
2574         * is directly aware of, but is otherwise perceptable to them to some degree.
2575         */
2576        public static final int IMPORTANCE_PERCEPTIBLE = 130;
2577
2578        /**
2579         * Constant for {@link #importance}: This process is running an
2580         * application that can not save its state, and thus can't be killed
2581         * while in the background.
2582         * @hide
2583         */
2584        public static final int IMPORTANCE_CANT_SAVE_STATE = 170;
2585
2586        /**
2587         * Constant for {@link #importance}: This process is contains services
2588         * that should remain running.  These are background services apps have
2589         * started, not something the user is aware of, so they may be killed by
2590         * the system relatively freely (though it is generally desired that they
2591         * stay running as long as they want to).
2592         */
2593        public static final int IMPORTANCE_SERVICE = 300;
2594
2595        /**
2596         * Constant for {@link #importance}: This process process contains
2597         * background code that is expendable.
2598         */
2599        public static final int IMPORTANCE_BACKGROUND = 400;
2600
2601        /**
2602         * Constant for {@link #importance}: This process is empty of any
2603         * actively running code.
2604         */
2605        public static final int IMPORTANCE_EMPTY = 500;
2606
2607        /**
2608         * Constant for {@link #importance}: This process does not exist.
2609         */
2610        public static final int IMPORTANCE_GONE = 1000;
2611
2612        /** @hide */
2613        public static int procStateToImportance(int procState) {
2614            if (procState == PROCESS_STATE_NONEXISTENT) {
2615                return IMPORTANCE_GONE;
2616            } else if (procState >= PROCESS_STATE_HOME) {
2617                return IMPORTANCE_BACKGROUND;
2618            } else if (procState >= PROCESS_STATE_SERVICE) {
2619                return IMPORTANCE_SERVICE;
2620            } else if (procState > PROCESS_STATE_HEAVY_WEIGHT) {
2621                return IMPORTANCE_CANT_SAVE_STATE;
2622            } else if (procState >= PROCESS_STATE_IMPORTANT_BACKGROUND) {
2623                return IMPORTANCE_PERCEPTIBLE;
2624            } else if (procState >= PROCESS_STATE_IMPORTANT_FOREGROUND) {
2625                return IMPORTANCE_VISIBLE;
2626            } else if (procState >= PROCESS_STATE_TOP_SLEEPING) {
2627                return IMPORTANCE_TOP_SLEEPING;
2628            } else if (procState >= PROCESS_STATE_FOREGROUND_SERVICE) {
2629                return IMPORTANCE_FOREGROUND_SERVICE;
2630            } else {
2631                return IMPORTANCE_FOREGROUND;
2632            }
2633        }
2634
2635        /**
2636         * The relative importance level that the system places on this
2637         * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
2638         * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE},
2639         * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}.  These
2640         * constants are numbered so that "more important" values are always
2641         * smaller than "less important" values.
2642         */
2643        public int importance;
2644
2645        /**
2646         * An additional ordering within a particular {@link #importance}
2647         * category, providing finer-grained information about the relative
2648         * utility of processes within a category.  This number means nothing
2649         * except that a smaller values are more recently used (and thus
2650         * more important).  Currently an LRU value is only maintained for
2651         * the {@link #IMPORTANCE_BACKGROUND} category, though others may
2652         * be maintained in the future.
2653         */
2654        public int lru;
2655
2656        /**
2657         * Constant for {@link #importanceReasonCode}: nothing special has
2658         * been specified for the reason for this level.
2659         */
2660        public static final int REASON_UNKNOWN = 0;
2661
2662        /**
2663         * Constant for {@link #importanceReasonCode}: one of the application's
2664         * content providers is being used by another process.  The pid of
2665         * the client process is in {@link #importanceReasonPid} and the
2666         * target provider in this process is in
2667         * {@link #importanceReasonComponent}.
2668         */
2669        public static final int REASON_PROVIDER_IN_USE = 1;
2670
2671        /**
2672         * Constant for {@link #importanceReasonCode}: one of the application's
2673         * content providers is being used by another process.  The pid of
2674         * the client process is in {@link #importanceReasonPid} and the
2675         * target provider in this process is in
2676         * {@link #importanceReasonComponent}.
2677         */
2678        public static final int REASON_SERVICE_IN_USE = 2;
2679
2680        /**
2681         * The reason for {@link #importance}, if any.
2682         */
2683        public int importanceReasonCode;
2684
2685        /**
2686         * For the specified values of {@link #importanceReasonCode}, this
2687         * is the process ID of the other process that is a client of this
2688         * process.  This will be 0 if no other process is using this one.
2689         */
2690        public int importanceReasonPid;
2691
2692        /**
2693         * For the specified values of {@link #importanceReasonCode}, this
2694         * is the name of the component that is being used in this process.
2695         */
2696        public ComponentName importanceReasonComponent;
2697
2698        /**
2699         * When {@link #importanceReasonPid} is non-0, this is the importance
2700         * of the other pid. @hide
2701         */
2702        public int importanceReasonImportance;
2703
2704        /**
2705         * Current process state, as per PROCESS_STATE_* constants.
2706         * @hide
2707         */
2708        public int processState;
2709
2710        public RunningAppProcessInfo() {
2711            importance = IMPORTANCE_FOREGROUND;
2712            importanceReasonCode = REASON_UNKNOWN;
2713            processState = PROCESS_STATE_IMPORTANT_FOREGROUND;
2714        }
2715
2716        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
2717            processName = pProcessName;
2718            pid = pPid;
2719            pkgList = pArr;
2720        }
2721
2722        public int describeContents() {
2723            return 0;
2724        }
2725
2726        public void writeToParcel(Parcel dest, int flags) {
2727            dest.writeString(processName);
2728            dest.writeInt(pid);
2729            dest.writeInt(uid);
2730            dest.writeStringArray(pkgList);
2731            dest.writeInt(this.flags);
2732            dest.writeInt(lastTrimLevel);
2733            dest.writeInt(importance);
2734            dest.writeInt(lru);
2735            dest.writeInt(importanceReasonCode);
2736            dest.writeInt(importanceReasonPid);
2737            ComponentName.writeToParcel(importanceReasonComponent, dest);
2738            dest.writeInt(importanceReasonImportance);
2739            dest.writeInt(processState);
2740        }
2741
2742        public void readFromParcel(Parcel source) {
2743            processName = source.readString();
2744            pid = source.readInt();
2745            uid = source.readInt();
2746            pkgList = source.readStringArray();
2747            flags = source.readInt();
2748            lastTrimLevel = source.readInt();
2749            importance = source.readInt();
2750            lru = source.readInt();
2751            importanceReasonCode = source.readInt();
2752            importanceReasonPid = source.readInt();
2753            importanceReasonComponent = ComponentName.readFromParcel(source);
2754            importanceReasonImportance = source.readInt();
2755            processState = source.readInt();
2756        }
2757
2758        public static final Creator<RunningAppProcessInfo> CREATOR =
2759            new Creator<RunningAppProcessInfo>() {
2760            public RunningAppProcessInfo createFromParcel(Parcel source) {
2761                return new RunningAppProcessInfo(source);
2762            }
2763            public RunningAppProcessInfo[] newArray(int size) {
2764                return new RunningAppProcessInfo[size];
2765            }
2766        };
2767
2768        private RunningAppProcessInfo(Parcel source) {
2769            readFromParcel(source);
2770        }
2771    }
2772
2773    /**
2774     * Returns a list of application processes installed on external media
2775     * that are running on the device.
2776     *
2777     * <p><b>Note: this method is only intended for debugging or building
2778     * a user-facing process management UI.</b></p>
2779     *
2780     * @return Returns a list of ApplicationInfo records, or null if none
2781     * This list ordering is not specified.
2782     * @hide
2783     */
2784    public List<ApplicationInfo> getRunningExternalApplications() {
2785        try {
2786            return ActivityManagerNative.getDefault().getRunningExternalApplications();
2787        } catch (RemoteException e) {
2788            return null;
2789        }
2790    }
2791
2792    /**
2793     * Sets the memory trim mode for a process and schedules a memory trim operation.
2794     *
2795     * <p><b>Note: this method is only intended for testing framework.</b></p>
2796     *
2797     * @return Returns true if successful.
2798     * @hide
2799     */
2800    public boolean setProcessMemoryTrimLevel(String process, int userId, int level) {
2801        try {
2802            return ActivityManagerNative.getDefault().setProcessMemoryTrimLevel(process, userId,
2803                    level);
2804        } catch (RemoteException e) {
2805            return false;
2806        }
2807    }
2808
2809    /**
2810     * Returns a list of application processes that are running on the device.
2811     *
2812     * <p><b>Note: this method is only intended for debugging or building
2813     * a user-facing process management UI.</b></p>
2814     *
2815     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
2816     * running processes (it will not return an empty list).  This list ordering is not
2817     * specified.
2818     */
2819    public List<RunningAppProcessInfo> getRunningAppProcesses() {
2820        try {
2821            return ActivityManagerNative.getDefault().getRunningAppProcesses();
2822        } catch (RemoteException e) {
2823            return null;
2824        }
2825    }
2826
2827    /**
2828     * Return the importance of a given package name, based on the processes that are
2829     * currently running.  The return value is one of the importance constants defined
2830     * in {@link RunningAppProcessInfo}, giving you the highest importance of all the
2831     * processes that this package has code running inside of.  If there are no processes
2832     * running its code, {@link RunningAppProcessInfo#IMPORTANCE_GONE} is returned.
2833     * @hide
2834     */
2835    @SystemApi
2836    public int getPackageImportance(String packageName) {
2837        try {
2838            int procState = ActivityManagerNative.getDefault().getPackageProcessState(packageName,
2839                    mContext.getOpPackageName());
2840            return RunningAppProcessInfo.procStateToImportance(procState);
2841        } catch (RemoteException e) {
2842            return RunningAppProcessInfo.IMPORTANCE_GONE;
2843        }
2844    }
2845
2846    /**
2847     * Return global memory state information for the calling process.  This
2848     * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
2849     * only fields that will be filled in are
2850     * {@link RunningAppProcessInfo#pid},
2851     * {@link RunningAppProcessInfo#uid},
2852     * {@link RunningAppProcessInfo#lastTrimLevel},
2853     * {@link RunningAppProcessInfo#importance},
2854     * {@link RunningAppProcessInfo#lru}, and
2855     * {@link RunningAppProcessInfo#importanceReasonCode}.
2856     */
2857    static public void getMyMemoryState(RunningAppProcessInfo outState) {
2858        try {
2859            ActivityManagerNative.getDefault().getMyMemoryState(outState);
2860        } catch (RemoteException e) {
2861        }
2862    }
2863
2864    /**
2865     * Return information about the memory usage of one or more processes.
2866     *
2867     * <p><b>Note: this method is only intended for debugging or building
2868     * a user-facing process management UI.</b></p>
2869     *
2870     * @param pids The pids of the processes whose memory usage is to be
2871     * retrieved.
2872     * @return Returns an array of memory information, one for each
2873     * requested pid.
2874     */
2875    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
2876        try {
2877            return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids);
2878        } catch (RemoteException e) {
2879            return null;
2880        }
2881    }
2882
2883    /**
2884     * @deprecated This is now just a wrapper for
2885     * {@link #killBackgroundProcesses(String)}; the previous behavior here
2886     * is no longer available to applications because it allows them to
2887     * break other applications by removing their alarms, stopping their
2888     * services, etc.
2889     */
2890    @Deprecated
2891    public void restartPackage(String packageName) {
2892        killBackgroundProcesses(packageName);
2893    }
2894
2895    /**
2896     * Have the system immediately kill all background processes associated
2897     * with the given package.  This is the same as the kernel killing those
2898     * processes to reclaim memory; the system will take care of restarting
2899     * these processes in the future as needed.
2900     *
2901     * <p>You must hold the permission
2902     * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
2903     * call this method.
2904     *
2905     * @param packageName The name of the package whose processes are to
2906     * be killed.
2907     */
2908    public void killBackgroundProcesses(String packageName) {
2909        try {
2910            ActivityManagerNative.getDefault().killBackgroundProcesses(packageName,
2911                    UserHandle.myUserId());
2912        } catch (RemoteException e) {
2913        }
2914    }
2915
2916    /**
2917     * Kills the specified UID.
2918     * @param uid The UID to kill.
2919     * @param reason The reason for the kill.
2920     *
2921     * @hide
2922     */
2923    @RequiresPermission(Manifest.permission.KILL_UID)
2924    public void killUid(int uid, String reason) {
2925        try {
2926            ActivityManagerNative.getDefault().killUid(UserHandle.getAppId(uid),
2927                    UserHandle.getUserId(uid), reason);
2928        } catch (RemoteException e) {
2929            Log.e(TAG, "Couldn't kill uid:" + uid, e);
2930        }
2931    }
2932
2933    /**
2934     * Have the system perform a force stop of everything associated with
2935     * the given application package.  All processes that share its uid
2936     * will be killed, all services it has running stopped, all activities
2937     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
2938     * broadcast will be sent, so that any of its registered alarms can
2939     * be stopped, notifications removed, etc.
2940     *
2941     * <p>You must hold the permission
2942     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
2943     * call this method.
2944     *
2945     * @param packageName The name of the package to be stopped.
2946     * @param userId The user for which the running package is to be stopped.
2947     *
2948     * @hide This is not available to third party applications due to
2949     * it allowing them to break other applications by stopping their
2950     * services, removing their alarms, etc.
2951     */
2952    public void forceStopPackageAsUser(String packageName, int userId) {
2953        try {
2954            ActivityManagerNative.getDefault().forceStopPackage(packageName, userId);
2955        } catch (RemoteException e) {
2956        }
2957    }
2958
2959    /**
2960     * @see #forceStopPackageAsUser(String, int)
2961     * @hide
2962     */
2963    public void forceStopPackage(String packageName) {
2964        forceStopPackageAsUser(packageName, UserHandle.myUserId());
2965    }
2966
2967    /**
2968     * Get the device configuration attributes.
2969     */
2970    public ConfigurationInfo getDeviceConfigurationInfo() {
2971        try {
2972            return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
2973        } catch (RemoteException e) {
2974        }
2975        return null;
2976    }
2977
2978    /**
2979     * Get the preferred density of icons for the launcher. This is used when
2980     * custom drawables are created (e.g., for shortcuts).
2981     *
2982     * @return density in terms of DPI
2983     */
2984    public int getLauncherLargeIconDensity() {
2985        final Resources res = mContext.getResources();
2986        final int density = res.getDisplayMetrics().densityDpi;
2987        final int sw = res.getConfiguration().smallestScreenWidthDp;
2988
2989        if (sw < 600) {
2990            // Smaller than approx 7" tablets, use the regular icon size.
2991            return density;
2992        }
2993
2994        switch (density) {
2995            case DisplayMetrics.DENSITY_LOW:
2996                return DisplayMetrics.DENSITY_MEDIUM;
2997            case DisplayMetrics.DENSITY_MEDIUM:
2998                return DisplayMetrics.DENSITY_HIGH;
2999            case DisplayMetrics.DENSITY_TV:
3000                return DisplayMetrics.DENSITY_XHIGH;
3001            case DisplayMetrics.DENSITY_HIGH:
3002                return DisplayMetrics.DENSITY_XHIGH;
3003            case DisplayMetrics.DENSITY_XHIGH:
3004                return DisplayMetrics.DENSITY_XXHIGH;
3005            case DisplayMetrics.DENSITY_XXHIGH:
3006                return DisplayMetrics.DENSITY_XHIGH * 2;
3007            default:
3008                // The density is some abnormal value.  Return some other
3009                // abnormal value that is a reasonable scaling of it.
3010                return (int)((density*1.5f)+.5f);
3011        }
3012    }
3013
3014    /**
3015     * Get the preferred launcher icon size. This is used when custom drawables
3016     * are created (e.g., for shortcuts).
3017     *
3018     * @return dimensions of square icons in terms of pixels
3019     */
3020    public int getLauncherLargeIconSize() {
3021        return getLauncherLargeIconSizeInner(mContext);
3022    }
3023
3024    static int getLauncherLargeIconSizeInner(Context context) {
3025        final Resources res = context.getResources();
3026        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
3027        final int sw = res.getConfiguration().smallestScreenWidthDp;
3028
3029        if (sw < 600) {
3030            // Smaller than approx 7" tablets, use the regular icon size.
3031            return size;
3032        }
3033
3034        final int density = res.getDisplayMetrics().densityDpi;
3035
3036        switch (density) {
3037            case DisplayMetrics.DENSITY_LOW:
3038                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
3039            case DisplayMetrics.DENSITY_MEDIUM:
3040                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
3041            case DisplayMetrics.DENSITY_TV:
3042                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
3043            case DisplayMetrics.DENSITY_HIGH:
3044                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
3045            case DisplayMetrics.DENSITY_XHIGH:
3046                return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
3047            case DisplayMetrics.DENSITY_XXHIGH:
3048                return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
3049            default:
3050                // The density is some abnormal value.  Return some other
3051                // abnormal value that is a reasonable scaling of it.
3052                return (int)((size*1.5f) + .5f);
3053        }
3054    }
3055
3056    /**
3057     * Returns "true" if the user interface is currently being messed with
3058     * by a monkey.
3059     */
3060    public static boolean isUserAMonkey() {
3061        try {
3062            return ActivityManagerNative.getDefault().isUserAMonkey();
3063        } catch (RemoteException e) {
3064        }
3065        return false;
3066    }
3067
3068    /**
3069     * Returns "true" if device is running in a test harness.
3070     */
3071    public static boolean isRunningInTestHarness() {
3072        return SystemProperties.getBoolean("ro.test_harness", false);
3073    }
3074
3075    /**
3076     * Returns the launch count of each installed package.
3077     *
3078     * @hide
3079     */
3080    /*public Map<String, Integer> getAllPackageLaunchCounts() {
3081        try {
3082            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
3083                    ServiceManager.getService("usagestats"));
3084            if (usageStatsService == null) {
3085                return new HashMap<String, Integer>();
3086            }
3087
3088            UsageStats.PackageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats(
3089                    ActivityThread.currentPackageName());
3090            if (allPkgUsageStats == null) {
3091                return new HashMap<String, Integer>();
3092            }
3093
3094            Map<String, Integer> launchCounts = new HashMap<String, Integer>();
3095            for (UsageStats.PackageStats pkgUsageStats : allPkgUsageStats) {
3096                launchCounts.put(pkgUsageStats.getPackageName(), pkgUsageStats.getLaunchCount());
3097            }
3098
3099            return launchCounts;
3100        } catch (RemoteException e) {
3101            Log.w(TAG, "Could not query launch counts", e);
3102            return new HashMap<String, Integer>();
3103        }
3104    }*/
3105
3106    /** @hide */
3107    public static int checkComponentPermission(String permission, int uid,
3108            int owningUid, boolean exported) {
3109        // Root, system server get to do everything.
3110        final int appId = UserHandle.getAppId(uid);
3111        if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
3112            return PackageManager.PERMISSION_GRANTED;
3113        }
3114        // Isolated processes don't get any permissions.
3115        if (UserHandle.isIsolated(uid)) {
3116            return PackageManager.PERMISSION_DENIED;
3117        }
3118        // If there is a uid that owns whatever is being accessed, it has
3119        // blanket access to it regardless of the permissions it requires.
3120        if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
3121            return PackageManager.PERMISSION_GRANTED;
3122        }
3123        // If the target is not exported, then nobody else can get to it.
3124        if (!exported) {
3125            /*
3126            RuntimeException here = new RuntimeException("here");
3127            here.fillInStackTrace();
3128            Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
3129                    here);
3130            */
3131            return PackageManager.PERMISSION_DENIED;
3132        }
3133        if (permission == null) {
3134            return PackageManager.PERMISSION_GRANTED;
3135        }
3136        try {
3137            return AppGlobals.getPackageManager()
3138                    .checkUidPermission(permission, uid);
3139        } catch (RemoteException e) {
3140            // Should never happen, but if it does... deny!
3141            Slog.e(TAG, "PackageManager is dead?!?", e);
3142        }
3143        return PackageManager.PERMISSION_DENIED;
3144    }
3145
3146    /** @hide */
3147    public static int checkUidPermission(String permission, int uid) {
3148        try {
3149            return AppGlobals.getPackageManager()
3150                    .checkUidPermission(permission, uid);
3151        } catch (RemoteException e) {
3152            // Should never happen, but if it does... deny!
3153            Slog.e(TAG, "PackageManager is dead?!?", e);
3154        }
3155        return PackageManager.PERMISSION_DENIED;
3156    }
3157
3158    /**
3159     * @hide
3160     * Helper for dealing with incoming user arguments to system service calls.
3161     * Takes care of checking permissions and converting USER_CURRENT to the
3162     * actual current user.
3163     *
3164     * @param callingPid The pid of the incoming call, as per Binder.getCallingPid().
3165     * @param callingUid The uid of the incoming call, as per Binder.getCallingUid().
3166     * @param userId The user id argument supplied by the caller -- this is the user
3167     * they want to run as.
3168     * @param allowAll If true, we will allow USER_ALL.  This means you must be prepared
3169     * to get a USER_ALL returned and deal with it correctly.  If false,
3170     * an exception will be thrown if USER_ALL is supplied.
3171     * @param requireFull If true, the caller must hold
3172     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a
3173     * different user than their current process; otherwise they must hold
3174     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
3175     * @param name Optional textual name of the incoming call; only for generating error messages.
3176     * @param callerPackage Optional package name of caller; only for error messages.
3177     *
3178     * @return Returns the user ID that the call should run as.  Will always be a concrete
3179     * user number, unless <var>allowAll</var> is true in which case it could also be
3180     * USER_ALL.
3181     */
3182    public static int handleIncomingUser(int callingPid, int callingUid, int userId,
3183            boolean allowAll, boolean requireFull, String name, String callerPackage) {
3184        if (UserHandle.getUserId(callingUid) == userId) {
3185            return userId;
3186        }
3187        try {
3188            return ActivityManagerNative.getDefault().handleIncomingUser(callingPid,
3189                    callingUid, userId, allowAll, requireFull, name, callerPackage);
3190        } catch (RemoteException e) {
3191            throw new SecurityException("Failed calling activity manager", e);
3192        }
3193    }
3194
3195    /**
3196     * Gets the userId of the current foreground user. Requires system permissions.
3197     * @hide
3198     */
3199    @SystemApi
3200    public static int getCurrentUser() {
3201        UserInfo ui;
3202        try {
3203            ui = ActivityManagerNative.getDefault().getCurrentUser();
3204            return ui != null ? ui.id : 0;
3205        } catch (RemoteException e) {
3206            return 0;
3207        }
3208    }
3209
3210    /**
3211     * @param userid the user's id. Zero indicates the default user.
3212     * @hide
3213     */
3214    public boolean switchUser(int userid) {
3215        try {
3216            return ActivityManagerNative.getDefault().switchUser(userid);
3217        } catch (RemoteException e) {
3218            return false;
3219        }
3220    }
3221
3222    /** {@hide} */
3223    public static final int FLAG_OR_STOPPED = 1 << 0;
3224    /** {@hide} */
3225    public static final int FLAG_AND_LOCKED = 1 << 1;
3226    /** {@hide} */
3227    public static final int FLAG_AND_UNLOCKED = 1 << 2;
3228
3229    /**
3230     * Return whether the given user is actively running.  This means that
3231     * the user is in the "started" state, not "stopped" -- it is currently
3232     * allowed to run code through scheduled alarms, receiving broadcasts,
3233     * etc.  A started user may be either the current foreground user or a
3234     * background user; the result here does not distinguish between the two.
3235     * @param userid the user's id. Zero indicates the default user.
3236     * @hide
3237     */
3238    public boolean isUserRunning(int userId) {
3239        try {
3240            return ActivityManagerNative.getDefault().isUserRunning(userId, 0);
3241        } catch (RemoteException e) {
3242            return false;
3243        }
3244    }
3245
3246    /** {@hide} */
3247    public boolean isUserRunningAndLocked(int userId) {
3248        try {
3249            return ActivityManagerNative.getDefault().isUserRunning(userId,
3250                    ActivityManager.FLAG_AND_LOCKED);
3251        } catch (RemoteException e) {
3252            return false;
3253        }
3254    }
3255
3256    /** {@hide} */
3257    public boolean isUserRunningAndUnlocked(int userId) {
3258        try {
3259            return ActivityManagerNative.getDefault().isUserRunning(userId,
3260                    ActivityManager.FLAG_AND_UNLOCKED);
3261        } catch (RemoteException e) {
3262            return false;
3263        }
3264    }
3265
3266    /**
3267     * Perform a system dump of various state associated with the given application
3268     * package name.  This call blocks while the dump is being performed, so should
3269     * not be done on a UI thread.  The data will be written to the given file
3270     * descriptor as text.  An application must hold the
3271     * {@link android.Manifest.permission#DUMP} permission to make this call.
3272     * @param fd The file descriptor that the dump should be written to.  The file
3273     * descriptor is <em>not</em> closed by this function; the caller continues to
3274     * own it.
3275     * @param packageName The name of the package that is to be dumped.
3276     */
3277    public void dumpPackageState(FileDescriptor fd, String packageName) {
3278        dumpPackageStateStatic(fd, packageName);
3279    }
3280
3281    /**
3282     * @hide
3283     */
3284    public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) {
3285        FileOutputStream fout = new FileOutputStream(fd);
3286        PrintWriter pw = new FastPrintWriter(fout);
3287        dumpService(pw, fd, "package", new String[] { packageName });
3288        pw.println();
3289        dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] {
3290                "-a", "package", packageName });
3291        pw.println();
3292        dumpService(pw, fd, "meminfo", new String[] { "--local", "--package", packageName });
3293        pw.println();
3294        dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { packageName });
3295        pw.println();
3296        dumpService(pw, fd, "usagestats", new String[] { "--packages", packageName });
3297        pw.println();
3298        dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName });
3299        pw.flush();
3300    }
3301
3302    private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) {
3303        pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
3304        IBinder service = ServiceManager.checkService(name);
3305        if (service == null) {
3306            pw.println("  (Service not found)");
3307            return;
3308        }
3309        TransferPipe tp = null;
3310        try {
3311            pw.flush();
3312            tp = new TransferPipe();
3313            tp.setBufferPrefix("  ");
3314            service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args);
3315            tp.go(fd, 10000);
3316        } catch (Throwable e) {
3317            if (tp != null) {
3318                tp.kill();
3319            }
3320            pw.println("Failure dumping service:");
3321            e.printStackTrace(pw);
3322        }
3323    }
3324
3325    /**
3326     * Request that the system start watching for the calling process to exceed a pss
3327     * size as given here.  Once called, the system will look for any occasions where it
3328     * sees the associated process with a larger pss size and, when this happens, automatically
3329     * pull a heap dump from it and allow the user to share the data.  Note that this request
3330     * continues running even if the process is killed and restarted.  To remove the watch,
3331     * use {@link #clearWatchHeapLimit()}.
3332     *
3333     * <p>This API only work if the calling process has been marked as
3334     * {@link ApplicationInfo#FLAG_DEBUGGABLE} or this is running on a debuggable
3335     * (userdebug or eng) build.</p>
3336     *
3337     * <p>Callers can optionally implement {@link #ACTION_REPORT_HEAP_LIMIT} to directly
3338     * handle heap limit reports themselves.</p>
3339     *
3340     * @param pssSize The size in bytes to set the limit at.
3341     */
3342    public void setWatchHeapLimit(long pssSize) {
3343        try {
3344            ActivityManagerNative.getDefault().setDumpHeapDebugLimit(null, 0, pssSize,
3345                    mContext.getPackageName());
3346        } catch (RemoteException e) {
3347        }
3348    }
3349
3350    /**
3351     * Action an app can implement to handle reports from {@link #setWatchHeapLimit(long)}.
3352     * If your package has an activity handling this action, it will be launched with the
3353     * heap data provided to it the same way as {@link Intent#ACTION_SEND}.  Note that to
3354     * match the activty must support this action and a MIME type of "*&#47;*".
3355     */
3356    public static final String ACTION_REPORT_HEAP_LIMIT = "android.app.action.REPORT_HEAP_LIMIT";
3357
3358    /**
3359     * Clear a heap watch limit previously set by {@link #setWatchHeapLimit(long)}.
3360     */
3361    public void clearWatchHeapLimit() {
3362        try {
3363            ActivityManagerNative.getDefault().setDumpHeapDebugLimit(null, 0, 0, null);
3364        } catch (RemoteException e) {
3365        }
3366    }
3367
3368    /**
3369     * @hide
3370     */
3371    public void startLockTaskMode(int taskId) {
3372        try {
3373            ActivityManagerNative.getDefault().startLockTaskMode(taskId);
3374        } catch (RemoteException e) {
3375        }
3376    }
3377
3378    /**
3379     * @hide
3380     */
3381    public void stopLockTaskMode() {
3382        try {
3383            ActivityManagerNative.getDefault().stopLockTaskMode();
3384        } catch (RemoteException e) {
3385        }
3386    }
3387
3388    /**
3389     * Return whether currently in lock task mode.  When in this mode
3390     * no new tasks can be created or switched to.
3391     *
3392     * @see Activity#startLockTask()
3393     *
3394     * @deprecated Use {@link #getLockTaskModeState} instead.
3395     */
3396    public boolean isInLockTaskMode() {
3397        return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3398    }
3399
3400    /**
3401     * Return the current state of task locking. The three possible outcomes
3402     * are {@link #LOCK_TASK_MODE_NONE}, {@link #LOCK_TASK_MODE_LOCKED}
3403     * and {@link #LOCK_TASK_MODE_PINNED}.
3404     *
3405     * @see Activity#startLockTask()
3406     */
3407    public int getLockTaskModeState() {
3408        try {
3409            return ActivityManagerNative.getDefault().getLockTaskModeState();
3410        } catch (RemoteException e) {
3411            return ActivityManager.LOCK_TASK_MODE_NONE;
3412        }
3413    }
3414
3415    /**
3416     * The AppTask allows you to manage your own application's tasks.
3417     * See {@link android.app.ActivityManager#getAppTasks()}
3418     */
3419    public static class AppTask {
3420        private IAppTask mAppTaskImpl;
3421
3422        /** @hide */
3423        public AppTask(IAppTask task) {
3424            mAppTaskImpl = task;
3425        }
3426
3427        /**
3428         * Finishes all activities in this task and removes it from the recent tasks list.
3429         */
3430        public void finishAndRemoveTask() {
3431            try {
3432                mAppTaskImpl.finishAndRemoveTask();
3433            } catch (RemoteException e) {
3434                Slog.e(TAG, "Invalid AppTask", e);
3435            }
3436        }
3437
3438        /**
3439         * Get the RecentTaskInfo associated with this task.
3440         *
3441         * @return The RecentTaskInfo for this task, or null if the task no longer exists.
3442         */
3443        public RecentTaskInfo getTaskInfo() {
3444            try {
3445                return mAppTaskImpl.getTaskInfo();
3446            } catch (RemoteException e) {
3447                Slog.e(TAG, "Invalid AppTask", e);
3448                return null;
3449            }
3450        }
3451
3452        /**
3453         * Bring this task to the foreground.  If it contains activities, they will be
3454         * brought to the foreground with it and their instances re-created if needed.
3455         * If it doesn't contain activities, the root activity of the task will be
3456         * re-launched.
3457         */
3458        public void moveToFront() {
3459            try {
3460                mAppTaskImpl.moveToFront();
3461            } catch (RemoteException e) {
3462                Slog.e(TAG, "Invalid AppTask", e);
3463            }
3464        }
3465
3466        /**
3467         * Start an activity in this task.  Brings the task to the foreground.  If this task
3468         * is not currently active (that is, its id < 0), then a new activity for the given
3469         * Intent will be launched as the root of the task and the task brought to the
3470         * foreground.  Otherwise, if this task is currently active and the Intent does not specify
3471         * an activity to launch in a new task, then a new activity for the given Intent will
3472         * be launched on top of the task and the task brought to the foreground.  If this
3473         * task is currently active and the Intent specifies {@link Intent#FLAG_ACTIVITY_NEW_TASK}
3474         * or would otherwise be launched in to a new task, then the activity not launched but
3475         * this task be brought to the foreground and a new intent delivered to the top
3476         * activity if appropriate.
3477         *
3478         * <p>In other words, you generally want to use an Intent here that does not specify
3479         * {@link Intent#FLAG_ACTIVITY_NEW_TASK} or {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT},
3480         * and let the system do the right thing.</p>
3481         *
3482         * @param intent The Intent describing the new activity to be launched on the task.
3483         * @param options Optional launch options.
3484         *
3485         * @see Activity#startActivity(android.content.Intent, android.os.Bundle)
3486         */
3487        public void startActivity(Context context, Intent intent, Bundle options) {
3488            ActivityThread thread = ActivityThread.currentActivityThread();
3489            thread.getInstrumentation().execStartActivityFromAppTask(context,
3490                    thread.getApplicationThread(), mAppTaskImpl, intent, options);
3491        }
3492
3493        /**
3494         * Modify the {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag in the root
3495         * Intent of this AppTask.
3496         *
3497         * @param exclude If true, {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} will
3498         * be set; otherwise, it will be cleared.
3499         */
3500        public void setExcludeFromRecents(boolean exclude) {
3501            try {
3502                mAppTaskImpl.setExcludeFromRecents(exclude);
3503            } catch (RemoteException e) {
3504                Slog.e(TAG, "Invalid AppTask", e);
3505            }
3506        }
3507    }
3508}
3509