ActivityManager.java revision 388945c01d4e00701e0157c96390eeac4b307b8a
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_SPLIT_SCREEN_PRIMARY;
20import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
21import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
22import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
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        public RecentTaskInfo() {
1539        }
1540
1541        @Override
1542        public int describeContents() {
1543            return 0;
1544        }
1545
1546        @Override
1547        public void writeToParcel(Parcel dest, int flags) {
1548            dest.writeInt(id);
1549            dest.writeInt(persistentId);
1550            if (baseIntent != null) {
1551                dest.writeInt(1);
1552                baseIntent.writeToParcel(dest, 0);
1553            } else {
1554                dest.writeInt(0);
1555            }
1556            ComponentName.writeToParcel(origActivity, dest);
1557            ComponentName.writeToParcel(realActivity, dest);
1558            TextUtils.writeToParcel(description, dest,
1559                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1560            if (taskDescription != null) {
1561                dest.writeInt(1);
1562                taskDescription.writeToParcel(dest, 0);
1563            } else {
1564                dest.writeInt(0);
1565            }
1566            dest.writeInt(stackId);
1567            dest.writeInt(userId);
1568            dest.writeLong(firstActiveTime);
1569            dest.writeLong(lastActiveTime);
1570            dest.writeInt(affiliatedTaskId);
1571            dest.writeInt(affiliatedTaskColor);
1572            ComponentName.writeToParcel(baseActivity, dest);
1573            ComponentName.writeToParcel(topActivity, dest);
1574            dest.writeInt(numActivities);
1575            if (bounds != null) {
1576                dest.writeInt(1);
1577                bounds.writeToParcel(dest, 0);
1578            } else {
1579                dest.writeInt(0);
1580            }
1581            dest.writeInt(supportsSplitScreenMultiWindow ? 1 : 0);
1582            dest.writeInt(resizeMode);
1583        }
1584
1585        public void readFromParcel(Parcel source) {
1586            id = source.readInt();
1587            persistentId = source.readInt();
1588            baseIntent = source.readInt() > 0 ? Intent.CREATOR.createFromParcel(source) : null;
1589            origActivity = ComponentName.readFromParcel(source);
1590            realActivity = ComponentName.readFromParcel(source);
1591            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
1592            taskDescription = source.readInt() > 0 ?
1593                    TaskDescription.CREATOR.createFromParcel(source) : null;
1594            stackId = source.readInt();
1595            userId = source.readInt();
1596            firstActiveTime = source.readLong();
1597            lastActiveTime = source.readLong();
1598            affiliatedTaskId = source.readInt();
1599            affiliatedTaskColor = source.readInt();
1600            baseActivity = ComponentName.readFromParcel(source);
1601            topActivity = ComponentName.readFromParcel(source);
1602            numActivities = source.readInt();
1603            bounds = source.readInt() > 0 ?
1604                    Rect.CREATOR.createFromParcel(source) : null;
1605            supportsSplitScreenMultiWindow = source.readInt() == 1;
1606            resizeMode = source.readInt();
1607        }
1608
1609        public static final Creator<RecentTaskInfo> CREATOR
1610                = new Creator<RecentTaskInfo>() {
1611            public RecentTaskInfo createFromParcel(Parcel source) {
1612                return new RecentTaskInfo(source);
1613            }
1614            public RecentTaskInfo[] newArray(int size) {
1615                return new RecentTaskInfo[size];
1616            }
1617        };
1618
1619        private RecentTaskInfo(Parcel source) {
1620            readFromParcel(source);
1621        }
1622    }
1623
1624    /**
1625     * Flag for use with {@link #getRecentTasks}: return all tasks, even those
1626     * that have set their
1627     * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
1628     */
1629    public static final int RECENT_WITH_EXCLUDED = 0x0001;
1630
1631    /**
1632     * Provides a list that does not contain any
1633     * recent tasks that currently are not available to the user.
1634     */
1635    public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002;
1636
1637    /**
1638     * Provides a list that contains recent tasks for all
1639     * profiles of a user.
1640     * @hide
1641     */
1642    public static final int RECENT_INCLUDE_PROFILES = 0x0004;
1643
1644    /**
1645     * Ignores all tasks that are on the home stack.
1646     * @hide
1647     */
1648    public static final int RECENT_IGNORE_HOME_AND_RECENTS_STACK_TASKS = 0x0008;
1649
1650    /**
1651     * Ignores the top task in the docked stack.
1652     * @hide
1653     */
1654    public static final int RECENT_INGORE_DOCKED_STACK_TOP_TASK = 0x0010;
1655
1656    /**
1657     * Ignores all tasks that are on the pinned stack.
1658     * @hide
1659     */
1660    public static final int RECENT_INGORE_PINNED_STACK_TASKS = 0x0020;
1661
1662    /**
1663     * <p></p>Return a list of the tasks that the user has recently launched, with
1664     * the most recent being first and older ones after in order.
1665     *
1666     * <p><b>Note: this method is only intended for debugging and presenting
1667     * task management user interfaces</b>.  This should never be used for
1668     * core logic in an application, such as deciding between different
1669     * behaviors based on the information found here.  Such uses are
1670     * <em>not</em> supported, and will likely break in the future.  For
1671     * example, if multiple applications can be actively running at the
1672     * same time, assumptions made about the meaning of the data here for
1673     * purposes of control flow will be incorrect.</p>
1674     *
1675     * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method is
1676     * no longer available to third party applications: the introduction of
1677     * document-centric recents means
1678     * it can leak personal information to the caller.  For backwards compatibility,
1679     * it will still return a small subset of its data: at least the caller's
1680     * own tasks (though see {@link #getAppTasks()} for the correct supported
1681     * way to retrieve that information), and possibly some other tasks
1682     * such as home that are known to not be sensitive.
1683     *
1684     * @param maxNum The maximum number of entries to return in the list.  The
1685     * actual number returned may be smaller, depending on how many tasks the
1686     * user has started and the maximum number the system can remember.
1687     * @param flags Information about what to return.  May be any combination
1688     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
1689     *
1690     * @return Returns a list of RecentTaskInfo records describing each of
1691     * the recent tasks.
1692     */
1693    @Deprecated
1694    public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags)
1695            throws SecurityException {
1696        try {
1697            return getService().getRecentTasks(maxNum,
1698                    flags, UserHandle.myUserId()).getList();
1699        } catch (RemoteException e) {
1700            throw e.rethrowFromSystemServer();
1701        }
1702    }
1703
1704    /**
1705     * Same as {@link #getRecentTasks(int, int)} but returns the recent tasks for a
1706     * specific user. It requires holding
1707     * the {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
1708     * @param maxNum The maximum number of entries to return in the list.  The
1709     * actual number returned may be smaller, depending on how many tasks the
1710     * user has started and the maximum number the system can remember.
1711     * @param flags Information about what to return.  May be any combination
1712     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
1713     *
1714     * @return Returns a list of RecentTaskInfo records describing each of
1715     * the recent tasks. Most recently activated tasks go first.
1716     *
1717     * @hide
1718     */
1719    public List<RecentTaskInfo> getRecentTasksForUser(int maxNum, int flags, int userId)
1720            throws SecurityException {
1721        try {
1722            return getService().getRecentTasks(maxNum,
1723                    flags, userId).getList();
1724        } catch (RemoteException e) {
1725            throw e.rethrowFromSystemServer();
1726        }
1727    }
1728
1729    /**
1730     * Information you can retrieve about a particular task that is currently
1731     * "running" in the system.  Note that a running task does not mean the
1732     * given task actually has a process it is actively running in; it simply
1733     * means that the user has gone to it and never closed it, but currently
1734     * the system may have killed its process and is only holding on to its
1735     * last state in order to restart it when the user returns.
1736     */
1737    public static class RunningTaskInfo implements Parcelable {
1738        /**
1739         * A unique identifier for this task.
1740         */
1741        public int id;
1742
1743        /**
1744         * The stack that currently contains this task.
1745         * @hide
1746         */
1747        public int stackId;
1748
1749        /**
1750         * The component launched as the first activity in the task.  This can
1751         * be considered the "application" of this task.
1752         */
1753        public ComponentName baseActivity;
1754
1755        /**
1756         * The activity component at the top of the history stack of the task.
1757         * This is what the user is currently doing.
1758         */
1759        public ComponentName topActivity;
1760
1761        /**
1762         * Thumbnail representation of the task's current state.  Currently
1763         * always null.
1764         */
1765        public Bitmap thumbnail;
1766
1767        /**
1768         * Description of the task's current state.
1769         */
1770        public CharSequence description;
1771
1772        /**
1773         * Number of activities in this task.
1774         */
1775        public int numActivities;
1776
1777        /**
1778         * Number of activities that are currently running (not stopped
1779         * and persisted) in this task.
1780         */
1781        public int numRunning;
1782
1783        /**
1784         * Last time task was run. For sorting.
1785         * @hide
1786         */
1787        public long lastActiveTime;
1788
1789        /**
1790         * True if the task can go in the docked stack.
1791         * @hide
1792         */
1793        public boolean supportsSplitScreenMultiWindow;
1794
1795        /**
1796         * The resize mode of the task. See {@link ActivityInfo#resizeMode}.
1797         * @hide
1798         */
1799        public int resizeMode;
1800
1801        /**
1802         * The full configuration the task is currently running in.
1803         * @hide
1804         */
1805        public Configuration configuration = new Configuration();
1806
1807        public RunningTaskInfo() {
1808        }
1809
1810        public int describeContents() {
1811            return 0;
1812        }
1813
1814        public void writeToParcel(Parcel dest, int flags) {
1815            dest.writeInt(id);
1816            dest.writeInt(stackId);
1817            ComponentName.writeToParcel(baseActivity, dest);
1818            ComponentName.writeToParcel(topActivity, dest);
1819            if (thumbnail != null) {
1820                dest.writeInt(1);
1821                thumbnail.writeToParcel(dest, 0);
1822            } else {
1823                dest.writeInt(0);
1824            }
1825            TextUtils.writeToParcel(description, dest,
1826                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1827            dest.writeInt(numActivities);
1828            dest.writeInt(numRunning);
1829            dest.writeInt(supportsSplitScreenMultiWindow ? 1 : 0);
1830            dest.writeInt(resizeMode);
1831            configuration.writeToParcel(dest, flags);
1832        }
1833
1834        public void readFromParcel(Parcel source) {
1835            id = source.readInt();
1836            stackId = source.readInt();
1837            baseActivity = ComponentName.readFromParcel(source);
1838            topActivity = ComponentName.readFromParcel(source);
1839            if (source.readInt() != 0) {
1840                thumbnail = Bitmap.CREATOR.createFromParcel(source);
1841            } else {
1842                thumbnail = null;
1843            }
1844            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
1845            numActivities = source.readInt();
1846            numRunning = source.readInt();
1847            supportsSplitScreenMultiWindow = source.readInt() != 0;
1848            resizeMode = source.readInt();
1849            configuration.readFromParcel(source);
1850        }
1851
1852        public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
1853            public RunningTaskInfo createFromParcel(Parcel source) {
1854                return new RunningTaskInfo(source);
1855            }
1856            public RunningTaskInfo[] newArray(int size) {
1857                return new RunningTaskInfo[size];
1858            }
1859        };
1860
1861        private RunningTaskInfo(Parcel source) {
1862            readFromParcel(source);
1863        }
1864    }
1865
1866    /**
1867     * Get the list of tasks associated with the calling application.
1868     *
1869     * @return The list of tasks associated with the application making this call.
1870     * @throws SecurityException
1871     */
1872    public List<ActivityManager.AppTask> getAppTasks() {
1873        ArrayList<AppTask> tasks = new ArrayList<AppTask>();
1874        List<IBinder> appTasks;
1875        try {
1876            appTasks = getService().getAppTasks(mContext.getPackageName());
1877        } catch (RemoteException e) {
1878            throw e.rethrowFromSystemServer();
1879        }
1880        int numAppTasks = appTasks.size();
1881        for (int i = 0; i < numAppTasks; i++) {
1882            tasks.add(new AppTask(IAppTask.Stub.asInterface(appTasks.get(i))));
1883        }
1884        return tasks;
1885    }
1886
1887    /**
1888     * Return the current design dimensions for {@link AppTask} thumbnails, for use
1889     * with {@link #addAppTask}.
1890     */
1891    public Size getAppTaskThumbnailSize() {
1892        synchronized (this) {
1893            ensureAppTaskThumbnailSizeLocked();
1894            return new Size(mAppTaskThumbnailSize.x, mAppTaskThumbnailSize.y);
1895        }
1896    }
1897
1898    private void ensureAppTaskThumbnailSizeLocked() {
1899        if (mAppTaskThumbnailSize == null) {
1900            try {
1901                mAppTaskThumbnailSize = getService().getAppTaskThumbnailSize();
1902            } catch (RemoteException e) {
1903                throw e.rethrowFromSystemServer();
1904            }
1905        }
1906    }
1907
1908    /**
1909     * Add a new {@link AppTask} for the calling application.  This will create a new
1910     * recents entry that is added to the <b>end</b> of all existing recents.
1911     *
1912     * @param activity The activity that is adding the entry.   This is used to help determine
1913     * the context that the new recents entry will be in.
1914     * @param intent The Intent that describes the recents entry.  This is the same Intent that
1915     * you would have used to launch the activity for it.  In generally you will want to set
1916     * both {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT} and
1917     * {@link Intent#FLAG_ACTIVITY_RETAIN_IN_RECENTS}; the latter is required since this recents
1918     * entry will exist without an activity, so it doesn't make sense to not retain it when
1919     * its activity disappears.  The given Intent here also must have an explicit ComponentName
1920     * set on it.
1921     * @param description Optional additional description information.
1922     * @param thumbnail Thumbnail to use for the recents entry.  Should be the size given by
1923     * {@link #getAppTaskThumbnailSize()}.  If the bitmap is not that exact size, it will be
1924     * recreated in your process, probably in a way you don't like, before the recents entry
1925     * is added.
1926     *
1927     * @return Returns the task id of the newly added app task, or -1 if the add failed.  The
1928     * most likely cause of failure is that there is no more room for more tasks for your app.
1929     */
1930    public int addAppTask(@NonNull Activity activity, @NonNull Intent intent,
1931            @Nullable TaskDescription description, @NonNull Bitmap thumbnail) {
1932        Point size;
1933        synchronized (this) {
1934            ensureAppTaskThumbnailSizeLocked();
1935            size = mAppTaskThumbnailSize;
1936        }
1937        final int tw = thumbnail.getWidth();
1938        final int th = thumbnail.getHeight();
1939        if (tw != size.x || th != size.y) {
1940            Bitmap bm = Bitmap.createBitmap(size.x, size.y, thumbnail.getConfig());
1941
1942            // Use ScaleType.CENTER_CROP, except we leave the top edge at the top.
1943            float scale;
1944            float dx = 0, dy = 0;
1945            if (tw * size.x > size.y * th) {
1946                scale = (float) size.x / (float) th;
1947                dx = (size.y - tw * scale) * 0.5f;
1948            } else {
1949                scale = (float) size.y / (float) tw;
1950                dy = (size.x - th * scale) * 0.5f;
1951            }
1952            Matrix matrix = new Matrix();
1953            matrix.setScale(scale, scale);
1954            matrix.postTranslate((int) (dx + 0.5f), 0);
1955
1956            Canvas canvas = new Canvas(bm);
1957            canvas.drawBitmap(thumbnail, matrix, null);
1958            canvas.setBitmap(null);
1959
1960            thumbnail = bm;
1961        }
1962        if (description == null) {
1963            description = new TaskDescription();
1964        }
1965        try {
1966            return getService().addAppTask(activity.getActivityToken(),
1967                    intent, description, thumbnail);
1968        } catch (RemoteException e) {
1969            throw e.rethrowFromSystemServer();
1970        }
1971    }
1972
1973    /**
1974     * Return a list of the tasks that are currently running, with
1975     * the most recent being first and older ones after in order.  Note that
1976     * "running" does not mean any of the task's code is currently loaded or
1977     * activity -- the task may have been frozen by the system, so that it
1978     * can be restarted in its previous state when next brought to the
1979     * foreground.
1980     *
1981     * <p><b>Note: this method is only intended for debugging and presenting
1982     * task management user interfaces</b>.  This should never be used for
1983     * core logic in an application, such as deciding between different
1984     * behaviors based on the information found here.  Such uses are
1985     * <em>not</em> supported, and will likely break in the future.  For
1986     * example, if multiple applications can be actively running at the
1987     * same time, assumptions made about the meaning of the data here for
1988     * purposes of control flow will be incorrect.</p>
1989     *
1990     * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method
1991     * is no longer available to third party
1992     * applications: the introduction of document-centric recents means
1993     * it can leak person information to the caller.  For backwards compatibility,
1994     * it will still return a small subset of its data: at least the caller's
1995     * own tasks, and possibly some other tasks
1996     * such as home that are known to not be sensitive.
1997     *
1998     * @param maxNum The maximum number of entries to return in the list.  The
1999     * actual number returned may be smaller, depending on how many tasks the
2000     * user has started.
2001     *
2002     * @return Returns a list of RunningTaskInfo records describing each of
2003     * the running tasks.
2004     */
2005    @Deprecated
2006    public List<RunningTaskInfo> getRunningTasks(int maxNum)
2007            throws SecurityException {
2008        try {
2009            return getService().getTasks(maxNum, 0);
2010        } catch (RemoteException e) {
2011            throw e.rethrowFromSystemServer();
2012        }
2013    }
2014
2015    /**
2016     * Completely remove the given task.
2017     *
2018     * @param taskId Identifier of the task to be removed.
2019     * @return Returns true if the given task was found and removed.
2020     *
2021     * @hide
2022     */
2023    public boolean removeTask(int taskId) throws SecurityException {
2024        try {
2025            return getService().removeTask(taskId);
2026        } catch (RemoteException e) {
2027            throw e.rethrowFromSystemServer();
2028        }
2029    }
2030
2031    /**
2032     * Sets the windowing mode for a specific task. Only works on tasks of type
2033     * {@link WindowConfiguration#ACTIVITY_TYPE_STANDARD}
2034     * @param taskId The id of the task to set the windowing mode for.
2035     * @param windowingMode The windowing mode to set for the task.
2036     * @param toTop If the task should be moved to the top once the windowing mode changes.
2037     * @hide
2038     */
2039    @TestApi
2040    @RequiresPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS)
2041    public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop)
2042            throws SecurityException {
2043        try {
2044            getService().setTaskWindowingMode(taskId, windowingMode, toTop);
2045        } catch (RemoteException e) {
2046            throw e.rethrowFromSystemServer();
2047        }
2048    }
2049
2050    /**
2051     * Resizes the input stack id to the given bounds.
2052     * @param stackId Id of the stack to resize.
2053     * @param bounds Bounds to resize the stack to or {@code null} for fullscreen.
2054     * @hide
2055     */
2056    @TestApi
2057    @RequiresPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS)
2058    public void resizeStack(int stackId, Rect bounds) throws SecurityException {
2059        try {
2060            getService().resizeStack(stackId, bounds, false /* allowResizeInDockedMode */,
2061                    false /* preserveWindows */, false /* animate */, -1 /* animationDuration */);
2062        } catch (RemoteException e) {
2063            throw e.rethrowFromSystemServer();
2064        }
2065    }
2066
2067    /**
2068     * Removes stacks in the windowing modes from the system if they are of activity type
2069     * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2070     *
2071     * @hide
2072     */
2073    @TestApi
2074    @RequiresPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS)
2075    public void removeStacksInWindowingModes(int[] windowingModes) throws SecurityException {
2076        try {
2077            getService().removeStacksInWindowingModes(windowingModes);
2078        } catch (RemoteException e) {
2079            throw e.rethrowFromSystemServer();
2080        }
2081    }
2082
2083    /**
2084     * Removes stack of the activity types from the system.
2085     *
2086     * @hide
2087     */
2088    @TestApi
2089    @RequiresPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS)
2090    public void removeStacksWithActivityTypes(int[] activityTypes) throws SecurityException {
2091        try {
2092            getService().removeStacksWithActivityTypes(activityTypes);
2093        } catch (RemoteException e) {
2094            throw e.rethrowFromSystemServer();
2095        }
2096    }
2097
2098    /**
2099     * Represents a task snapshot.
2100     * @hide
2101     */
2102    public static class TaskSnapshot implements Parcelable {
2103
2104        private final GraphicBuffer mSnapshot;
2105        private final int mOrientation;
2106        private final Rect mContentInsets;
2107        private final boolean mReducedResolution;
2108        private final float mScale;
2109
2110        public TaskSnapshot(GraphicBuffer snapshot, int orientation, Rect contentInsets,
2111                boolean reducedResolution, float scale) {
2112            mSnapshot = snapshot;
2113            mOrientation = orientation;
2114            mContentInsets = new Rect(contentInsets);
2115            mReducedResolution = reducedResolution;
2116            mScale = scale;
2117        }
2118
2119        private TaskSnapshot(Parcel source) {
2120            mSnapshot = source.readParcelable(null /* classLoader */);
2121            mOrientation = source.readInt();
2122            mContentInsets = source.readParcelable(null /* classLoader */);
2123            mReducedResolution = source.readBoolean();
2124            mScale = source.readFloat();
2125        }
2126
2127        /**
2128         * @return The graphic buffer representing the screenshot.
2129         */
2130        public GraphicBuffer getSnapshot() {
2131            return mSnapshot;
2132        }
2133
2134        /**
2135         * @return The screen orientation the screenshot was taken in.
2136         */
2137        public int getOrientation() {
2138            return mOrientation;
2139        }
2140
2141        /**
2142         * @return The system/content insets on the snapshot. These can be clipped off in order to
2143         *         remove any areas behind system bars in the snapshot.
2144         */
2145        public Rect getContentInsets() {
2146            return mContentInsets;
2147        }
2148
2149        /**
2150         * @return Whether this snapshot is a down-sampled version of the full resolution.
2151         */
2152        public boolean isReducedResolution() {
2153            return mReducedResolution;
2154        }
2155
2156        /**
2157         * @return The scale this snapshot was taken in.
2158         */
2159        public float getScale() {
2160            return mScale;
2161        }
2162
2163        @Override
2164        public int describeContents() {
2165            return 0;
2166        }
2167
2168        @Override
2169        public void writeToParcel(Parcel dest, int flags) {
2170            dest.writeParcelable(mSnapshot, 0);
2171            dest.writeInt(mOrientation);
2172            dest.writeParcelable(mContentInsets, 0);
2173            dest.writeBoolean(mReducedResolution);
2174            dest.writeFloat(mScale);
2175        }
2176
2177        @Override
2178        public String toString() {
2179            return "TaskSnapshot{mSnapshot=" + mSnapshot + " mOrientation=" + mOrientation
2180                    + " mContentInsets=" + mContentInsets.toShortString()
2181                    + " mReducedResolution=" + mReducedResolution + " mScale=" + mScale;
2182        }
2183
2184        public static final Creator<TaskSnapshot> CREATOR = new Creator<TaskSnapshot>() {
2185            public TaskSnapshot createFromParcel(Parcel source) {
2186                return new TaskSnapshot(source);
2187            }
2188            public TaskSnapshot[] newArray(int size) {
2189                return new TaskSnapshot[size];
2190            }
2191        };
2192    }
2193
2194    /** @hide */
2195    @IntDef(flag = true, prefix = { "MOVE_TASK_" }, value = {
2196            MOVE_TASK_WITH_HOME,
2197            MOVE_TASK_NO_USER_ACTION,
2198    })
2199    @Retention(RetentionPolicy.SOURCE)
2200    public @interface MoveTaskFlags {}
2201
2202    /**
2203     * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
2204     * activity along with the task, so it is positioned immediately behind
2205     * the task.
2206     */
2207    public static final int MOVE_TASK_WITH_HOME = 0x00000001;
2208
2209    /**
2210     * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
2211     * user-instigated action, so the current activity will not receive a
2212     * hint that the user is leaving.
2213     */
2214    public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
2215
2216    /**
2217     * Equivalent to calling {@link #moveTaskToFront(int, int, Bundle)}
2218     * with a null options argument.
2219     *
2220     * @param taskId The identifier of the task to be moved, as found in
2221     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
2222     * @param flags Additional operational flags.
2223     */
2224    @RequiresPermission(android.Manifest.permission.REORDER_TASKS)
2225    public void moveTaskToFront(int taskId, @MoveTaskFlags int flags) {
2226        moveTaskToFront(taskId, flags, null);
2227    }
2228
2229    /**
2230     * Ask that the task associated with a given task ID be moved to the
2231     * front of the stack, so it is now visible to the user.
2232     *
2233     * @param taskId The identifier of the task to be moved, as found in
2234     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
2235     * @param flags Additional operational flags.
2236     * @param options Additional options for the operation, either null or
2237     * as per {@link Context#startActivity(Intent, android.os.Bundle)
2238     * Context.startActivity(Intent, Bundle)}.
2239     */
2240    @RequiresPermission(android.Manifest.permission.REORDER_TASKS)
2241    public void moveTaskToFront(int taskId, @MoveTaskFlags int flags, Bundle options) {
2242        try {
2243            getService().moveTaskToFront(taskId, flags, options);
2244        } catch (RemoteException e) {
2245            throw e.rethrowFromSystemServer();
2246        }
2247    }
2248
2249    /**
2250     * Information you can retrieve about a particular Service that is
2251     * currently running in the system.
2252     */
2253    public static class RunningServiceInfo implements Parcelable {
2254        /**
2255         * The service component.
2256         */
2257        public ComponentName service;
2258
2259        /**
2260         * If non-zero, this is the process the service is running in.
2261         */
2262        public int pid;
2263
2264        /**
2265         * The UID that owns this service.
2266         */
2267        public int uid;
2268
2269        /**
2270         * The name of the process this service runs in.
2271         */
2272        public String process;
2273
2274        /**
2275         * Set to true if the service has asked to run as a foreground process.
2276         */
2277        public boolean foreground;
2278
2279        /**
2280         * The time when the service was first made active, either by someone
2281         * starting or binding to it.  This
2282         * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
2283         */
2284        public long activeSince;
2285
2286        /**
2287         * Set to true if this service has been explicitly started.
2288         */
2289        public boolean started;
2290
2291        /**
2292         * Number of clients connected to the service.
2293         */
2294        public int clientCount;
2295
2296        /**
2297         * Number of times the service's process has crashed while the service
2298         * is running.
2299         */
2300        public int crashCount;
2301
2302        /**
2303         * The time when there was last activity in the service (either
2304         * explicit requests to start it or clients binding to it).  This
2305         * is in units of {@link android.os.SystemClock#uptimeMillis()}.
2306         */
2307        public long lastActivityTime;
2308
2309        /**
2310         * If non-zero, this service is not currently running, but scheduled to
2311         * restart at the given time.
2312         */
2313        public long restarting;
2314
2315        /**
2316         * Bit for {@link #flags}: set if this service has been
2317         * explicitly started.
2318         */
2319        public static final int FLAG_STARTED = 1<<0;
2320
2321        /**
2322         * Bit for {@link #flags}: set if the service has asked to
2323         * run as a foreground process.
2324         */
2325        public static final int FLAG_FOREGROUND = 1<<1;
2326
2327        /**
2328         * Bit for {@link #flags}: set if the service is running in a
2329         * core system process.
2330         */
2331        public static final int FLAG_SYSTEM_PROCESS = 1<<2;
2332
2333        /**
2334         * Bit for {@link #flags}: set if the service is running in a
2335         * persistent process.
2336         */
2337        public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
2338
2339        /**
2340         * Running flags.
2341         */
2342        public int flags;
2343
2344        /**
2345         * For special services that are bound to by system code, this is
2346         * the package that holds the binding.
2347         */
2348        public String clientPackage;
2349
2350        /**
2351         * For special services that are bound to by system code, this is
2352         * a string resource providing a user-visible label for who the
2353         * client is.
2354         */
2355        public int clientLabel;
2356
2357        public RunningServiceInfo() {
2358        }
2359
2360        public int describeContents() {
2361            return 0;
2362        }
2363
2364        public void writeToParcel(Parcel dest, int flags) {
2365            ComponentName.writeToParcel(service, dest);
2366            dest.writeInt(pid);
2367            dest.writeInt(uid);
2368            dest.writeString(process);
2369            dest.writeInt(foreground ? 1 : 0);
2370            dest.writeLong(activeSince);
2371            dest.writeInt(started ? 1 : 0);
2372            dest.writeInt(clientCount);
2373            dest.writeInt(crashCount);
2374            dest.writeLong(lastActivityTime);
2375            dest.writeLong(restarting);
2376            dest.writeInt(this.flags);
2377            dest.writeString(clientPackage);
2378            dest.writeInt(clientLabel);
2379        }
2380
2381        public void readFromParcel(Parcel source) {
2382            service = ComponentName.readFromParcel(source);
2383            pid = source.readInt();
2384            uid = source.readInt();
2385            process = source.readString();
2386            foreground = source.readInt() != 0;
2387            activeSince = source.readLong();
2388            started = source.readInt() != 0;
2389            clientCount = source.readInt();
2390            crashCount = source.readInt();
2391            lastActivityTime = source.readLong();
2392            restarting = source.readLong();
2393            flags = source.readInt();
2394            clientPackage = source.readString();
2395            clientLabel = source.readInt();
2396        }
2397
2398        public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
2399            public RunningServiceInfo createFromParcel(Parcel source) {
2400                return new RunningServiceInfo(source);
2401            }
2402            public RunningServiceInfo[] newArray(int size) {
2403                return new RunningServiceInfo[size];
2404            }
2405        };
2406
2407        private RunningServiceInfo(Parcel source) {
2408            readFromParcel(source);
2409        }
2410    }
2411
2412    /**
2413     * Return a list of the services that are currently running.
2414     *
2415     * <p><b>Note: this method is only intended for debugging or implementing
2416     * service management type user interfaces.</b></p>
2417     *
2418     * @deprecated As of {@link android.os.Build.VERSION_CODES#O}, this method
2419     * is no longer available to third party applications.  For backwards compatibility,
2420     * it will still return the caller's own services.
2421     *
2422     * @param maxNum The maximum number of entries to return in the list.  The
2423     * actual number returned may be smaller, depending on how many services
2424     * are running.
2425     *
2426     * @return Returns a list of RunningServiceInfo records describing each of
2427     * the running tasks.
2428     */
2429    @Deprecated
2430    public List<RunningServiceInfo> getRunningServices(int maxNum)
2431            throws SecurityException {
2432        try {
2433            return getService()
2434                    .getServices(maxNum, 0);
2435        } catch (RemoteException e) {
2436            throw e.rethrowFromSystemServer();
2437        }
2438    }
2439
2440    /**
2441     * Returns a PendingIntent you can start to show a control panel for the
2442     * given running service.  If the service does not have a control panel,
2443     * null is returned.
2444     */
2445    public PendingIntent getRunningServiceControlPanel(ComponentName service)
2446            throws SecurityException {
2447        try {
2448            return getService()
2449                    .getRunningServiceControlPanel(service);
2450        } catch (RemoteException e) {
2451            throw e.rethrowFromSystemServer();
2452        }
2453    }
2454
2455    /**
2456     * Information you can retrieve about the available memory through
2457     * {@link ActivityManager#getMemoryInfo}.
2458     */
2459    public static class MemoryInfo implements Parcelable {
2460        /**
2461         * The available memory on the system.  This number should not
2462         * be considered absolute: due to the nature of the kernel, a significant
2463         * portion of this memory is actually in use and needed for the overall
2464         * system to run well.
2465         */
2466        public long availMem;
2467
2468        /**
2469         * The total memory accessible by the kernel.  This is basically the
2470         * RAM size of the device, not including below-kernel fixed allocations
2471         * like DMA buffers, RAM for the baseband CPU, etc.
2472         */
2473        public long totalMem;
2474
2475        /**
2476         * The threshold of {@link #availMem} at which we consider memory to be
2477         * low and start killing background services and other non-extraneous
2478         * processes.
2479         */
2480        public long threshold;
2481
2482        /**
2483         * Set to true if the system considers itself to currently be in a low
2484         * memory situation.
2485         */
2486        public boolean lowMemory;
2487
2488        /** @hide */
2489        public long hiddenAppThreshold;
2490        /** @hide */
2491        public long secondaryServerThreshold;
2492        /** @hide */
2493        public long visibleAppThreshold;
2494        /** @hide */
2495        public long foregroundAppThreshold;
2496
2497        public MemoryInfo() {
2498        }
2499
2500        public int describeContents() {
2501            return 0;
2502        }
2503
2504        public void writeToParcel(Parcel dest, int flags) {
2505            dest.writeLong(availMem);
2506            dest.writeLong(totalMem);
2507            dest.writeLong(threshold);
2508            dest.writeInt(lowMemory ? 1 : 0);
2509            dest.writeLong(hiddenAppThreshold);
2510            dest.writeLong(secondaryServerThreshold);
2511            dest.writeLong(visibleAppThreshold);
2512            dest.writeLong(foregroundAppThreshold);
2513        }
2514
2515        public void readFromParcel(Parcel source) {
2516            availMem = source.readLong();
2517            totalMem = source.readLong();
2518            threshold = source.readLong();
2519            lowMemory = source.readInt() != 0;
2520            hiddenAppThreshold = source.readLong();
2521            secondaryServerThreshold = source.readLong();
2522            visibleAppThreshold = source.readLong();
2523            foregroundAppThreshold = source.readLong();
2524        }
2525
2526        public static final Creator<MemoryInfo> CREATOR
2527                = new Creator<MemoryInfo>() {
2528            public MemoryInfo createFromParcel(Parcel source) {
2529                return new MemoryInfo(source);
2530            }
2531            public MemoryInfo[] newArray(int size) {
2532                return new MemoryInfo[size];
2533            }
2534        };
2535
2536        private MemoryInfo(Parcel source) {
2537            readFromParcel(source);
2538        }
2539    }
2540
2541    /**
2542     * Return general information about the memory state of the system.  This
2543     * can be used to help decide how to manage your own memory, though note
2544     * that polling is not recommended and
2545     * {@link android.content.ComponentCallbacks2#onTrimMemory(int)
2546     * ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this.
2547     * Also see {@link #getMyMemoryState} for how to retrieve the current trim
2548     * level of your process as needed, which gives a better hint for how to
2549     * manage its memory.
2550     */
2551    public void getMemoryInfo(MemoryInfo outInfo) {
2552        try {
2553            getService().getMemoryInfo(outInfo);
2554        } catch (RemoteException e) {
2555            throw e.rethrowFromSystemServer();
2556        }
2557    }
2558
2559    /**
2560     * Information you can retrieve about an ActivityStack in the system.
2561     * @hide
2562     */
2563    public static class StackInfo implements Parcelable {
2564        public int stackId;
2565        public Rect bounds = new Rect();
2566        public int[] taskIds;
2567        public String[] taskNames;
2568        public Rect[] taskBounds;
2569        public int[] taskUserIds;
2570        public ComponentName topActivity;
2571        public int displayId;
2572        public int userId;
2573        public boolean visible;
2574        // Index of the stack in the display's stack list, can be used for comparison of stack order
2575        public int position;
2576        /**
2577         * The full configuration the stack is currently running in.
2578         * @hide
2579         */
2580        public Configuration configuration = new Configuration();
2581
2582        @Override
2583        public int describeContents() {
2584            return 0;
2585        }
2586
2587        @Override
2588        public void writeToParcel(Parcel dest, int flags) {
2589            dest.writeInt(stackId);
2590            dest.writeInt(bounds.left);
2591            dest.writeInt(bounds.top);
2592            dest.writeInt(bounds.right);
2593            dest.writeInt(bounds.bottom);
2594            dest.writeIntArray(taskIds);
2595            dest.writeStringArray(taskNames);
2596            final int boundsCount = taskBounds == null ? 0 : taskBounds.length;
2597            dest.writeInt(boundsCount);
2598            for (int i = 0; i < boundsCount; i++) {
2599                dest.writeInt(taskBounds[i].left);
2600                dest.writeInt(taskBounds[i].top);
2601                dest.writeInt(taskBounds[i].right);
2602                dest.writeInt(taskBounds[i].bottom);
2603            }
2604            dest.writeIntArray(taskUserIds);
2605            dest.writeInt(displayId);
2606            dest.writeInt(userId);
2607            dest.writeInt(visible ? 1 : 0);
2608            dest.writeInt(position);
2609            if (topActivity != null) {
2610                dest.writeInt(1);
2611                topActivity.writeToParcel(dest, 0);
2612            } else {
2613                dest.writeInt(0);
2614            }
2615            configuration.writeToParcel(dest, flags);
2616        }
2617
2618        public void readFromParcel(Parcel source) {
2619            stackId = source.readInt();
2620            bounds = new Rect(
2621                    source.readInt(), source.readInt(), source.readInt(), source.readInt());
2622            taskIds = source.createIntArray();
2623            taskNames = source.createStringArray();
2624            final int boundsCount = source.readInt();
2625            if (boundsCount > 0) {
2626                taskBounds = new Rect[boundsCount];
2627                for (int i = 0; i < boundsCount; i++) {
2628                    taskBounds[i] = new Rect();
2629                    taskBounds[i].set(
2630                            source.readInt(), source.readInt(), source.readInt(), source.readInt());
2631                }
2632            } else {
2633                taskBounds = null;
2634            }
2635            taskUserIds = source.createIntArray();
2636            displayId = source.readInt();
2637            userId = source.readInt();
2638            visible = source.readInt() > 0;
2639            position = source.readInt();
2640            if (source.readInt() > 0) {
2641                topActivity = ComponentName.readFromParcel(source);
2642            }
2643            configuration.readFromParcel(source);
2644        }
2645
2646        public static final Creator<StackInfo> CREATOR = new Creator<StackInfo>() {
2647            @Override
2648            public StackInfo createFromParcel(Parcel source) {
2649                return new StackInfo(source);
2650            }
2651            @Override
2652            public StackInfo[] newArray(int size) {
2653                return new StackInfo[size];
2654            }
2655        };
2656
2657        public StackInfo() {
2658        }
2659
2660        private StackInfo(Parcel source) {
2661            readFromParcel(source);
2662        }
2663
2664        public String toString(String prefix) {
2665            StringBuilder sb = new StringBuilder(256);
2666            sb.append(prefix); sb.append("Stack id="); sb.append(stackId);
2667                    sb.append(" bounds="); sb.append(bounds.toShortString());
2668                    sb.append(" displayId="); sb.append(displayId);
2669                    sb.append(" userId="); sb.append(userId);
2670                    sb.append("\n");
2671                    sb.append(" configuration="); sb.append(configuration);
2672                    sb.append("\n");
2673            prefix = prefix + "  ";
2674            for (int i = 0; i < taskIds.length; ++i) {
2675                sb.append(prefix); sb.append("taskId="); sb.append(taskIds[i]);
2676                        sb.append(": "); sb.append(taskNames[i]);
2677                        if (taskBounds != null) {
2678                            sb.append(" bounds="); sb.append(taskBounds[i].toShortString());
2679                        }
2680                        sb.append(" userId=").append(taskUserIds[i]);
2681                        sb.append(" visible=").append(visible);
2682                        if (topActivity != null) {
2683                            sb.append(" topActivity=").append(topActivity);
2684                        }
2685                        sb.append("\n");
2686            }
2687            return sb.toString();
2688        }
2689
2690        @Override
2691        public String toString() {
2692            return toString("");
2693        }
2694    }
2695
2696    /**
2697     * @hide
2698     */
2699    @RequiresPermission(anyOf={Manifest.permission.CLEAR_APP_USER_DATA,
2700            Manifest.permission.ACCESS_INSTANT_APPS})
2701    public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
2702        try {
2703            return getService().clearApplicationUserData(packageName,
2704                    observer, UserHandle.myUserId());
2705        } catch (RemoteException e) {
2706            throw e.rethrowFromSystemServer();
2707        }
2708    }
2709
2710    /**
2711     * Permits an application to erase its own data from disk.  This is equivalent to
2712     * the user choosing to clear the app's data from within the device settings UI.  It
2713     * erases all dynamic data associated with the app -- its private data and data in its
2714     * private area on external storage -- but does not remove the installed application
2715     * itself, nor any OBB files. It also revokes all runtime permissions that the app has acquired,
2716     * clears all notifications and removes all Uri grants related to this application.
2717     *
2718     * @return {@code true} if the application successfully requested that the application's
2719     *     data be erased; {@code false} otherwise.
2720     */
2721    public boolean clearApplicationUserData() {
2722        return clearApplicationUserData(mContext.getPackageName(), null);
2723    }
2724
2725
2726    /**
2727     * Permits an application to get the persistent URI permissions granted to another.
2728     *
2729     * <p>Typically called by Settings.
2730     *
2731     * @param packageName application to look for the granted permissions
2732     * @return list of granted URI permissions
2733     *
2734     * @hide
2735     */
2736    public ParceledListSlice<UriPermission> getGrantedUriPermissions(String packageName) {
2737        try {
2738            return getService().getGrantedUriPermissions(packageName,
2739                    UserHandle.myUserId());
2740        } catch (RemoteException e) {
2741            throw e.rethrowFromSystemServer();
2742        }
2743    }
2744
2745    /**
2746     * Permits an application to clear the persistent URI permissions granted to another.
2747     *
2748     * <p>Typically called by Settings.
2749     *
2750     * @param packageName application to clear its granted permissions
2751     *
2752     * @hide
2753     */
2754    public void clearGrantedUriPermissions(String packageName) {
2755        try {
2756            getService().clearGrantedUriPermissions(packageName,
2757                    UserHandle.myUserId());
2758        } catch (RemoteException e) {
2759            throw e.rethrowFromSystemServer();
2760        }
2761    }
2762
2763    /**
2764     * Information you can retrieve about any processes that are in an error condition.
2765     */
2766    public static class ProcessErrorStateInfo implements Parcelable {
2767        /**
2768         * Condition codes
2769         */
2770        public static final int NO_ERROR = 0;
2771        public static final int CRASHED = 1;
2772        public static final int NOT_RESPONDING = 2;
2773
2774        /**
2775         * The condition that the process is in.
2776         */
2777        public int condition;
2778
2779        /**
2780         * The process name in which the crash or error occurred.
2781         */
2782        public String processName;
2783
2784        /**
2785         * The pid of this process; 0 if none
2786         */
2787        public int pid;
2788
2789        /**
2790         * The kernel user-ID that has been assigned to this process;
2791         * currently this is not a unique ID (multiple applications can have
2792         * the same uid).
2793         */
2794        public int uid;
2795
2796        /**
2797         * The activity name associated with the error, if known.  May be null.
2798         */
2799        public String tag;
2800
2801        /**
2802         * A short message describing the error condition.
2803         */
2804        public String shortMsg;
2805
2806        /**
2807         * A long message describing the error condition.
2808         */
2809        public String longMsg;
2810
2811        /**
2812         * The stack trace where the error originated.  May be null.
2813         */
2814        public String stackTrace;
2815
2816        /**
2817         * to be deprecated: This value will always be null.
2818         */
2819        public byte[] crashData = null;
2820
2821        public ProcessErrorStateInfo() {
2822        }
2823
2824        @Override
2825        public int describeContents() {
2826            return 0;
2827        }
2828
2829        @Override
2830        public void writeToParcel(Parcel dest, int flags) {
2831            dest.writeInt(condition);
2832            dest.writeString(processName);
2833            dest.writeInt(pid);
2834            dest.writeInt(uid);
2835            dest.writeString(tag);
2836            dest.writeString(shortMsg);
2837            dest.writeString(longMsg);
2838            dest.writeString(stackTrace);
2839        }
2840
2841        public void readFromParcel(Parcel source) {
2842            condition = source.readInt();
2843            processName = source.readString();
2844            pid = source.readInt();
2845            uid = source.readInt();
2846            tag = source.readString();
2847            shortMsg = source.readString();
2848            longMsg = source.readString();
2849            stackTrace = source.readString();
2850        }
2851
2852        public static final Creator<ProcessErrorStateInfo> CREATOR =
2853                new Creator<ProcessErrorStateInfo>() {
2854            public ProcessErrorStateInfo createFromParcel(Parcel source) {
2855                return new ProcessErrorStateInfo(source);
2856            }
2857            public ProcessErrorStateInfo[] newArray(int size) {
2858                return new ProcessErrorStateInfo[size];
2859            }
2860        };
2861
2862        private ProcessErrorStateInfo(Parcel source) {
2863            readFromParcel(source);
2864        }
2865    }
2866
2867    /**
2868     * Returns a list of any processes that are currently in an error condition.  The result
2869     * will be null if all processes are running properly at this time.
2870     *
2871     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
2872     * current error conditions (it will not return an empty list).  This list ordering is not
2873     * specified.
2874     */
2875    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
2876        try {
2877            return getService().getProcessesInErrorState();
2878        } catch (RemoteException e) {
2879            throw e.rethrowFromSystemServer();
2880        }
2881    }
2882
2883    /**
2884     * Information you can retrieve about a running process.
2885     */
2886    public static class RunningAppProcessInfo implements Parcelable {
2887        /**
2888         * The name of the process that this object is associated with
2889         */
2890        public String processName;
2891
2892        /**
2893         * The pid of this process; 0 if none
2894         */
2895        public int pid;
2896
2897        /**
2898         * The user id of this process.
2899         */
2900        public int uid;
2901
2902        /**
2903         * All packages that have been loaded into the process.
2904         */
2905        public String pkgList[];
2906
2907        /**
2908         * Constant for {@link #flags}: this is an app that is unable to
2909         * correctly save its state when going to the background,
2910         * so it can not be killed while in the background.
2911         * @hide
2912         */
2913        public static final int FLAG_CANT_SAVE_STATE = 1<<0;
2914
2915        /**
2916         * Constant for {@link #flags}: this process is associated with a
2917         * persistent system app.
2918         * @hide
2919         */
2920        public static final int FLAG_PERSISTENT = 1<<1;
2921
2922        /**
2923         * Constant for {@link #flags}: this process is associated with a
2924         * persistent system app.
2925         * @hide
2926         */
2927        public static final int FLAG_HAS_ACTIVITIES = 1<<2;
2928
2929        /**
2930         * Flags of information.  May be any of
2931         * {@link #FLAG_CANT_SAVE_STATE}.
2932         * @hide
2933         */
2934        public int flags;
2935
2936        /**
2937         * Last memory trim level reported to the process: corresponds to
2938         * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
2939         * ComponentCallbacks2.onTrimMemory(int)}.
2940         */
2941        public int lastTrimLevel;
2942
2943        /** @hide */
2944        @IntDef(prefix = { "IMPORTANCE_" }, value = {
2945                IMPORTANCE_FOREGROUND,
2946                IMPORTANCE_FOREGROUND_SERVICE,
2947                IMPORTANCE_TOP_SLEEPING,
2948                IMPORTANCE_VISIBLE,
2949                IMPORTANCE_PERCEPTIBLE,
2950                IMPORTANCE_CANT_SAVE_STATE,
2951                IMPORTANCE_SERVICE,
2952                IMPORTANCE_CACHED,
2953                IMPORTANCE_GONE,
2954        })
2955        @Retention(RetentionPolicy.SOURCE)
2956        public @interface Importance {}
2957
2958        /**
2959         * Constant for {@link #importance}: This process is running the
2960         * foreground UI; that is, it is the thing currently at the top of the screen
2961         * that the user is interacting with.
2962         */
2963        public static final int IMPORTANCE_FOREGROUND = 100;
2964
2965        /**
2966         * Constant for {@link #importance}: This process is running a foreground
2967         * service, for example to perform music playback even while the user is
2968         * not immediately in the app.  This generally indicates that the process
2969         * is doing something the user actively cares about.
2970         */
2971        public static final int IMPORTANCE_FOREGROUND_SERVICE = 125;
2972
2973        /**
2974         * Constant for {@link #importance}: This process is running the foreground
2975         * UI, but the device is asleep so it is not visible to the user.  This means
2976         * the user is not really aware of the process, because they can not see or
2977         * interact with it, but it is quite important because it what they expect to
2978         * return to once unlocking the device.
2979         */
2980        public static final int IMPORTANCE_TOP_SLEEPING = 150;
2981
2982        /**
2983         * Constant for {@link #importance}: This process is running something
2984         * that is actively visible to the user, though not in the immediate
2985         * foreground.  This may be running a window that is behind the current
2986         * foreground (so paused and with its state saved, not interacting with
2987         * the user, but visible to them to some degree); it may also be running
2988         * other services under the system's control that it inconsiders important.
2989         */
2990        public static final int IMPORTANCE_VISIBLE = 200;
2991
2992        /**
2993         * Constant for {@link #importance}: {@link #IMPORTANCE_PERCEPTIBLE} had this wrong value
2994         * before {@link Build.VERSION_CODES#O}.  Since the {@link Build.VERSION_CODES#O} SDK,
2995         * the value of {@link #IMPORTANCE_PERCEPTIBLE} has been fixed.
2996         *
2997         * <p>The system will return this value instead of {@link #IMPORTANCE_PERCEPTIBLE}
2998         * on Android versions below {@link Build.VERSION_CODES#O}.
2999         *
3000         * <p>On Android version {@link Build.VERSION_CODES#O} and later, this value will still be
3001         * returned for apps with the target API level below {@link Build.VERSION_CODES#O}.
3002         * For apps targeting version {@link Build.VERSION_CODES#O} and later,
3003         * the correct value {@link #IMPORTANCE_PERCEPTIBLE} will be returned.
3004         */
3005        public static final int IMPORTANCE_PERCEPTIBLE_PRE_26 = 130;
3006
3007        /**
3008         * Constant for {@link #importance}: This process is not something the user
3009         * is directly aware of, but is otherwise perceptible to them to some degree.
3010         */
3011        public static final int IMPORTANCE_PERCEPTIBLE = 230;
3012
3013        /**
3014         * Constant for {@link #importance}: {@link #IMPORTANCE_CANT_SAVE_STATE} had
3015         * this wrong value
3016         * before {@link Build.VERSION_CODES#O}.  Since the {@link Build.VERSION_CODES#O} SDK,
3017         * the value of {@link #IMPORTANCE_CANT_SAVE_STATE} has been fixed.
3018         *
3019         * <p>The system will return this value instead of {@link #IMPORTANCE_CANT_SAVE_STATE}
3020         * on Android versions below {@link Build.VERSION_CODES#O}.
3021         *
3022         * <p>On Android version {@link Build.VERSION_CODES#O} after, this value will still be
3023         * returned for apps with the target API level below {@link Build.VERSION_CODES#O}.
3024         * For apps targeting version {@link Build.VERSION_CODES#O} and later,
3025         * the correct value {@link #IMPORTANCE_CANT_SAVE_STATE} will be returned.
3026         *
3027         * @hide
3028         */
3029        public static final int IMPORTANCE_CANT_SAVE_STATE_PRE_26 = 170;
3030
3031        /**
3032         * Constant for {@link #importance}: This process is running an
3033         * application that can not save its state, and thus can't be killed
3034         * while in the background.
3035         * @hide
3036         */
3037        public static final int IMPORTANCE_CANT_SAVE_STATE= 270;
3038
3039        /**
3040         * Constant for {@link #importance}: This process is contains services
3041         * that should remain running.  These are background services apps have
3042         * started, not something the user is aware of, so they may be killed by
3043         * the system relatively freely (though it is generally desired that they
3044         * stay running as long as they want to).
3045         */
3046        public static final int IMPORTANCE_SERVICE = 300;
3047
3048        /**
3049         * Constant for {@link #importance}: This process process contains
3050         * cached code that is expendable, not actively running any app components
3051         * we care about.
3052         */
3053        public static final int IMPORTANCE_CACHED = 400;
3054
3055        /**
3056         * @deprecated Renamed to {@link #IMPORTANCE_CACHED}.
3057         */
3058        public static final int IMPORTANCE_BACKGROUND = IMPORTANCE_CACHED;
3059
3060        /**
3061         * Constant for {@link #importance}: This process is empty of any
3062         * actively running code.
3063         * @deprecated This value is no longer reported, use {@link #IMPORTANCE_CACHED} instead.
3064         */
3065        @Deprecated
3066        public static final int IMPORTANCE_EMPTY = 500;
3067
3068        /**
3069         * Constant for {@link #importance}: This process does not exist.
3070         */
3071        public static final int IMPORTANCE_GONE = 1000;
3072
3073        /**
3074         * Convert a proc state to the correspondent IMPORTANCE_* constant.  If the return value
3075         * will be passed to a client, use {@link #procStateToImportanceForClient}.
3076         * @hide
3077         */
3078        public static @Importance int procStateToImportance(int procState) {
3079            if (procState == PROCESS_STATE_NONEXISTENT) {
3080                return IMPORTANCE_GONE;
3081            } else if (procState >= PROCESS_STATE_HOME) {
3082                return IMPORTANCE_CACHED;
3083            } else if (procState >= PROCESS_STATE_SERVICE) {
3084                return IMPORTANCE_SERVICE;
3085            } else if (procState > PROCESS_STATE_HEAVY_WEIGHT) {
3086                return IMPORTANCE_CANT_SAVE_STATE;
3087            } else if (procState >= PROCESS_STATE_TRANSIENT_BACKGROUND) {
3088                return IMPORTANCE_PERCEPTIBLE;
3089            } else if (procState >= PROCESS_STATE_IMPORTANT_FOREGROUND) {
3090                return IMPORTANCE_VISIBLE;
3091            } else if (procState >= PROCESS_STATE_TOP_SLEEPING) {
3092                return IMPORTANCE_TOP_SLEEPING;
3093            } else if (procState >= PROCESS_STATE_FOREGROUND_SERVICE) {
3094                return IMPORTANCE_FOREGROUND_SERVICE;
3095            } else {
3096                return IMPORTANCE_FOREGROUND;
3097            }
3098        }
3099
3100        /**
3101         * Convert a proc state to the correspondent IMPORTANCE_* constant for a client represented
3102         * by a given {@link Context}, with converting {@link #IMPORTANCE_PERCEPTIBLE}
3103         * and {@link #IMPORTANCE_CANT_SAVE_STATE} to the corresponding "wrong" value if the
3104         * client's target SDK < {@link VERSION_CODES#O}.
3105         * @hide
3106         */
3107        public static @Importance int procStateToImportanceForClient(int procState,
3108                Context clientContext) {
3109            return procStateToImportanceForTargetSdk(procState,
3110                    clientContext.getApplicationInfo().targetSdkVersion);
3111        }
3112
3113        /**
3114         * See {@link #procStateToImportanceForClient}.
3115         * @hide
3116         */
3117        public static @Importance int procStateToImportanceForTargetSdk(int procState,
3118                int targetSdkVersion) {
3119            final int importance = procStateToImportance(procState);
3120
3121            // For pre O apps, convert to the old, wrong values.
3122            if (targetSdkVersion < VERSION_CODES.O) {
3123                switch (importance) {
3124                    case IMPORTANCE_PERCEPTIBLE:
3125                        return IMPORTANCE_PERCEPTIBLE_PRE_26;
3126                    case IMPORTANCE_CANT_SAVE_STATE:
3127                        return IMPORTANCE_CANT_SAVE_STATE_PRE_26;
3128                }
3129            }
3130            return importance;
3131        }
3132
3133        /** @hide */
3134        public static int importanceToProcState(@Importance int importance) {
3135            if (importance == IMPORTANCE_GONE) {
3136                return PROCESS_STATE_NONEXISTENT;
3137            } else if (importance >= IMPORTANCE_CACHED) {
3138                return PROCESS_STATE_HOME;
3139            } else if (importance >= IMPORTANCE_SERVICE) {
3140                return PROCESS_STATE_SERVICE;
3141            } else if (importance > IMPORTANCE_CANT_SAVE_STATE) {
3142                return PROCESS_STATE_HEAVY_WEIGHT;
3143            } else if (importance >= IMPORTANCE_PERCEPTIBLE) {
3144                return PROCESS_STATE_TRANSIENT_BACKGROUND;
3145            } else if (importance >= IMPORTANCE_VISIBLE) {
3146                return PROCESS_STATE_IMPORTANT_FOREGROUND;
3147            } else if (importance >= IMPORTANCE_TOP_SLEEPING) {
3148                return PROCESS_STATE_TOP_SLEEPING;
3149            } else if (importance >= IMPORTANCE_FOREGROUND_SERVICE) {
3150                return PROCESS_STATE_FOREGROUND_SERVICE;
3151            } else {
3152                return PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
3153            }
3154        }
3155
3156        /**
3157         * The relative importance level that the system places on this process.
3158         * These constants are numbered so that "more important" values are
3159         * always smaller than "less important" values.
3160         */
3161        public @Importance int importance;
3162
3163        /**
3164         * An additional ordering within a particular {@link #importance}
3165         * category, providing finer-grained information about the relative
3166         * utility of processes within a category.  This number means nothing
3167         * except that a smaller values are more recently used (and thus
3168         * more important).  Currently an LRU value is only maintained for
3169         * the {@link #IMPORTANCE_CACHED} category, though others may
3170         * be maintained in the future.
3171         */
3172        public int lru;
3173
3174        /**
3175         * Constant for {@link #importanceReasonCode}: nothing special has
3176         * been specified for the reason for this level.
3177         */
3178        public static final int REASON_UNKNOWN = 0;
3179
3180        /**
3181         * Constant for {@link #importanceReasonCode}: one of the application's
3182         * content providers is being used by another process.  The pid of
3183         * the client process is in {@link #importanceReasonPid} and the
3184         * target provider in this process is in
3185         * {@link #importanceReasonComponent}.
3186         */
3187        public static final int REASON_PROVIDER_IN_USE = 1;
3188
3189        /**
3190         * Constant for {@link #importanceReasonCode}: one of the application's
3191         * content providers is being used by another process.  The pid of
3192         * the client process is in {@link #importanceReasonPid} and the
3193         * target provider in this process is in
3194         * {@link #importanceReasonComponent}.
3195         */
3196        public static final int REASON_SERVICE_IN_USE = 2;
3197
3198        /**
3199         * The reason for {@link #importance}, if any.
3200         */
3201        public int importanceReasonCode;
3202
3203        /**
3204         * For the specified values of {@link #importanceReasonCode}, this
3205         * is the process ID of the other process that is a client of this
3206         * process.  This will be 0 if no other process is using this one.
3207         */
3208        public int importanceReasonPid;
3209
3210        /**
3211         * For the specified values of {@link #importanceReasonCode}, this
3212         * is the name of the component that is being used in this process.
3213         */
3214        public ComponentName importanceReasonComponent;
3215
3216        /**
3217         * When {@link #importanceReasonPid} is non-0, this is the importance
3218         * of the other pid. @hide
3219         */
3220        public int importanceReasonImportance;
3221
3222        /**
3223         * Current process state, as per PROCESS_STATE_* constants.
3224         * @hide
3225         */
3226        public int processState;
3227
3228        public RunningAppProcessInfo() {
3229            importance = IMPORTANCE_FOREGROUND;
3230            importanceReasonCode = REASON_UNKNOWN;
3231            processState = PROCESS_STATE_IMPORTANT_FOREGROUND;
3232        }
3233
3234        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
3235            processName = pProcessName;
3236            pid = pPid;
3237            pkgList = pArr;
3238        }
3239
3240        public int describeContents() {
3241            return 0;
3242        }
3243
3244        public void writeToParcel(Parcel dest, int flags) {
3245            dest.writeString(processName);
3246            dest.writeInt(pid);
3247            dest.writeInt(uid);
3248            dest.writeStringArray(pkgList);
3249            dest.writeInt(this.flags);
3250            dest.writeInt(lastTrimLevel);
3251            dest.writeInt(importance);
3252            dest.writeInt(lru);
3253            dest.writeInt(importanceReasonCode);
3254            dest.writeInt(importanceReasonPid);
3255            ComponentName.writeToParcel(importanceReasonComponent, dest);
3256            dest.writeInt(importanceReasonImportance);
3257            dest.writeInt(processState);
3258        }
3259
3260        public void readFromParcel(Parcel source) {
3261            processName = source.readString();
3262            pid = source.readInt();
3263            uid = source.readInt();
3264            pkgList = source.readStringArray();
3265            flags = source.readInt();
3266            lastTrimLevel = source.readInt();
3267            importance = source.readInt();
3268            lru = source.readInt();
3269            importanceReasonCode = source.readInt();
3270            importanceReasonPid = source.readInt();
3271            importanceReasonComponent = ComponentName.readFromParcel(source);
3272            importanceReasonImportance = source.readInt();
3273            processState = source.readInt();
3274        }
3275
3276        public static final Creator<RunningAppProcessInfo> CREATOR =
3277            new Creator<RunningAppProcessInfo>() {
3278            public RunningAppProcessInfo createFromParcel(Parcel source) {
3279                return new RunningAppProcessInfo(source);
3280            }
3281            public RunningAppProcessInfo[] newArray(int size) {
3282                return new RunningAppProcessInfo[size];
3283            }
3284        };
3285
3286        private RunningAppProcessInfo(Parcel source) {
3287            readFromParcel(source);
3288        }
3289    }
3290
3291    /**
3292     * Returns a list of application processes installed on external media
3293     * that are running on the device.
3294     *
3295     * <p><b>Note: this method is only intended for debugging or building
3296     * a user-facing process management UI.</b></p>
3297     *
3298     * @return Returns a list of ApplicationInfo records, or null if none
3299     * This list ordering is not specified.
3300     * @hide
3301     */
3302    public List<ApplicationInfo> getRunningExternalApplications() {
3303        try {
3304            return getService().getRunningExternalApplications();
3305        } catch (RemoteException e) {
3306            throw e.rethrowFromSystemServer();
3307        }
3308    }
3309
3310    /**
3311     * Sets the memory trim mode for a process and schedules a memory trim operation.
3312     *
3313     * <p><b>Note: this method is only intended for testing framework.</b></p>
3314     *
3315     * @return Returns true if successful.
3316     * @hide
3317     */
3318    public boolean setProcessMemoryTrimLevel(String process, int userId, int level) {
3319        try {
3320            return getService().setProcessMemoryTrimLevel(process, userId,
3321                    level);
3322        } catch (RemoteException e) {
3323            throw e.rethrowFromSystemServer();
3324        }
3325    }
3326
3327    /**
3328     * Returns a list of application processes that are running on the device.
3329     *
3330     * <p><b>Note: this method is only intended for debugging or building
3331     * a user-facing process management UI.</b></p>
3332     *
3333     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
3334     * running processes (it will not return an empty list).  This list ordering is not
3335     * specified.
3336     */
3337    public List<RunningAppProcessInfo> getRunningAppProcesses() {
3338        try {
3339            return getService().getRunningAppProcesses();
3340        } catch (RemoteException e) {
3341            throw e.rethrowFromSystemServer();
3342        }
3343    }
3344
3345    /**
3346     * Return the importance of a given package name, based on the processes that are
3347     * currently running.  The return value is one of the importance constants defined
3348     * in {@link RunningAppProcessInfo}, giving you the highest importance of all the
3349     * processes that this package has code running inside of.  If there are no processes
3350     * running its code, {@link RunningAppProcessInfo#IMPORTANCE_GONE} is returned.
3351     * @hide
3352     */
3353    @SystemApi @TestApi
3354    @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3355    public @RunningAppProcessInfo.Importance int getPackageImportance(String packageName) {
3356        try {
3357            int procState = getService().getPackageProcessState(packageName,
3358                    mContext.getOpPackageName());
3359            return RunningAppProcessInfo.procStateToImportanceForClient(procState, mContext);
3360        } catch (RemoteException e) {
3361            throw e.rethrowFromSystemServer();
3362        }
3363    }
3364
3365    /**
3366     * Return the importance of a given uid, based on the processes that are
3367     * currently running.  The return value is one of the importance constants defined
3368     * in {@link RunningAppProcessInfo}, giving you the highest importance of all the
3369     * processes that this uid has running.  If there are no processes
3370     * running its code, {@link RunningAppProcessInfo#IMPORTANCE_GONE} is returned.
3371     * @hide
3372     */
3373    @SystemApi @TestApi
3374    @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3375    public @RunningAppProcessInfo.Importance int getUidImportance(int uid) {
3376        try {
3377            int procState = getService().getUidProcessState(uid,
3378                    mContext.getOpPackageName());
3379            return RunningAppProcessInfo.procStateToImportanceForClient(procState, mContext);
3380        } catch (RemoteException e) {
3381            throw e.rethrowFromSystemServer();
3382        }
3383    }
3384
3385    /**
3386     * Callback to get reports about changes to the importance of a uid.  Use with
3387     * {@link #addOnUidImportanceListener}.
3388     * @hide
3389     */
3390    @SystemApi @TestApi
3391    public interface OnUidImportanceListener {
3392        /**
3393         * The importance if a given uid has changed.  Will be one of the importance
3394         * values in {@link RunningAppProcessInfo};
3395         * {@link RunningAppProcessInfo#IMPORTANCE_GONE IMPORTANCE_GONE} will be reported
3396         * when the uid is no longer running at all.  This callback will happen on a thread
3397         * from a thread pool, not the main UI thread.
3398         * @param uid The uid whose importance has changed.
3399         * @param importance The new importance value as per {@link RunningAppProcessInfo}.
3400         */
3401        void onUidImportance(int uid, @RunningAppProcessInfo.Importance int importance);
3402    }
3403
3404    /**
3405     * Start monitoring changes to the imoportance of uids running in the system.
3406     * @param listener The listener callback that will receive change reports.
3407     * @param importanceCutpoint The level of importance in which the caller is interested
3408     * in differences.  For example, if {@link RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE}
3409     * is used here, you will receive a call each time a uids importance transitions between
3410     * being <= {@link RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE} and
3411     * > {@link RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE}.
3412     *
3413     * <p>The caller must hold the {@link android.Manifest.permission#PACKAGE_USAGE_STATS}
3414     * permission to use this feature.</p>
3415     *
3416     * @throws IllegalArgumentException If the listener is already registered.
3417     * @throws SecurityException If the caller does not hold
3418     * {@link android.Manifest.permission#PACKAGE_USAGE_STATS}.
3419     * @hide
3420     */
3421    @SystemApi @TestApi
3422    @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3423    public void addOnUidImportanceListener(OnUidImportanceListener listener,
3424            @RunningAppProcessInfo.Importance int importanceCutpoint) {
3425        synchronized (this) {
3426            if (mImportanceListeners.containsKey(listener)) {
3427                throw new IllegalArgumentException("Listener already registered: " + listener);
3428            }
3429            // TODO: implement the cut point in the system process to avoid IPCs.
3430            UidObserver observer = new UidObserver(listener, mContext);
3431            try {
3432                getService().registerUidObserver(observer,
3433                        UID_OBSERVER_PROCSTATE | UID_OBSERVER_GONE,
3434                        RunningAppProcessInfo.importanceToProcState(importanceCutpoint),
3435                        mContext.getOpPackageName());
3436            } catch (RemoteException e) {
3437                throw e.rethrowFromSystemServer();
3438            }
3439            mImportanceListeners.put(listener, observer);
3440        }
3441    }
3442
3443    /**
3444     * Remove an importance listener that was previously registered with
3445     * {@link #addOnUidImportanceListener}.
3446     *
3447     * @throws IllegalArgumentException If the listener is not registered.
3448     * @hide
3449     */
3450    @SystemApi @TestApi
3451    @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3452    public void removeOnUidImportanceListener(OnUidImportanceListener listener) {
3453        synchronized (this) {
3454            UidObserver observer = mImportanceListeners.remove(listener);
3455            if (observer == null) {
3456                throw new IllegalArgumentException("Listener not registered: " + listener);
3457            }
3458            try {
3459                getService().unregisterUidObserver(observer);
3460            } catch (RemoteException e) {
3461                throw e.rethrowFromSystemServer();
3462            }
3463        }
3464    }
3465
3466    /**
3467     * Return global memory state information for the calling process.  This
3468     * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
3469     * only fields that will be filled in are
3470     * {@link RunningAppProcessInfo#pid},
3471     * {@link RunningAppProcessInfo#uid},
3472     * {@link RunningAppProcessInfo#lastTrimLevel},
3473     * {@link RunningAppProcessInfo#importance},
3474     * {@link RunningAppProcessInfo#lru}, and
3475     * {@link RunningAppProcessInfo#importanceReasonCode}.
3476     */
3477    static public void getMyMemoryState(RunningAppProcessInfo outState) {
3478        try {
3479            getService().getMyMemoryState(outState);
3480        } catch (RemoteException e) {
3481            throw e.rethrowFromSystemServer();
3482        }
3483    }
3484
3485    /**
3486     * Return information about the memory usage of one or more processes.
3487     *
3488     * <p><b>Note: this method is only intended for debugging or building
3489     * a user-facing process management UI.</b></p>
3490     *
3491     * @param pids The pids of the processes whose memory usage is to be
3492     * retrieved.
3493     * @return Returns an array of memory information, one for each
3494     * requested pid.
3495     */
3496    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
3497        try {
3498            return getService().getProcessMemoryInfo(pids);
3499        } catch (RemoteException e) {
3500            throw e.rethrowFromSystemServer();
3501        }
3502    }
3503
3504    /**
3505     * @deprecated This is now just a wrapper for
3506     * {@link #killBackgroundProcesses(String)}; the previous behavior here
3507     * is no longer available to applications because it allows them to
3508     * break other applications by removing their alarms, stopping their
3509     * services, etc.
3510     */
3511    @Deprecated
3512    public void restartPackage(String packageName) {
3513        killBackgroundProcesses(packageName);
3514    }
3515
3516    /**
3517     * Have the system immediately kill all background processes associated
3518     * with the given package.  This is the same as the kernel killing those
3519     * processes to reclaim memory; the system will take care of restarting
3520     * these processes in the future as needed.
3521     *
3522     * @param packageName The name of the package whose processes are to
3523     * be killed.
3524     */
3525    @RequiresPermission(Manifest.permission.KILL_BACKGROUND_PROCESSES)
3526    public void killBackgroundProcesses(String packageName) {
3527        try {
3528            getService().killBackgroundProcesses(packageName,
3529                    UserHandle.myUserId());
3530        } catch (RemoteException e) {
3531            throw e.rethrowFromSystemServer();
3532        }
3533    }
3534
3535    /**
3536     * Kills the specified UID.
3537     * @param uid The UID to kill.
3538     * @param reason The reason for the kill.
3539     *
3540     * @hide
3541     */
3542    @SystemApi
3543    @RequiresPermission(Manifest.permission.KILL_UID)
3544    public void killUid(int uid, String reason) {
3545        try {
3546            getService().killUid(UserHandle.getAppId(uid),
3547                    UserHandle.getUserId(uid), reason);
3548        } catch (RemoteException e) {
3549            throw e.rethrowFromSystemServer();
3550        }
3551    }
3552
3553    /**
3554     * Have the system perform a force stop of everything associated with
3555     * the given application package.  All processes that share its uid
3556     * will be killed, all services it has running stopped, all activities
3557     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
3558     * broadcast will be sent, so that any of its registered alarms can
3559     * be stopped, notifications removed, etc.
3560     *
3561     * <p>You must hold the permission
3562     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
3563     * call this method.
3564     *
3565     * @param packageName The name of the package to be stopped.
3566     * @param userId The user for which the running package is to be stopped.
3567     *
3568     * @hide This is not available to third party applications due to
3569     * it allowing them to break other applications by stopping their
3570     * services, removing their alarms, etc.
3571     */
3572    public void forceStopPackageAsUser(String packageName, int userId) {
3573        try {
3574            getService().forceStopPackage(packageName, userId);
3575        } catch (RemoteException e) {
3576            throw e.rethrowFromSystemServer();
3577        }
3578    }
3579
3580    /**
3581     * @see #forceStopPackageAsUser(String, int)
3582     * @hide
3583     */
3584    @SystemApi
3585    @RequiresPermission(Manifest.permission.FORCE_STOP_PACKAGES)
3586    public void forceStopPackage(String packageName) {
3587        forceStopPackageAsUser(packageName, UserHandle.myUserId());
3588    }
3589
3590    /**
3591     * Get the device configuration attributes.
3592     */
3593    public ConfigurationInfo getDeviceConfigurationInfo() {
3594        try {
3595            return getService().getDeviceConfigurationInfo();
3596        } catch (RemoteException e) {
3597            throw e.rethrowFromSystemServer();
3598        }
3599    }
3600
3601    /**
3602     * Get the preferred density of icons for the launcher. This is used when
3603     * custom drawables are created (e.g., for shortcuts).
3604     *
3605     * @return density in terms of DPI
3606     */
3607    public int getLauncherLargeIconDensity() {
3608        final Resources res = mContext.getResources();
3609        final int density = res.getDisplayMetrics().densityDpi;
3610        final int sw = res.getConfiguration().smallestScreenWidthDp;
3611
3612        if (sw < 600) {
3613            // Smaller than approx 7" tablets, use the regular icon size.
3614            return density;
3615        }
3616
3617        switch (density) {
3618            case DisplayMetrics.DENSITY_LOW:
3619                return DisplayMetrics.DENSITY_MEDIUM;
3620            case DisplayMetrics.DENSITY_MEDIUM:
3621                return DisplayMetrics.DENSITY_HIGH;
3622            case DisplayMetrics.DENSITY_TV:
3623                return DisplayMetrics.DENSITY_XHIGH;
3624            case DisplayMetrics.DENSITY_HIGH:
3625                return DisplayMetrics.DENSITY_XHIGH;
3626            case DisplayMetrics.DENSITY_XHIGH:
3627                return DisplayMetrics.DENSITY_XXHIGH;
3628            case DisplayMetrics.DENSITY_XXHIGH:
3629                return DisplayMetrics.DENSITY_XHIGH * 2;
3630            default:
3631                // The density is some abnormal value.  Return some other
3632                // abnormal value that is a reasonable scaling of it.
3633                return (int)((density*1.5f)+.5f);
3634        }
3635    }
3636
3637    /**
3638     * Get the preferred launcher icon size. This is used when custom drawables
3639     * are created (e.g., for shortcuts).
3640     *
3641     * @return dimensions of square icons in terms of pixels
3642     */
3643    public int getLauncherLargeIconSize() {
3644        return getLauncherLargeIconSizeInner(mContext);
3645    }
3646
3647    static int getLauncherLargeIconSizeInner(Context context) {
3648        final Resources res = context.getResources();
3649        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
3650        final int sw = res.getConfiguration().smallestScreenWidthDp;
3651
3652        if (sw < 600) {
3653            // Smaller than approx 7" tablets, use the regular icon size.
3654            return size;
3655        }
3656
3657        final int density = res.getDisplayMetrics().densityDpi;
3658
3659        switch (density) {
3660            case DisplayMetrics.DENSITY_LOW:
3661                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
3662            case DisplayMetrics.DENSITY_MEDIUM:
3663                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
3664            case DisplayMetrics.DENSITY_TV:
3665                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
3666            case DisplayMetrics.DENSITY_HIGH:
3667                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
3668            case DisplayMetrics.DENSITY_XHIGH:
3669                return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
3670            case DisplayMetrics.DENSITY_XXHIGH:
3671                return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
3672            default:
3673                // The density is some abnormal value.  Return some other
3674                // abnormal value that is a reasonable scaling of it.
3675                return (int)((size*1.5f) + .5f);
3676        }
3677    }
3678
3679    /**
3680     * Returns "true" if the user interface is currently being messed with
3681     * by a monkey.
3682     */
3683    public static boolean isUserAMonkey() {
3684        try {
3685            return getService().isUserAMonkey();
3686        } catch (RemoteException e) {
3687            throw e.rethrowFromSystemServer();
3688        }
3689    }
3690
3691    /**
3692     * Returns "true" if device is running in a test harness.
3693     */
3694    public static boolean isRunningInTestHarness() {
3695        return SystemProperties.getBoolean("ro.test_harness", false);
3696    }
3697
3698    /**
3699     * Returns the launch count of each installed package.
3700     *
3701     * @hide
3702     */
3703    /*public Map<String, Integer> getAllPackageLaunchCounts() {
3704        try {
3705            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
3706                    ServiceManager.getService("usagestats"));
3707            if (usageStatsService == null) {
3708                return new HashMap<String, Integer>();
3709            }
3710
3711            UsageStats.PackageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats(
3712                    ActivityThread.currentPackageName());
3713            if (allPkgUsageStats == null) {
3714                return new HashMap<String, Integer>();
3715            }
3716
3717            Map<String, Integer> launchCounts = new HashMap<String, Integer>();
3718            for (UsageStats.PackageStats pkgUsageStats : allPkgUsageStats) {
3719                launchCounts.put(pkgUsageStats.getPackageName(), pkgUsageStats.getLaunchCount());
3720            }
3721
3722            return launchCounts;
3723        } catch (RemoteException e) {
3724            Log.w(TAG, "Could not query launch counts", e);
3725            return new HashMap<String, Integer>();
3726        }
3727    }*/
3728
3729    /** @hide */
3730    public static int checkComponentPermission(String permission, int uid,
3731            int owningUid, boolean exported) {
3732        // Root, system server get to do everything.
3733        final int appId = UserHandle.getAppId(uid);
3734        if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
3735            return PackageManager.PERMISSION_GRANTED;
3736        }
3737        // Isolated processes don't get any permissions.
3738        if (UserHandle.isIsolated(uid)) {
3739            return PackageManager.PERMISSION_DENIED;
3740        }
3741        // If there is a uid that owns whatever is being accessed, it has
3742        // blanket access to it regardless of the permissions it requires.
3743        if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
3744            return PackageManager.PERMISSION_GRANTED;
3745        }
3746        // If the target is not exported, then nobody else can get to it.
3747        if (!exported) {
3748            /*
3749            RuntimeException here = new RuntimeException("here");
3750            here.fillInStackTrace();
3751            Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
3752                    here);
3753            */
3754            return PackageManager.PERMISSION_DENIED;
3755        }
3756        if (permission == null) {
3757            return PackageManager.PERMISSION_GRANTED;
3758        }
3759        try {
3760            return AppGlobals.getPackageManager()
3761                    .checkUidPermission(permission, uid);
3762        } catch (RemoteException e) {
3763            throw e.rethrowFromSystemServer();
3764        }
3765    }
3766
3767    /** @hide */
3768    public static int checkUidPermission(String permission, int uid) {
3769        try {
3770            return AppGlobals.getPackageManager()
3771                    .checkUidPermission(permission, uid);
3772        } catch (RemoteException e) {
3773            throw e.rethrowFromSystemServer();
3774        }
3775    }
3776
3777    /**
3778     * @hide
3779     * Helper for dealing with incoming user arguments to system service calls.
3780     * Takes care of checking permissions and converting USER_CURRENT to the
3781     * actual current user.
3782     *
3783     * @param callingPid The pid of the incoming call, as per Binder.getCallingPid().
3784     * @param callingUid The uid of the incoming call, as per Binder.getCallingUid().
3785     * @param userId The user id argument supplied by the caller -- this is the user
3786     * they want to run as.
3787     * @param allowAll If true, we will allow USER_ALL.  This means you must be prepared
3788     * to get a USER_ALL returned and deal with it correctly.  If false,
3789     * an exception will be thrown if USER_ALL is supplied.
3790     * @param requireFull If true, the caller must hold
3791     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a
3792     * different user than their current process; otherwise they must hold
3793     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
3794     * @param name Optional textual name of the incoming call; only for generating error messages.
3795     * @param callerPackage Optional package name of caller; only for error messages.
3796     *
3797     * @return Returns the user ID that the call should run as.  Will always be a concrete
3798     * user number, unless <var>allowAll</var> is true in which case it could also be
3799     * USER_ALL.
3800     */
3801    public static int handleIncomingUser(int callingPid, int callingUid, int userId,
3802            boolean allowAll, boolean requireFull, String name, String callerPackage) {
3803        if (UserHandle.getUserId(callingUid) == userId) {
3804            return userId;
3805        }
3806        try {
3807            return getService().handleIncomingUser(callingPid,
3808                    callingUid, userId, allowAll, requireFull, name, callerPackage);
3809        } catch (RemoteException e) {
3810            throw e.rethrowFromSystemServer();
3811        }
3812    }
3813
3814    /**
3815     * Gets the userId of the current foreground user. Requires system permissions.
3816     * @hide
3817     */
3818    @SystemApi
3819    @RequiresPermission(anyOf = {
3820            "android.permission.INTERACT_ACROSS_USERS",
3821            "android.permission.INTERACT_ACROSS_USERS_FULL"
3822    })
3823    public static int getCurrentUser() {
3824        UserInfo ui;
3825        try {
3826            ui = getService().getCurrentUser();
3827            return ui != null ? ui.id : 0;
3828        } catch (RemoteException e) {
3829            throw e.rethrowFromSystemServer();
3830        }
3831    }
3832
3833    /**
3834     * @param userid the user's id. Zero indicates the default user.
3835     * @hide
3836     */
3837    public boolean switchUser(int userid) {
3838        try {
3839            return getService().switchUser(userid);
3840        } catch (RemoteException e) {
3841            throw e.rethrowFromSystemServer();
3842        }
3843    }
3844
3845    /**
3846     * Logs out current current foreground user by switching to the system user and stopping the
3847     * user being switched from.
3848     * @hide
3849     */
3850    public static void logoutCurrentUser() {
3851        int currentUser = ActivityManager.getCurrentUser();
3852        if (currentUser != UserHandle.USER_SYSTEM) {
3853            try {
3854                getService().switchUser(UserHandle.USER_SYSTEM);
3855                getService().stopUser(currentUser, /* force= */ false, null);
3856            } catch (RemoteException e) {
3857                e.rethrowFromSystemServer();
3858            }
3859        }
3860    }
3861
3862    /** {@hide} */
3863    public static final int FLAG_OR_STOPPED = 1 << 0;
3864    /** {@hide} */
3865    public static final int FLAG_AND_LOCKED = 1 << 1;
3866    /** {@hide} */
3867    public static final int FLAG_AND_UNLOCKED = 1 << 2;
3868    /** {@hide} */
3869    public static final int FLAG_AND_UNLOCKING_OR_UNLOCKED = 1 << 3;
3870
3871    /**
3872     * Return whether the given user is actively running.  This means that
3873     * the user is in the "started" state, not "stopped" -- it is currently
3874     * allowed to run code through scheduled alarms, receiving broadcasts,
3875     * etc.  A started user may be either the current foreground user or a
3876     * background user; the result here does not distinguish between the two.
3877     * @param userId the user's id. Zero indicates the default user.
3878     * @hide
3879     */
3880    public boolean isUserRunning(int userId) {
3881        try {
3882            return getService().isUserRunning(userId, 0);
3883        } catch (RemoteException e) {
3884            throw e.rethrowFromSystemServer();
3885        }
3886    }
3887
3888    /** {@hide} */
3889    public boolean isVrModePackageEnabled(ComponentName component) {
3890        try {
3891            return getService().isVrModePackageEnabled(component);
3892        } catch (RemoteException e) {
3893            throw e.rethrowFromSystemServer();
3894        }
3895    }
3896
3897    /**
3898     * Perform a system dump of various state associated with the given application
3899     * package name.  This call blocks while the dump is being performed, so should
3900     * not be done on a UI thread.  The data will be written to the given file
3901     * descriptor as text.
3902     * @param fd The file descriptor that the dump should be written to.  The file
3903     * descriptor is <em>not</em> closed by this function; the caller continues to
3904     * own it.
3905     * @param packageName The name of the package that is to be dumped.
3906     */
3907    @RequiresPermission(Manifest.permission.DUMP)
3908    public void dumpPackageState(FileDescriptor fd, String packageName) {
3909        dumpPackageStateStatic(fd, packageName);
3910    }
3911
3912    /**
3913     * @hide
3914     */
3915    public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) {
3916        FileOutputStream fout = new FileOutputStream(fd);
3917        PrintWriter pw = new FastPrintWriter(fout);
3918        dumpService(pw, fd, "package", new String[] { packageName });
3919        pw.println();
3920        dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] {
3921                "-a", "package", packageName });
3922        pw.println();
3923        dumpService(pw, fd, "meminfo", new String[] { "--local", "--package", packageName });
3924        pw.println();
3925        dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { packageName });
3926        pw.println();
3927        dumpService(pw, fd, "usagestats", new String[] { "--packages", packageName });
3928        pw.println();
3929        dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName });
3930        pw.flush();
3931    }
3932
3933    /**
3934     * @hide
3935     */
3936    public static boolean isSystemReady() {
3937        if (!sSystemReady) {
3938            if (ActivityThread.isSystem()) {
3939                sSystemReady =
3940                        LocalServices.getService(ActivityManagerInternal.class).isSystemReady();
3941            } else {
3942                // Since this is being called from outside system server, system should be
3943                // ready by now.
3944                sSystemReady = true;
3945            }
3946        }
3947        return sSystemReady;
3948    }
3949
3950    /**
3951     * @hide
3952     */
3953    public static void broadcastStickyIntent(Intent intent, int userId) {
3954        broadcastStickyIntent(intent, AppOpsManager.OP_NONE, userId);
3955    }
3956
3957    /**
3958     * Convenience for sending a sticky broadcast.  For internal use only.
3959     *
3960     * @hide
3961     */
3962    public static void broadcastStickyIntent(Intent intent, int appOp, int userId) {
3963        try {
3964            getService().broadcastIntent(
3965                    null, intent, null, null, Activity.RESULT_OK, null, null,
3966                    null /*permission*/, appOp, null, false, true, userId);
3967        } catch (RemoteException ex) {
3968        }
3969    }
3970
3971    /**
3972     * @hide
3973     */
3974    public static void noteWakeupAlarm(PendingIntent ps, int sourceUid, String sourcePkg,
3975            String tag) {
3976        try {
3977            getService().noteWakeupAlarm((ps != null) ? ps.getTarget() : null,
3978                    sourceUid, sourcePkg, tag);
3979        } catch (RemoteException ex) {
3980        }
3981    }
3982
3983    /**
3984     * @hide
3985     */
3986    public static void noteAlarmStart(PendingIntent ps, int sourceUid, String tag) {
3987        try {
3988            getService().noteAlarmStart((ps != null) ? ps.getTarget() : null, sourceUid, tag);
3989        } catch (RemoteException ex) {
3990        }
3991    }
3992
3993    /**
3994     * @hide
3995     */
3996    public static void noteAlarmFinish(PendingIntent ps, int sourceUid, String tag) {
3997        try {
3998            getService().noteAlarmFinish((ps != null) ? ps.getTarget() : null, sourceUid, tag);
3999        } catch (RemoteException ex) {
4000        }
4001    }
4002
4003    /**
4004     * @hide
4005     */
4006    public static IActivityManager getService() {
4007        return IActivityManagerSingleton.get();
4008    }
4009
4010    private static final Singleton<IActivityManager> IActivityManagerSingleton =
4011            new Singleton<IActivityManager>() {
4012                @Override
4013                protected IActivityManager create() {
4014                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
4015                    final IActivityManager am = IActivityManager.Stub.asInterface(b);
4016                    return am;
4017                }
4018            };
4019
4020    private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) {
4021        pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
4022        IBinder service = ServiceManager.checkService(name);
4023        if (service == null) {
4024            pw.println("  (Service not found)");
4025            return;
4026        }
4027        TransferPipe tp = null;
4028        try {
4029            pw.flush();
4030            tp = new TransferPipe();
4031            tp.setBufferPrefix("  ");
4032            service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args);
4033            tp.go(fd, 10000);
4034        } catch (Throwable e) {
4035            if (tp != null) {
4036                tp.kill();
4037            }
4038            pw.println("Failure dumping service:");
4039            e.printStackTrace(pw);
4040        }
4041    }
4042
4043    /**
4044     * Request that the system start watching for the calling process to exceed a pss
4045     * size as given here.  Once called, the system will look for any occasions where it
4046     * sees the associated process with a larger pss size and, when this happens, automatically
4047     * pull a heap dump from it and allow the user to share the data.  Note that this request
4048     * continues running even if the process is killed and restarted.  To remove the watch,
4049     * use {@link #clearWatchHeapLimit()}.
4050     *
4051     * <p>This API only work if the calling process has been marked as
4052     * {@link ApplicationInfo#FLAG_DEBUGGABLE} or this is running on a debuggable
4053     * (userdebug or eng) build.</p>
4054     *
4055     * <p>Callers can optionally implement {@link #ACTION_REPORT_HEAP_LIMIT} to directly
4056     * handle heap limit reports themselves.</p>
4057     *
4058     * @param pssSize The size in bytes to set the limit at.
4059     */
4060    public void setWatchHeapLimit(long pssSize) {
4061        try {
4062            getService().setDumpHeapDebugLimit(null, 0, pssSize,
4063                    mContext.getPackageName());
4064        } catch (RemoteException e) {
4065            throw e.rethrowFromSystemServer();
4066        }
4067    }
4068
4069    /**
4070     * Action an app can implement to handle reports from {@link #setWatchHeapLimit(long)}.
4071     * If your package has an activity handling this action, it will be launched with the
4072     * heap data provided to it the same way as {@link Intent#ACTION_SEND}.  Note that to
4073     * match the activty must support this action and a MIME type of "*&#47;*".
4074     */
4075    public static final String ACTION_REPORT_HEAP_LIMIT = "android.app.action.REPORT_HEAP_LIMIT";
4076
4077    /**
4078     * Clear a heap watch limit previously set by {@link #setWatchHeapLimit(long)}.
4079     */
4080    public void clearWatchHeapLimit() {
4081        try {
4082            getService().setDumpHeapDebugLimit(null, 0, 0, null);
4083        } catch (RemoteException e) {
4084            throw e.rethrowFromSystemServer();
4085        }
4086    }
4087
4088    /**
4089     * Return whether currently in lock task mode.  When in this mode
4090     * no new tasks can be created or switched to.
4091     *
4092     * @see Activity#startLockTask()
4093     *
4094     * @deprecated Use {@link #getLockTaskModeState} instead.
4095     */
4096    @Deprecated
4097    public boolean isInLockTaskMode() {
4098        return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
4099    }
4100
4101    /**
4102     * Return the current state of task locking. The three possible outcomes
4103     * are {@link #LOCK_TASK_MODE_NONE}, {@link #LOCK_TASK_MODE_LOCKED}
4104     * and {@link #LOCK_TASK_MODE_PINNED}.
4105     *
4106     * @see Activity#startLockTask()
4107     */
4108    public int getLockTaskModeState() {
4109        try {
4110            return getService().getLockTaskModeState();
4111        } catch (RemoteException e) {
4112            throw e.rethrowFromSystemServer();
4113        }
4114    }
4115
4116    /**
4117     * Enable more aggressive scheduling for latency-sensitive low-runtime VR threads. Only one
4118     * thread can be a VR thread in a process at a time, and that thread may be subject to
4119     * restrictions on the amount of time it can run.
4120     *
4121     * If persistent VR mode is set, whatever thread has been granted aggressive scheduling via this
4122     * method will return to normal operation, and calling this method will do nothing while
4123     * persistent VR mode is enabled.
4124     *
4125     * To reset the VR thread for an application, a tid of 0 can be passed.
4126     *
4127     * @see android.os.Process#myTid()
4128     * @param tid tid of the VR thread
4129     */
4130    public static void setVrThread(int tid) {
4131        try {
4132            getService().setVrThread(tid);
4133        } catch (RemoteException e) {
4134            // pass
4135        }
4136    }
4137
4138    /**
4139     * Enable more aggressive scheduling for latency-sensitive low-runtime VR threads that persist
4140     * beyond a single process. Only one thread can be a
4141     * persistent VR thread at a time, and that thread may be subject to restrictions on the amount
4142     * of time it can run. Calling this method will disable aggressive scheduling for non-persistent
4143     * VR threads set via {@link #setVrThread}. If persistent VR mode is disabled then the
4144     * persistent VR thread loses its new scheduling priority; this method must be called again to
4145     * set the persistent thread.
4146     *
4147     * To reset the persistent VR thread, a tid of 0 can be passed.
4148     *
4149     * @see android.os.Process#myTid()
4150     * @param tid tid of the VR thread
4151     * @hide
4152     */
4153    @RequiresPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
4154    public static void setPersistentVrThread(int tid) {
4155        try {
4156            getService().setPersistentVrThread(tid);
4157        } catch (RemoteException e) {
4158            // pass
4159        }
4160    }
4161
4162    /**
4163     * The AppTask allows you to manage your own application's tasks.
4164     * See {@link android.app.ActivityManager#getAppTasks()}
4165     */
4166    public static class AppTask {
4167        private IAppTask mAppTaskImpl;
4168
4169        /** @hide */
4170        public AppTask(IAppTask task) {
4171            mAppTaskImpl = task;
4172        }
4173
4174        /**
4175         * Finishes all activities in this task and removes it from the recent tasks list.
4176         */
4177        public void finishAndRemoveTask() {
4178            try {
4179                mAppTaskImpl.finishAndRemoveTask();
4180            } catch (RemoteException e) {
4181                throw e.rethrowFromSystemServer();
4182            }
4183        }
4184
4185        /**
4186         * Get the RecentTaskInfo associated with this task.
4187         *
4188         * @return The RecentTaskInfo for this task, or null if the task no longer exists.
4189         */
4190        public RecentTaskInfo getTaskInfo() {
4191            try {
4192                return mAppTaskImpl.getTaskInfo();
4193            } catch (RemoteException e) {
4194                throw e.rethrowFromSystemServer();
4195            }
4196        }
4197
4198        /**
4199         * Bring this task to the foreground.  If it contains activities, they will be
4200         * brought to the foreground with it and their instances re-created if needed.
4201         * If it doesn't contain activities, the root activity of the task will be
4202         * re-launched.
4203         */
4204        public void moveToFront() {
4205            try {
4206                mAppTaskImpl.moveToFront();
4207            } catch (RemoteException e) {
4208                throw e.rethrowFromSystemServer();
4209            }
4210        }
4211
4212        /**
4213         * Start an activity in this task.  Brings the task to the foreground.  If this task
4214         * is not currently active (that is, its id < 0), then a new activity for the given
4215         * Intent will be launched as the root of the task and the task brought to the
4216         * foreground.  Otherwise, if this task is currently active and the Intent does not specify
4217         * an activity to launch in a new task, then a new activity for the given Intent will
4218         * be launched on top of the task and the task brought to the foreground.  If this
4219         * task is currently active and the Intent specifies {@link Intent#FLAG_ACTIVITY_NEW_TASK}
4220         * or would otherwise be launched in to a new task, then the activity not launched but
4221         * this task be brought to the foreground and a new intent delivered to the top
4222         * activity if appropriate.
4223         *
4224         * <p>In other words, you generally want to use an Intent here that does not specify
4225         * {@link Intent#FLAG_ACTIVITY_NEW_TASK} or {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT},
4226         * and let the system do the right thing.</p>
4227         *
4228         * @param intent The Intent describing the new activity to be launched on the task.
4229         * @param options Optional launch options.
4230         *
4231         * @see Activity#startActivity(android.content.Intent, android.os.Bundle)
4232         */
4233        public void startActivity(Context context, Intent intent, Bundle options) {
4234            ActivityThread thread = ActivityThread.currentActivityThread();
4235            thread.getInstrumentation().execStartActivityFromAppTask(context,
4236                    thread.getApplicationThread(), mAppTaskImpl, intent, options);
4237        }
4238
4239        /**
4240         * Modify the {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag in the root
4241         * Intent of this AppTask.
4242         *
4243         * @param exclude If true, {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} will
4244         * be set; otherwise, it will be cleared.
4245         */
4246        public void setExcludeFromRecents(boolean exclude) {
4247            try {
4248                mAppTaskImpl.setExcludeFromRecents(exclude);
4249            } catch (RemoteException e) {
4250                throw e.rethrowFromSystemServer();
4251            }
4252        }
4253    }
4254}
4255