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