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