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