ActivityManager.java revision 326be275726047c7e3b3ada5d85a58649b377b81
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. It also revokes all runtime permissions that the app has acquired,
2702     * clears all notifications and removes all Uri grants related to this application.
2703     *
2704     * @return {@code true} if the application successfully requested that the application's
2705     *     data be erased; {@code false} otherwise.
2706     */
2707    public boolean clearApplicationUserData() {
2708        return clearApplicationUserData(mContext.getPackageName(), null);
2709    }
2710
2711
2712    /**
2713     * Permits an application to get the persistent URI permissions granted to another.
2714     *
2715     * <p>Typically called by Settings.
2716     *
2717     * @param packageName application to look for the granted permissions
2718     * @return list of granted URI permissions
2719     *
2720     * @hide
2721     */
2722    public ParceledListSlice<UriPermission> getGrantedUriPermissions(String packageName) {
2723        try {
2724            return getService().getGrantedUriPermissions(packageName,
2725                    UserHandle.myUserId());
2726        } catch (RemoteException e) {
2727            throw e.rethrowFromSystemServer();
2728        }
2729    }
2730
2731    /**
2732     * Permits an application to clear the persistent URI permissions granted to another.
2733     *
2734     * <p>Typically called by Settings.
2735     *
2736     * @param packageName application to clear its granted permissions
2737     *
2738     * @hide
2739     */
2740    public void clearGrantedUriPermissions(String packageName) {
2741        try {
2742            getService().clearGrantedUriPermissions(packageName,
2743                    UserHandle.myUserId());
2744        } catch (RemoteException e) {
2745            throw e.rethrowFromSystemServer();
2746        }
2747    }
2748
2749    /**
2750     * Information you can retrieve about any processes that are in an error condition.
2751     */
2752    public static class ProcessErrorStateInfo implements Parcelable {
2753        /**
2754         * Condition codes
2755         */
2756        public static final int NO_ERROR = 0;
2757        public static final int CRASHED = 1;
2758        public static final int NOT_RESPONDING = 2;
2759
2760        /**
2761         * The condition that the process is in.
2762         */
2763        public int condition;
2764
2765        /**
2766         * The process name in which the crash or error occurred.
2767         */
2768        public String processName;
2769
2770        /**
2771         * The pid of this process; 0 if none
2772         */
2773        public int pid;
2774
2775        /**
2776         * The kernel user-ID that has been assigned to this process;
2777         * currently this is not a unique ID (multiple applications can have
2778         * the same uid).
2779         */
2780        public int uid;
2781
2782        /**
2783         * The activity name associated with the error, if known.  May be null.
2784         */
2785        public String tag;
2786
2787        /**
2788         * A short message describing the error condition.
2789         */
2790        public String shortMsg;
2791
2792        /**
2793         * A long message describing the error condition.
2794         */
2795        public String longMsg;
2796
2797        /**
2798         * The stack trace where the error originated.  May be null.
2799         */
2800        public String stackTrace;
2801
2802        /**
2803         * to be deprecated: This value will always be null.
2804         */
2805        public byte[] crashData = null;
2806
2807        public ProcessErrorStateInfo() {
2808        }
2809
2810        @Override
2811        public int describeContents() {
2812            return 0;
2813        }
2814
2815        @Override
2816        public void writeToParcel(Parcel dest, int flags) {
2817            dest.writeInt(condition);
2818            dest.writeString(processName);
2819            dest.writeInt(pid);
2820            dest.writeInt(uid);
2821            dest.writeString(tag);
2822            dest.writeString(shortMsg);
2823            dest.writeString(longMsg);
2824            dest.writeString(stackTrace);
2825        }
2826
2827        public void readFromParcel(Parcel source) {
2828            condition = source.readInt();
2829            processName = source.readString();
2830            pid = source.readInt();
2831            uid = source.readInt();
2832            tag = source.readString();
2833            shortMsg = source.readString();
2834            longMsg = source.readString();
2835            stackTrace = source.readString();
2836        }
2837
2838        public static final Creator<ProcessErrorStateInfo> CREATOR =
2839                new Creator<ProcessErrorStateInfo>() {
2840            public ProcessErrorStateInfo createFromParcel(Parcel source) {
2841                return new ProcessErrorStateInfo(source);
2842            }
2843            public ProcessErrorStateInfo[] newArray(int size) {
2844                return new ProcessErrorStateInfo[size];
2845            }
2846        };
2847
2848        private ProcessErrorStateInfo(Parcel source) {
2849            readFromParcel(source);
2850        }
2851    }
2852
2853    /**
2854     * Returns a list of any processes that are currently in an error condition.  The result
2855     * will be null if all processes are running properly at this time.
2856     *
2857     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
2858     * current error conditions (it will not return an empty list).  This list ordering is not
2859     * specified.
2860     */
2861    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
2862        try {
2863            return getService().getProcessesInErrorState();
2864        } catch (RemoteException e) {
2865            throw e.rethrowFromSystemServer();
2866        }
2867    }
2868
2869    /**
2870     * Information you can retrieve about a running process.
2871     */
2872    public static class RunningAppProcessInfo implements Parcelable {
2873        /**
2874         * The name of the process that this object is associated with
2875         */
2876        public String processName;
2877
2878        /**
2879         * The pid of this process; 0 if none
2880         */
2881        public int pid;
2882
2883        /**
2884         * The user id of this process.
2885         */
2886        public int uid;
2887
2888        /**
2889         * All packages that have been loaded into the process.
2890         */
2891        public String pkgList[];
2892
2893        /**
2894         * Constant for {@link #flags}: this is an app that is unable to
2895         * correctly save its state when going to the background,
2896         * so it can not be killed while in the background.
2897         * @hide
2898         */
2899        public static final int FLAG_CANT_SAVE_STATE = 1<<0;
2900
2901        /**
2902         * Constant for {@link #flags}: this process is associated with a
2903         * persistent system app.
2904         * @hide
2905         */
2906        public static final int FLAG_PERSISTENT = 1<<1;
2907
2908        /**
2909         * Constant for {@link #flags}: this process is associated with a
2910         * persistent system app.
2911         * @hide
2912         */
2913        public static final int FLAG_HAS_ACTIVITIES = 1<<2;
2914
2915        /**
2916         * Flags of information.  May be any of
2917         * {@link #FLAG_CANT_SAVE_STATE}.
2918         * @hide
2919         */
2920        public int flags;
2921
2922        /**
2923         * Last memory trim level reported to the process: corresponds to
2924         * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
2925         * ComponentCallbacks2.onTrimMemory(int)}.
2926         */
2927        public int lastTrimLevel;
2928
2929        /** @hide */
2930        @IntDef(prefix = { "IMPORTANCE_" }, value = {
2931                IMPORTANCE_FOREGROUND,
2932                IMPORTANCE_FOREGROUND_SERVICE,
2933                IMPORTANCE_TOP_SLEEPING,
2934                IMPORTANCE_VISIBLE,
2935                IMPORTANCE_PERCEPTIBLE,
2936                IMPORTANCE_CANT_SAVE_STATE,
2937                IMPORTANCE_SERVICE,
2938                IMPORTANCE_CACHED,
2939                IMPORTANCE_GONE,
2940        })
2941        @Retention(RetentionPolicy.SOURCE)
2942        public @interface Importance {}
2943
2944        /**
2945         * Constant for {@link #importance}: This process is running the
2946         * foreground UI; that is, it is the thing currently at the top of the screen
2947         * that the user is interacting with.
2948         */
2949        public static final int IMPORTANCE_FOREGROUND = 100;
2950
2951        /**
2952         * Constant for {@link #importance}: This process is running a foreground
2953         * service, for example to perform music playback even while the user is
2954         * not immediately in the app.  This generally indicates that the process
2955         * is doing something the user actively cares about.
2956         */
2957        public static final int IMPORTANCE_FOREGROUND_SERVICE = 125;
2958
2959        /**
2960         * Constant for {@link #importance}: This process is running the foreground
2961         * UI, but the device is asleep so it is not visible to the user.  This means
2962         * the user is not really aware of the process, because they can not see or
2963         * interact with it, but it is quite important because it what they expect to
2964         * return to once unlocking the device.
2965         */
2966        public static final int IMPORTANCE_TOP_SLEEPING = 150;
2967
2968        /**
2969         * Constant for {@link #importance}: This process is running something
2970         * that is actively visible to the user, though not in the immediate
2971         * foreground.  This may be running a window that is behind the current
2972         * foreground (so paused and with its state saved, not interacting with
2973         * the user, but visible to them to some degree); it may also be running
2974         * other services under the system's control that it inconsiders important.
2975         */
2976        public static final int IMPORTANCE_VISIBLE = 200;
2977
2978        /**
2979         * Constant for {@link #importance}: {@link #IMPORTANCE_PERCEPTIBLE} had this wrong value
2980         * before {@link Build.VERSION_CODES#O}.  Since the {@link Build.VERSION_CODES#O} SDK,
2981         * the value of {@link #IMPORTANCE_PERCEPTIBLE} has been fixed.
2982         *
2983         * <p>The system will return this value instead of {@link #IMPORTANCE_PERCEPTIBLE}
2984         * on Android versions below {@link Build.VERSION_CODES#O}.
2985         *
2986         * <p>On Android version {@link Build.VERSION_CODES#O} and later, this value will still be
2987         * returned for apps with the target API level below {@link Build.VERSION_CODES#O}.
2988         * For apps targeting version {@link Build.VERSION_CODES#O} and later,
2989         * the correct value {@link #IMPORTANCE_PERCEPTIBLE} will be returned.
2990         */
2991        public static final int IMPORTANCE_PERCEPTIBLE_PRE_26 = 130;
2992
2993        /**
2994         * Constant for {@link #importance}: This process is not something the user
2995         * is directly aware of, but is otherwise perceptible to them to some degree.
2996         */
2997        public static final int IMPORTANCE_PERCEPTIBLE = 230;
2998
2999        /**
3000         * Constant for {@link #importance}: {@link #IMPORTANCE_CANT_SAVE_STATE} had
3001         * this wrong value
3002         * before {@link Build.VERSION_CODES#O}.  Since the {@link Build.VERSION_CODES#O} SDK,
3003         * the value of {@link #IMPORTANCE_CANT_SAVE_STATE} has been fixed.
3004         *
3005         * <p>The system will return this value instead of {@link #IMPORTANCE_CANT_SAVE_STATE}
3006         * on Android versions below {@link Build.VERSION_CODES#O}.
3007         *
3008         * <p>On Android version {@link Build.VERSION_CODES#O} after, this value will still be
3009         * returned for apps with the target API level below {@link Build.VERSION_CODES#O}.
3010         * For apps targeting version {@link Build.VERSION_CODES#O} and later,
3011         * the correct value {@link #IMPORTANCE_CANT_SAVE_STATE} will be returned.
3012         *
3013         * @hide
3014         */
3015        public static final int IMPORTANCE_CANT_SAVE_STATE_PRE_26 = 170;
3016
3017        /**
3018         * Constant for {@link #importance}: This process is running an
3019         * application that can not save its state, and thus can't be killed
3020         * while in the background.
3021         * @hide
3022         */
3023        public static final int IMPORTANCE_CANT_SAVE_STATE= 270;
3024
3025        /**
3026         * Constant for {@link #importance}: This process is contains services
3027         * that should remain running.  These are background services apps have
3028         * started, not something the user is aware of, so they may be killed by
3029         * the system relatively freely (though it is generally desired that they
3030         * stay running as long as they want to).
3031         */
3032        public static final int IMPORTANCE_SERVICE = 300;
3033
3034        /**
3035         * Constant for {@link #importance}: This process process contains
3036         * cached code that is expendable, not actively running any app components
3037         * we care about.
3038         */
3039        public static final int IMPORTANCE_CACHED = 400;
3040
3041        /**
3042         * @deprecated Renamed to {@link #IMPORTANCE_CACHED}.
3043         */
3044        public static final int IMPORTANCE_BACKGROUND = IMPORTANCE_CACHED;
3045
3046        /**
3047         * Constant for {@link #importance}: This process is empty of any
3048         * actively running code.
3049         * @deprecated This value is no longer reported, use {@link #IMPORTANCE_CACHED} instead.
3050         */
3051        @Deprecated
3052        public static final int IMPORTANCE_EMPTY = 500;
3053
3054        /**
3055         * Constant for {@link #importance}: This process does not exist.
3056         */
3057        public static final int IMPORTANCE_GONE = 1000;
3058
3059        /**
3060         * Convert a proc state to the correspondent IMPORTANCE_* constant.  If the return value
3061         * will be passed to a client, use {@link #procStateToImportanceForClient}.
3062         * @hide
3063         */
3064        public static @Importance int procStateToImportance(int procState) {
3065            if (procState == PROCESS_STATE_NONEXISTENT) {
3066                return IMPORTANCE_GONE;
3067            } else if (procState >= PROCESS_STATE_HOME) {
3068                return IMPORTANCE_CACHED;
3069            } else if (procState >= PROCESS_STATE_SERVICE) {
3070                return IMPORTANCE_SERVICE;
3071            } else if (procState > PROCESS_STATE_HEAVY_WEIGHT) {
3072                return IMPORTANCE_CANT_SAVE_STATE;
3073            } else if (procState >= PROCESS_STATE_TRANSIENT_BACKGROUND) {
3074                return IMPORTANCE_PERCEPTIBLE;
3075            } else if (procState >= PROCESS_STATE_IMPORTANT_FOREGROUND) {
3076                return IMPORTANCE_VISIBLE;
3077            } else if (procState >= PROCESS_STATE_TOP_SLEEPING) {
3078                return IMPORTANCE_TOP_SLEEPING;
3079            } else if (procState >= PROCESS_STATE_FOREGROUND_SERVICE) {
3080                return IMPORTANCE_FOREGROUND_SERVICE;
3081            } else {
3082                return IMPORTANCE_FOREGROUND;
3083            }
3084        }
3085
3086        /**
3087         * Convert a proc state to the correspondent IMPORTANCE_* constant for a client represented
3088         * by a given {@link Context}, with converting {@link #IMPORTANCE_PERCEPTIBLE}
3089         * and {@link #IMPORTANCE_CANT_SAVE_STATE} to the corresponding "wrong" value if the
3090         * client's target SDK < {@link VERSION_CODES#O}.
3091         * @hide
3092         */
3093        public static @Importance int procStateToImportanceForClient(int procState,
3094                Context clientContext) {
3095            return procStateToImportanceForTargetSdk(procState,
3096                    clientContext.getApplicationInfo().targetSdkVersion);
3097        }
3098
3099        /**
3100         * See {@link #procStateToImportanceForClient}.
3101         * @hide
3102         */
3103        public static @Importance int procStateToImportanceForTargetSdk(int procState,
3104                int targetSdkVersion) {
3105            final int importance = procStateToImportance(procState);
3106
3107            // For pre O apps, convert to the old, wrong values.
3108            if (targetSdkVersion < VERSION_CODES.O) {
3109                switch (importance) {
3110                    case IMPORTANCE_PERCEPTIBLE:
3111                        return IMPORTANCE_PERCEPTIBLE_PRE_26;
3112                    case IMPORTANCE_CANT_SAVE_STATE:
3113                        return IMPORTANCE_CANT_SAVE_STATE_PRE_26;
3114                }
3115            }
3116            return importance;
3117        }
3118
3119        /** @hide */
3120        public static int importanceToProcState(@Importance int importance) {
3121            if (importance == IMPORTANCE_GONE) {
3122                return PROCESS_STATE_NONEXISTENT;
3123            } else if (importance >= IMPORTANCE_CACHED) {
3124                return PROCESS_STATE_HOME;
3125            } else if (importance >= IMPORTANCE_SERVICE) {
3126                return PROCESS_STATE_SERVICE;
3127            } else if (importance > IMPORTANCE_CANT_SAVE_STATE) {
3128                return PROCESS_STATE_HEAVY_WEIGHT;
3129            } else if (importance >= IMPORTANCE_PERCEPTIBLE) {
3130                return PROCESS_STATE_TRANSIENT_BACKGROUND;
3131            } else if (importance >= IMPORTANCE_VISIBLE) {
3132                return PROCESS_STATE_IMPORTANT_FOREGROUND;
3133            } else if (importance >= IMPORTANCE_TOP_SLEEPING) {
3134                return PROCESS_STATE_TOP_SLEEPING;
3135            } else if (importance >= IMPORTANCE_FOREGROUND_SERVICE) {
3136                return PROCESS_STATE_FOREGROUND_SERVICE;
3137            } else {
3138                return PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
3139            }
3140        }
3141
3142        /**
3143         * The relative importance level that the system places on this process.
3144         * These constants are numbered so that "more important" values are
3145         * always smaller than "less important" values.
3146         */
3147        public @Importance int importance;
3148
3149        /**
3150         * An additional ordering within a particular {@link #importance}
3151         * category, providing finer-grained information about the relative
3152         * utility of processes within a category.  This number means nothing
3153         * except that a smaller values are more recently used (and thus
3154         * more important).  Currently an LRU value is only maintained for
3155         * the {@link #IMPORTANCE_CACHED} category, though others may
3156         * be maintained in the future.
3157         */
3158        public int lru;
3159
3160        /**
3161         * Constant for {@link #importanceReasonCode}: nothing special has
3162         * been specified for the reason for this level.
3163         */
3164        public static final int REASON_UNKNOWN = 0;
3165
3166        /**
3167         * Constant for {@link #importanceReasonCode}: one of the application's
3168         * content providers is being used by another process.  The pid of
3169         * the client process is in {@link #importanceReasonPid} and the
3170         * target provider in this process is in
3171         * {@link #importanceReasonComponent}.
3172         */
3173        public static final int REASON_PROVIDER_IN_USE = 1;
3174
3175        /**
3176         * Constant for {@link #importanceReasonCode}: one of the application's
3177         * content providers is being used by another process.  The pid of
3178         * the client process is in {@link #importanceReasonPid} and the
3179         * target provider in this process is in
3180         * {@link #importanceReasonComponent}.
3181         */
3182        public static final int REASON_SERVICE_IN_USE = 2;
3183
3184        /**
3185         * The reason for {@link #importance}, if any.
3186         */
3187        public int importanceReasonCode;
3188
3189        /**
3190         * For the specified values of {@link #importanceReasonCode}, this
3191         * is the process ID of the other process that is a client of this
3192         * process.  This will be 0 if no other process is using this one.
3193         */
3194        public int importanceReasonPid;
3195
3196        /**
3197         * For the specified values of {@link #importanceReasonCode}, this
3198         * is the name of the component that is being used in this process.
3199         */
3200        public ComponentName importanceReasonComponent;
3201
3202        /**
3203         * When {@link #importanceReasonPid} is non-0, this is the importance
3204         * of the other pid. @hide
3205         */
3206        public int importanceReasonImportance;
3207
3208        /**
3209         * Current process state, as per PROCESS_STATE_* constants.
3210         * @hide
3211         */
3212        public int processState;
3213
3214        public RunningAppProcessInfo() {
3215            importance = IMPORTANCE_FOREGROUND;
3216            importanceReasonCode = REASON_UNKNOWN;
3217            processState = PROCESS_STATE_IMPORTANT_FOREGROUND;
3218        }
3219
3220        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
3221            processName = pProcessName;
3222            pid = pPid;
3223            pkgList = pArr;
3224        }
3225
3226        public int describeContents() {
3227            return 0;
3228        }
3229
3230        public void writeToParcel(Parcel dest, int flags) {
3231            dest.writeString(processName);
3232            dest.writeInt(pid);
3233            dest.writeInt(uid);
3234            dest.writeStringArray(pkgList);
3235            dest.writeInt(this.flags);
3236            dest.writeInt(lastTrimLevel);
3237            dest.writeInt(importance);
3238            dest.writeInt(lru);
3239            dest.writeInt(importanceReasonCode);
3240            dest.writeInt(importanceReasonPid);
3241            ComponentName.writeToParcel(importanceReasonComponent, dest);
3242            dest.writeInt(importanceReasonImportance);
3243            dest.writeInt(processState);
3244        }
3245
3246        public void readFromParcel(Parcel source) {
3247            processName = source.readString();
3248            pid = source.readInt();
3249            uid = source.readInt();
3250            pkgList = source.readStringArray();
3251            flags = source.readInt();
3252            lastTrimLevel = source.readInt();
3253            importance = source.readInt();
3254            lru = source.readInt();
3255            importanceReasonCode = source.readInt();
3256            importanceReasonPid = source.readInt();
3257            importanceReasonComponent = ComponentName.readFromParcel(source);
3258            importanceReasonImportance = source.readInt();
3259            processState = source.readInt();
3260        }
3261
3262        public static final Creator<RunningAppProcessInfo> CREATOR =
3263            new Creator<RunningAppProcessInfo>() {
3264            public RunningAppProcessInfo createFromParcel(Parcel source) {
3265                return new RunningAppProcessInfo(source);
3266            }
3267            public RunningAppProcessInfo[] newArray(int size) {
3268                return new RunningAppProcessInfo[size];
3269            }
3270        };
3271
3272        private RunningAppProcessInfo(Parcel source) {
3273            readFromParcel(source);
3274        }
3275    }
3276
3277    /**
3278     * Returns a list of application processes installed on external media
3279     * that are running on the device.
3280     *
3281     * <p><b>Note: this method is only intended for debugging or building
3282     * a user-facing process management UI.</b></p>
3283     *
3284     * @return Returns a list of ApplicationInfo records, or null if none
3285     * This list ordering is not specified.
3286     * @hide
3287     */
3288    public List<ApplicationInfo> getRunningExternalApplications() {
3289        try {
3290            return getService().getRunningExternalApplications();
3291        } catch (RemoteException e) {
3292            throw e.rethrowFromSystemServer();
3293        }
3294    }
3295
3296    /**
3297     * Sets the memory trim mode for a process and schedules a memory trim operation.
3298     *
3299     * <p><b>Note: this method is only intended for testing framework.</b></p>
3300     *
3301     * @return Returns true if successful.
3302     * @hide
3303     */
3304    public boolean setProcessMemoryTrimLevel(String process, int userId, int level) {
3305        try {
3306            return getService().setProcessMemoryTrimLevel(process, userId,
3307                    level);
3308        } catch (RemoteException e) {
3309            throw e.rethrowFromSystemServer();
3310        }
3311    }
3312
3313    /**
3314     * Returns a list of application processes that are running on the device.
3315     *
3316     * <p><b>Note: this method is only intended for debugging or building
3317     * a user-facing process management UI.</b></p>
3318     *
3319     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
3320     * running processes (it will not return an empty list).  This list ordering is not
3321     * specified.
3322     */
3323    public List<RunningAppProcessInfo> getRunningAppProcesses() {
3324        try {
3325            return getService().getRunningAppProcesses();
3326        } catch (RemoteException e) {
3327            throw e.rethrowFromSystemServer();
3328        }
3329    }
3330
3331    /**
3332     * Return the importance of a given package name, based on the processes that are
3333     * currently running.  The return value is one of the importance constants defined
3334     * in {@link RunningAppProcessInfo}, giving you the highest importance of all the
3335     * processes that this package has code running inside of.  If there are no processes
3336     * running its code, {@link RunningAppProcessInfo#IMPORTANCE_GONE} is returned.
3337     * @hide
3338     */
3339    @SystemApi @TestApi
3340    @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3341    public @RunningAppProcessInfo.Importance int getPackageImportance(String packageName) {
3342        try {
3343            int procState = getService().getPackageProcessState(packageName,
3344                    mContext.getOpPackageName());
3345            return RunningAppProcessInfo.procStateToImportanceForClient(procState, mContext);
3346        } catch (RemoteException e) {
3347            throw e.rethrowFromSystemServer();
3348        }
3349    }
3350
3351    /**
3352     * Return the importance of a given uid, based on the processes that are
3353     * currently running.  The return value is one of the importance constants defined
3354     * in {@link RunningAppProcessInfo}, giving you the highest importance of all the
3355     * processes that this uid has running.  If there are no processes
3356     * running its code, {@link RunningAppProcessInfo#IMPORTANCE_GONE} is returned.
3357     * @hide
3358     */
3359    @SystemApi @TestApi
3360    @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3361    public @RunningAppProcessInfo.Importance int getUidImportance(int uid) {
3362        try {
3363            int procState = getService().getUidProcessState(uid,
3364                    mContext.getOpPackageName());
3365            return RunningAppProcessInfo.procStateToImportanceForClient(procState, mContext);
3366        } catch (RemoteException e) {
3367            throw e.rethrowFromSystemServer();
3368        }
3369    }
3370
3371    /**
3372     * Callback to get reports about changes to the importance of a uid.  Use with
3373     * {@link #addOnUidImportanceListener}.
3374     * @hide
3375     */
3376    @SystemApi @TestApi
3377    public interface OnUidImportanceListener {
3378        /**
3379         * The importance if a given uid has changed.  Will be one of the importance
3380         * values in {@link RunningAppProcessInfo};
3381         * {@link RunningAppProcessInfo#IMPORTANCE_GONE IMPORTANCE_GONE} will be reported
3382         * when the uid is no longer running at all.  This callback will happen on a thread
3383         * from a thread pool, not the main UI thread.
3384         * @param uid The uid whose importance has changed.
3385         * @param importance The new importance value as per {@link RunningAppProcessInfo}.
3386         */
3387        void onUidImportance(int uid, @RunningAppProcessInfo.Importance int importance);
3388    }
3389
3390    /**
3391     * Start monitoring changes to the imoportance of uids running in the system.
3392     * @param listener The listener callback that will receive change reports.
3393     * @param importanceCutpoint The level of importance in which the caller is interested
3394     * in differences.  For example, if {@link RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE}
3395     * is used here, you will receive a call each time a uids importance transitions between
3396     * being <= {@link RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE} and
3397     * > {@link RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE}.
3398     *
3399     * <p>The caller must hold the {@link android.Manifest.permission#PACKAGE_USAGE_STATS}
3400     * permission to use this feature.</p>
3401     *
3402     * @throws IllegalArgumentException If the listener is already registered.
3403     * @throws SecurityException If the caller does not hold
3404     * {@link android.Manifest.permission#PACKAGE_USAGE_STATS}.
3405     * @hide
3406     */
3407    @SystemApi @TestApi
3408    @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3409    public void addOnUidImportanceListener(OnUidImportanceListener listener,
3410            @RunningAppProcessInfo.Importance int importanceCutpoint) {
3411        synchronized (this) {
3412            if (mImportanceListeners.containsKey(listener)) {
3413                throw new IllegalArgumentException("Listener already registered: " + listener);
3414            }
3415            // TODO: implement the cut point in the system process to avoid IPCs.
3416            UidObserver observer = new UidObserver(listener, mContext);
3417            try {
3418                getService().registerUidObserver(observer,
3419                        UID_OBSERVER_PROCSTATE | UID_OBSERVER_GONE,
3420                        RunningAppProcessInfo.importanceToProcState(importanceCutpoint),
3421                        mContext.getOpPackageName());
3422            } catch (RemoteException e) {
3423                throw e.rethrowFromSystemServer();
3424            }
3425            mImportanceListeners.put(listener, observer);
3426        }
3427    }
3428
3429    /**
3430     * Remove an importance listener that was previously registered with
3431     * {@link #addOnUidImportanceListener}.
3432     *
3433     * @throws IllegalArgumentException If the listener is not registered.
3434     * @hide
3435     */
3436    @SystemApi @TestApi
3437    @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3438    public void removeOnUidImportanceListener(OnUidImportanceListener listener) {
3439        synchronized (this) {
3440            UidObserver observer = mImportanceListeners.remove(listener);
3441            if (observer == null) {
3442                throw new IllegalArgumentException("Listener not registered: " + listener);
3443            }
3444            try {
3445                getService().unregisterUidObserver(observer);
3446            } catch (RemoteException e) {
3447                throw e.rethrowFromSystemServer();
3448            }
3449        }
3450    }
3451
3452    /**
3453     * Return global memory state information for the calling process.  This
3454     * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
3455     * only fields that will be filled in are
3456     * {@link RunningAppProcessInfo#pid},
3457     * {@link RunningAppProcessInfo#uid},
3458     * {@link RunningAppProcessInfo#lastTrimLevel},
3459     * {@link RunningAppProcessInfo#importance},
3460     * {@link RunningAppProcessInfo#lru}, and
3461     * {@link RunningAppProcessInfo#importanceReasonCode}.
3462     */
3463    static public void getMyMemoryState(RunningAppProcessInfo outState) {
3464        try {
3465            getService().getMyMemoryState(outState);
3466        } catch (RemoteException e) {
3467            throw e.rethrowFromSystemServer();
3468        }
3469    }
3470
3471    /**
3472     * Return information about the memory usage of one or more processes.
3473     *
3474     * <p><b>Note: this method is only intended for debugging or building
3475     * a user-facing process management UI.</b></p>
3476     *
3477     * @param pids The pids of the processes whose memory usage is to be
3478     * retrieved.
3479     * @return Returns an array of memory information, one for each
3480     * requested pid.
3481     */
3482    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
3483        try {
3484            return getService().getProcessMemoryInfo(pids);
3485        } catch (RemoteException e) {
3486            throw e.rethrowFromSystemServer();
3487        }
3488    }
3489
3490    /**
3491     * @deprecated This is now just a wrapper for
3492     * {@link #killBackgroundProcesses(String)}; the previous behavior here
3493     * is no longer available to applications because it allows them to
3494     * break other applications by removing their alarms, stopping their
3495     * services, etc.
3496     */
3497    @Deprecated
3498    public void restartPackage(String packageName) {
3499        killBackgroundProcesses(packageName);
3500    }
3501
3502    /**
3503     * Have the system immediately kill all background processes associated
3504     * with the given package.  This is the same as the kernel killing those
3505     * processes to reclaim memory; the system will take care of restarting
3506     * these processes in the future as needed.
3507     *
3508     * @param packageName The name of the package whose processes are to
3509     * be killed.
3510     */
3511    @RequiresPermission(Manifest.permission.KILL_BACKGROUND_PROCESSES)
3512    public void killBackgroundProcesses(String packageName) {
3513        try {
3514            getService().killBackgroundProcesses(packageName,
3515                    UserHandle.myUserId());
3516        } catch (RemoteException e) {
3517            throw e.rethrowFromSystemServer();
3518        }
3519    }
3520
3521    /**
3522     * Kills the specified UID.
3523     * @param uid The UID to kill.
3524     * @param reason The reason for the kill.
3525     *
3526     * @hide
3527     */
3528    @SystemApi
3529    @RequiresPermission(Manifest.permission.KILL_UID)
3530    public void killUid(int uid, String reason) {
3531        try {
3532            getService().killUid(UserHandle.getAppId(uid),
3533                    UserHandle.getUserId(uid), reason);
3534        } catch (RemoteException e) {
3535            throw e.rethrowFromSystemServer();
3536        }
3537    }
3538
3539    /**
3540     * Have the system perform a force stop of everything associated with
3541     * the given application package.  All processes that share its uid
3542     * will be killed, all services it has running stopped, all activities
3543     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
3544     * broadcast will be sent, so that any of its registered alarms can
3545     * be stopped, notifications removed, etc.
3546     *
3547     * <p>You must hold the permission
3548     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
3549     * call this method.
3550     *
3551     * @param packageName The name of the package to be stopped.
3552     * @param userId The user for which the running package is to be stopped.
3553     *
3554     * @hide This is not available to third party applications due to
3555     * it allowing them to break other applications by stopping their
3556     * services, removing their alarms, etc.
3557     */
3558    public void forceStopPackageAsUser(String packageName, int userId) {
3559        try {
3560            getService().forceStopPackage(packageName, userId);
3561        } catch (RemoteException e) {
3562            throw e.rethrowFromSystemServer();
3563        }
3564    }
3565
3566    /**
3567     * @see #forceStopPackageAsUser(String, int)
3568     * @hide
3569     */
3570    @SystemApi
3571    @RequiresPermission(Manifest.permission.FORCE_STOP_PACKAGES)
3572    public void forceStopPackage(String packageName) {
3573        forceStopPackageAsUser(packageName, UserHandle.myUserId());
3574    }
3575
3576    /**
3577     * Get the device configuration attributes.
3578     */
3579    public ConfigurationInfo getDeviceConfigurationInfo() {
3580        try {
3581            return getService().getDeviceConfigurationInfo();
3582        } catch (RemoteException e) {
3583            throw e.rethrowFromSystemServer();
3584        }
3585    }
3586
3587    /**
3588     * Get the preferred density of icons for the launcher. This is used when
3589     * custom drawables are created (e.g., for shortcuts).
3590     *
3591     * @return density in terms of DPI
3592     */
3593    public int getLauncherLargeIconDensity() {
3594        final Resources res = mContext.getResources();
3595        final int density = res.getDisplayMetrics().densityDpi;
3596        final int sw = res.getConfiguration().smallestScreenWidthDp;
3597
3598        if (sw < 600) {
3599            // Smaller than approx 7" tablets, use the regular icon size.
3600            return density;
3601        }
3602
3603        switch (density) {
3604            case DisplayMetrics.DENSITY_LOW:
3605                return DisplayMetrics.DENSITY_MEDIUM;
3606            case DisplayMetrics.DENSITY_MEDIUM:
3607                return DisplayMetrics.DENSITY_HIGH;
3608            case DisplayMetrics.DENSITY_TV:
3609                return DisplayMetrics.DENSITY_XHIGH;
3610            case DisplayMetrics.DENSITY_HIGH:
3611                return DisplayMetrics.DENSITY_XHIGH;
3612            case DisplayMetrics.DENSITY_XHIGH:
3613                return DisplayMetrics.DENSITY_XXHIGH;
3614            case DisplayMetrics.DENSITY_XXHIGH:
3615                return DisplayMetrics.DENSITY_XHIGH * 2;
3616            default:
3617                // The density is some abnormal value.  Return some other
3618                // abnormal value that is a reasonable scaling of it.
3619                return (int)((density*1.5f)+.5f);
3620        }
3621    }
3622
3623    /**
3624     * Get the preferred launcher icon size. This is used when custom drawables
3625     * are created (e.g., for shortcuts).
3626     *
3627     * @return dimensions of square icons in terms of pixels
3628     */
3629    public int getLauncherLargeIconSize() {
3630        return getLauncherLargeIconSizeInner(mContext);
3631    }
3632
3633    static int getLauncherLargeIconSizeInner(Context context) {
3634        final Resources res = context.getResources();
3635        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
3636        final int sw = res.getConfiguration().smallestScreenWidthDp;
3637
3638        if (sw < 600) {
3639            // Smaller than approx 7" tablets, use the regular icon size.
3640            return size;
3641        }
3642
3643        final int density = res.getDisplayMetrics().densityDpi;
3644
3645        switch (density) {
3646            case DisplayMetrics.DENSITY_LOW:
3647                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
3648            case DisplayMetrics.DENSITY_MEDIUM:
3649                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
3650            case DisplayMetrics.DENSITY_TV:
3651                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
3652            case DisplayMetrics.DENSITY_HIGH:
3653                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
3654            case DisplayMetrics.DENSITY_XHIGH:
3655                return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
3656            case DisplayMetrics.DENSITY_XXHIGH:
3657                return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
3658            default:
3659                // The density is some abnormal value.  Return some other
3660                // abnormal value that is a reasonable scaling of it.
3661                return (int)((size*1.5f) + .5f);
3662        }
3663    }
3664
3665    /**
3666     * Returns "true" if the user interface is currently being messed with
3667     * by a monkey.
3668     */
3669    public static boolean isUserAMonkey() {
3670        try {
3671            return getService().isUserAMonkey();
3672        } catch (RemoteException e) {
3673            throw e.rethrowFromSystemServer();
3674        }
3675    }
3676
3677    /**
3678     * Returns "true" if device is running in a test harness.
3679     */
3680    public static boolean isRunningInTestHarness() {
3681        return SystemProperties.getBoolean("ro.test_harness", false);
3682    }
3683
3684    /**
3685     * Returns the launch count of each installed package.
3686     *
3687     * @hide
3688     */
3689    /*public Map<String, Integer> getAllPackageLaunchCounts() {
3690        try {
3691            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
3692                    ServiceManager.getService("usagestats"));
3693            if (usageStatsService == null) {
3694                return new HashMap<String, Integer>();
3695            }
3696
3697            UsageStats.PackageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats(
3698                    ActivityThread.currentPackageName());
3699            if (allPkgUsageStats == null) {
3700                return new HashMap<String, Integer>();
3701            }
3702
3703            Map<String, Integer> launchCounts = new HashMap<String, Integer>();
3704            for (UsageStats.PackageStats pkgUsageStats : allPkgUsageStats) {
3705                launchCounts.put(pkgUsageStats.getPackageName(), pkgUsageStats.getLaunchCount());
3706            }
3707
3708            return launchCounts;
3709        } catch (RemoteException e) {
3710            Log.w(TAG, "Could not query launch counts", e);
3711            return new HashMap<String, Integer>();
3712        }
3713    }*/
3714
3715    /** @hide */
3716    public static int checkComponentPermission(String permission, int uid,
3717            int owningUid, boolean exported) {
3718        // Root, system server get to do everything.
3719        final int appId = UserHandle.getAppId(uid);
3720        if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
3721            return PackageManager.PERMISSION_GRANTED;
3722        }
3723        // Isolated processes don't get any permissions.
3724        if (UserHandle.isIsolated(uid)) {
3725            return PackageManager.PERMISSION_DENIED;
3726        }
3727        // If there is a uid that owns whatever is being accessed, it has
3728        // blanket access to it regardless of the permissions it requires.
3729        if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
3730            return PackageManager.PERMISSION_GRANTED;
3731        }
3732        // If the target is not exported, then nobody else can get to it.
3733        if (!exported) {
3734            /*
3735            RuntimeException here = new RuntimeException("here");
3736            here.fillInStackTrace();
3737            Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
3738                    here);
3739            */
3740            return PackageManager.PERMISSION_DENIED;
3741        }
3742        if (permission == null) {
3743            return PackageManager.PERMISSION_GRANTED;
3744        }
3745        try {
3746            return AppGlobals.getPackageManager()
3747                    .checkUidPermission(permission, uid);
3748        } catch (RemoteException e) {
3749            throw e.rethrowFromSystemServer();
3750        }
3751    }
3752
3753    /** @hide */
3754    public static int checkUidPermission(String permission, int uid) {
3755        try {
3756            return AppGlobals.getPackageManager()
3757                    .checkUidPermission(permission, uid);
3758        } catch (RemoteException e) {
3759            throw e.rethrowFromSystemServer();
3760        }
3761    }
3762
3763    /**
3764     * @hide
3765     * Helper for dealing with incoming user arguments to system service calls.
3766     * Takes care of checking permissions and converting USER_CURRENT to the
3767     * actual current user.
3768     *
3769     * @param callingPid The pid of the incoming call, as per Binder.getCallingPid().
3770     * @param callingUid The uid of the incoming call, as per Binder.getCallingUid().
3771     * @param userId The user id argument supplied by the caller -- this is the user
3772     * they want to run as.
3773     * @param allowAll If true, we will allow USER_ALL.  This means you must be prepared
3774     * to get a USER_ALL returned and deal with it correctly.  If false,
3775     * an exception will be thrown if USER_ALL is supplied.
3776     * @param requireFull If true, the caller must hold
3777     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a
3778     * different user than their current process; otherwise they must hold
3779     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
3780     * @param name Optional textual name of the incoming call; only for generating error messages.
3781     * @param callerPackage Optional package name of caller; only for error messages.
3782     *
3783     * @return Returns the user ID that the call should run as.  Will always be a concrete
3784     * user number, unless <var>allowAll</var> is true in which case it could also be
3785     * USER_ALL.
3786     */
3787    public static int handleIncomingUser(int callingPid, int callingUid, int userId,
3788            boolean allowAll, boolean requireFull, String name, String callerPackage) {
3789        if (UserHandle.getUserId(callingUid) == userId) {
3790            return userId;
3791        }
3792        try {
3793            return getService().handleIncomingUser(callingPid,
3794                    callingUid, userId, allowAll, requireFull, name, callerPackage);
3795        } catch (RemoteException e) {
3796            throw e.rethrowFromSystemServer();
3797        }
3798    }
3799
3800    /**
3801     * Gets the userId of the current foreground user. Requires system permissions.
3802     * @hide
3803     */
3804    @SystemApi
3805    @RequiresPermission(anyOf = {
3806            "android.permission.INTERACT_ACROSS_USERS",
3807            "android.permission.INTERACT_ACROSS_USERS_FULL"
3808    })
3809    public static int getCurrentUser() {
3810        UserInfo ui;
3811        try {
3812            ui = getService().getCurrentUser();
3813            return ui != null ? ui.id : 0;
3814        } catch (RemoteException e) {
3815            throw e.rethrowFromSystemServer();
3816        }
3817    }
3818
3819    /**
3820     * @param userid the user's id. Zero indicates the default user.
3821     * @hide
3822     */
3823    public boolean switchUser(int userid) {
3824        try {
3825            return getService().switchUser(userid);
3826        } catch (RemoteException e) {
3827            throw e.rethrowFromSystemServer();
3828        }
3829    }
3830
3831    /**
3832     * Logs out current current foreground user by switching to the system user and stopping the
3833     * user being switched from.
3834     * @hide
3835     */
3836    public static void logoutCurrentUser() {
3837        int currentUser = ActivityManager.getCurrentUser();
3838        if (currentUser != UserHandle.USER_SYSTEM) {
3839            try {
3840                getService().switchUser(UserHandle.USER_SYSTEM);
3841                getService().stopUser(currentUser, /* force= */ false, null);
3842            } catch (RemoteException e) {
3843                e.rethrowFromSystemServer();
3844            }
3845        }
3846    }
3847
3848    /** {@hide} */
3849    public static final int FLAG_OR_STOPPED = 1 << 0;
3850    /** {@hide} */
3851    public static final int FLAG_AND_LOCKED = 1 << 1;
3852    /** {@hide} */
3853    public static final int FLAG_AND_UNLOCKED = 1 << 2;
3854    /** {@hide} */
3855    public static final int FLAG_AND_UNLOCKING_OR_UNLOCKED = 1 << 3;
3856
3857    /**
3858     * Return whether the given user is actively running.  This means that
3859     * the user is in the "started" state, not "stopped" -- it is currently
3860     * allowed to run code through scheduled alarms, receiving broadcasts,
3861     * etc.  A started user may be either the current foreground user or a
3862     * background user; the result here does not distinguish between the two.
3863     * @param userId the user's id. Zero indicates the default user.
3864     * @hide
3865     */
3866    public boolean isUserRunning(int userId) {
3867        try {
3868            return getService().isUserRunning(userId, 0);
3869        } catch (RemoteException e) {
3870            throw e.rethrowFromSystemServer();
3871        }
3872    }
3873
3874    /** {@hide} */
3875    public boolean isVrModePackageEnabled(ComponentName component) {
3876        try {
3877            return getService().isVrModePackageEnabled(component);
3878        } catch (RemoteException e) {
3879            throw e.rethrowFromSystemServer();
3880        }
3881    }
3882
3883    /**
3884     * Perform a system dump of various state associated with the given application
3885     * package name.  This call blocks while the dump is being performed, so should
3886     * not be done on a UI thread.  The data will be written to the given file
3887     * descriptor as text.
3888     * @param fd The file descriptor that the dump should be written to.  The file
3889     * descriptor is <em>not</em> closed by this function; the caller continues to
3890     * own it.
3891     * @param packageName The name of the package that is to be dumped.
3892     */
3893    @RequiresPermission(Manifest.permission.DUMP)
3894    public void dumpPackageState(FileDescriptor fd, String packageName) {
3895        dumpPackageStateStatic(fd, packageName);
3896    }
3897
3898    /**
3899     * @hide
3900     */
3901    public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) {
3902        FileOutputStream fout = new FileOutputStream(fd);
3903        PrintWriter pw = new FastPrintWriter(fout);
3904        dumpService(pw, fd, "package", new String[] { packageName });
3905        pw.println();
3906        dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] {
3907                "-a", "package", packageName });
3908        pw.println();
3909        dumpService(pw, fd, "meminfo", new String[] { "--local", "--package", packageName });
3910        pw.println();
3911        dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { packageName });
3912        pw.println();
3913        dumpService(pw, fd, "usagestats", new String[] { "--packages", packageName });
3914        pw.println();
3915        dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName });
3916        pw.flush();
3917    }
3918
3919    /**
3920     * @hide
3921     */
3922    public static boolean isSystemReady() {
3923        if (!sSystemReady) {
3924            if (ActivityThread.isSystem()) {
3925                sSystemReady =
3926                        LocalServices.getService(ActivityManagerInternal.class).isSystemReady();
3927            } else {
3928                // Since this is being called from outside system server, system should be
3929                // ready by now.
3930                sSystemReady = true;
3931            }
3932        }
3933        return sSystemReady;
3934    }
3935
3936    /**
3937     * @hide
3938     */
3939    public static void broadcastStickyIntent(Intent intent, int userId) {
3940        broadcastStickyIntent(intent, AppOpsManager.OP_NONE, userId);
3941    }
3942
3943    /**
3944     * Convenience for sending a sticky broadcast.  For internal use only.
3945     *
3946     * @hide
3947     */
3948    public static void broadcastStickyIntent(Intent intent, int appOp, int userId) {
3949        try {
3950            getService().broadcastIntent(
3951                    null, intent, null, null, Activity.RESULT_OK, null, null,
3952                    null /*permission*/, appOp, null, false, true, userId);
3953        } catch (RemoteException ex) {
3954        }
3955    }
3956
3957    /**
3958     * @hide
3959     */
3960    public static void noteWakeupAlarm(PendingIntent ps, int sourceUid, String sourcePkg,
3961            String tag) {
3962        try {
3963            getService().noteWakeupAlarm((ps != null) ? ps.getTarget() : null,
3964                    sourceUid, sourcePkg, tag);
3965        } catch (RemoteException ex) {
3966        }
3967    }
3968
3969    /**
3970     * @hide
3971     */
3972    public static void noteAlarmStart(PendingIntent ps, int sourceUid, String tag) {
3973        try {
3974            getService().noteAlarmStart((ps != null) ? ps.getTarget() : null, sourceUid, tag);
3975        } catch (RemoteException ex) {
3976        }
3977    }
3978
3979    /**
3980     * @hide
3981     */
3982    public static void noteAlarmFinish(PendingIntent ps, int sourceUid, String tag) {
3983        try {
3984            getService().noteAlarmFinish((ps != null) ? ps.getTarget() : null, sourceUid, tag);
3985        } catch (RemoteException ex) {
3986        }
3987    }
3988
3989    /**
3990     * @hide
3991     */
3992    public static IActivityManager getService() {
3993        return IActivityManagerSingleton.get();
3994    }
3995
3996    private static final Singleton<IActivityManager> IActivityManagerSingleton =
3997            new Singleton<IActivityManager>() {
3998                @Override
3999                protected IActivityManager create() {
4000                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
4001                    final IActivityManager am = IActivityManager.Stub.asInterface(b);
4002                    return am;
4003                }
4004            };
4005
4006    private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) {
4007        pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
4008        IBinder service = ServiceManager.checkService(name);
4009        if (service == null) {
4010            pw.println("  (Service not found)");
4011            return;
4012        }
4013        TransferPipe tp = null;
4014        try {
4015            pw.flush();
4016            tp = new TransferPipe();
4017            tp.setBufferPrefix("  ");
4018            service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args);
4019            tp.go(fd, 10000);
4020        } catch (Throwable e) {
4021            if (tp != null) {
4022                tp.kill();
4023            }
4024            pw.println("Failure dumping service:");
4025            e.printStackTrace(pw);
4026        }
4027    }
4028
4029    /**
4030     * Request that the system start watching for the calling process to exceed a pss
4031     * size as given here.  Once called, the system will look for any occasions where it
4032     * sees the associated process with a larger pss size and, when this happens, automatically
4033     * pull a heap dump from it and allow the user to share the data.  Note that this request
4034     * continues running even if the process is killed and restarted.  To remove the watch,
4035     * use {@link #clearWatchHeapLimit()}.
4036     *
4037     * <p>This API only work if the calling process has been marked as
4038     * {@link ApplicationInfo#FLAG_DEBUGGABLE} or this is running on a debuggable
4039     * (userdebug or eng) build.</p>
4040     *
4041     * <p>Callers can optionally implement {@link #ACTION_REPORT_HEAP_LIMIT} to directly
4042     * handle heap limit reports themselves.</p>
4043     *
4044     * @param pssSize The size in bytes to set the limit at.
4045     */
4046    public void setWatchHeapLimit(long pssSize) {
4047        try {
4048            getService().setDumpHeapDebugLimit(null, 0, pssSize,
4049                    mContext.getPackageName());
4050        } catch (RemoteException e) {
4051            throw e.rethrowFromSystemServer();
4052        }
4053    }
4054
4055    /**
4056     * Action an app can implement to handle reports from {@link #setWatchHeapLimit(long)}.
4057     * If your package has an activity handling this action, it will be launched with the
4058     * heap data provided to it the same way as {@link Intent#ACTION_SEND}.  Note that to
4059     * match the activty must support this action and a MIME type of "*&#47;*".
4060     */
4061    public static final String ACTION_REPORT_HEAP_LIMIT = "android.app.action.REPORT_HEAP_LIMIT";
4062
4063    /**
4064     * Clear a heap watch limit previously set by {@link #setWatchHeapLimit(long)}.
4065     */
4066    public void clearWatchHeapLimit() {
4067        try {
4068            getService().setDumpHeapDebugLimit(null, 0, 0, null);
4069        } catch (RemoteException e) {
4070            throw e.rethrowFromSystemServer();
4071        }
4072    }
4073
4074    /**
4075     * Return whether currently in lock task mode.  When in this mode
4076     * no new tasks can be created or switched to.
4077     *
4078     * @see Activity#startLockTask()
4079     *
4080     * @deprecated Use {@link #getLockTaskModeState} instead.
4081     */
4082    @Deprecated
4083    public boolean isInLockTaskMode() {
4084        return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
4085    }
4086
4087    /**
4088     * Return the current state of task locking. The three possible outcomes
4089     * are {@link #LOCK_TASK_MODE_NONE}, {@link #LOCK_TASK_MODE_LOCKED}
4090     * and {@link #LOCK_TASK_MODE_PINNED}.
4091     *
4092     * @see Activity#startLockTask()
4093     */
4094    public int getLockTaskModeState() {
4095        try {
4096            return getService().getLockTaskModeState();
4097        } catch (RemoteException e) {
4098            throw e.rethrowFromSystemServer();
4099        }
4100    }
4101
4102    /**
4103     * Enable more aggressive scheduling for latency-sensitive low-runtime VR threads. Only one
4104     * thread can be a VR thread in a process at a time, and that thread may be subject to
4105     * restrictions on the amount of time it can run.
4106     *
4107     * If persistent VR mode is set, whatever thread has been granted aggressive scheduling via this
4108     * method will return to normal operation, and calling this method will do nothing while
4109     * persistent VR mode is enabled.
4110     *
4111     * To reset the VR thread for an application, a tid of 0 can be passed.
4112     *
4113     * @see android.os.Process#myTid()
4114     * @param tid tid of the VR thread
4115     */
4116    public static void setVrThread(int tid) {
4117        try {
4118            getService().setVrThread(tid);
4119        } catch (RemoteException e) {
4120            // pass
4121        }
4122    }
4123
4124    /**
4125     * Enable more aggressive scheduling for latency-sensitive low-runtime VR threads that persist
4126     * beyond a single process. Only one thread can be a
4127     * persistent VR thread at a time, and that thread may be subject to restrictions on the amount
4128     * of time it can run. Calling this method will disable aggressive scheduling for non-persistent
4129     * VR threads set via {@link #setVrThread}. If persistent VR mode is disabled then the
4130     * persistent VR thread loses its new scheduling priority; this method must be called again to
4131     * set the persistent thread.
4132     *
4133     * To reset the persistent VR thread, a tid of 0 can be passed.
4134     *
4135     * @see android.os.Process#myTid()
4136     * @param tid tid of the VR thread
4137     * @hide
4138     */
4139    @RequiresPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
4140    public static void setPersistentVrThread(int tid) {
4141        try {
4142            getService().setPersistentVrThread(tid);
4143        } catch (RemoteException e) {
4144            // pass
4145        }
4146    }
4147
4148    /**
4149     * The AppTask allows you to manage your own application's tasks.
4150     * See {@link android.app.ActivityManager#getAppTasks()}
4151     */
4152    public static class AppTask {
4153        private IAppTask mAppTaskImpl;
4154
4155        /** @hide */
4156        public AppTask(IAppTask task) {
4157            mAppTaskImpl = task;
4158        }
4159
4160        /**
4161         * Finishes all activities in this task and removes it from the recent tasks list.
4162         */
4163        public void finishAndRemoveTask() {
4164            try {
4165                mAppTaskImpl.finishAndRemoveTask();
4166            } catch (RemoteException e) {
4167                throw e.rethrowFromSystemServer();
4168            }
4169        }
4170
4171        /**
4172         * Get the RecentTaskInfo associated with this task.
4173         *
4174         * @return The RecentTaskInfo for this task, or null if the task no longer exists.
4175         */
4176        public RecentTaskInfo getTaskInfo() {
4177            try {
4178                return mAppTaskImpl.getTaskInfo();
4179            } catch (RemoteException e) {
4180                throw e.rethrowFromSystemServer();
4181            }
4182        }
4183
4184        /**
4185         * Bring this task to the foreground.  If it contains activities, they will be
4186         * brought to the foreground with it and their instances re-created if needed.
4187         * If it doesn't contain activities, the root activity of the task will be
4188         * re-launched.
4189         */
4190        public void moveToFront() {
4191            try {
4192                mAppTaskImpl.moveToFront();
4193            } catch (RemoteException e) {
4194                throw e.rethrowFromSystemServer();
4195            }
4196        }
4197
4198        /**
4199         * Start an activity in this task.  Brings the task to the foreground.  If this task
4200         * is not currently active (that is, its id < 0), then a new activity for the given
4201         * Intent will be launched as the root of the task and the task brought to the
4202         * foreground.  Otherwise, if this task is currently active and the Intent does not specify
4203         * an activity to launch in a new task, then a new activity for the given Intent will
4204         * be launched on top of the task and the task brought to the foreground.  If this
4205         * task is currently active and the Intent specifies {@link Intent#FLAG_ACTIVITY_NEW_TASK}
4206         * or would otherwise be launched in to a new task, then the activity not launched but
4207         * this task be brought to the foreground and a new intent delivered to the top
4208         * activity if appropriate.
4209         *
4210         * <p>In other words, you generally want to use an Intent here that does not specify
4211         * {@link Intent#FLAG_ACTIVITY_NEW_TASK} or {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT},
4212         * and let the system do the right thing.</p>
4213         *
4214         * @param intent The Intent describing the new activity to be launched on the task.
4215         * @param options Optional launch options.
4216         *
4217         * @see Activity#startActivity(android.content.Intent, android.os.Bundle)
4218         */
4219        public void startActivity(Context context, Intent intent, Bundle options) {
4220            ActivityThread thread = ActivityThread.currentActivityThread();
4221            thread.getInstrumentation().execStartActivityFromAppTask(context,
4222                    thread.getApplicationThread(), mAppTaskImpl, intent, options);
4223        }
4224
4225        /**
4226         * Modify the {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag in the root
4227         * Intent of this AppTask.
4228         *
4229         * @param exclude If true, {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} will
4230         * be set; otherwise, it will be cleared.
4231         */
4232        public void setExcludeFromRecents(boolean exclude) {
4233            try {
4234                mAppTaskImpl.setExcludeFromRecents(exclude);
4235            } catch (RemoteException e) {
4236                throw e.rethrowFromSystemServer();
4237            }
4238        }
4239    }
4240}
4241