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