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