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