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