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