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