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