代码位于frameworks/base/services/core/java/com/android/server/am/,一共有七十个文件。

Java源码位于package com.android.server.am里

该类继承了IActivityManager.Stub的aidl通信接口,实现了watchdog monitor和battery stats impl的basttery callback接口

 456public class ActivityManagerService extends IActivityManager.Stub
457 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
458

顶端app的启动优先级

 459    /**
460 * Priority we boost main thread and RT of top app to.
461 */
462 public static final int TOP_APP_PRIORITY_BOOST = -10;
463

相应tag

 464    private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM;
465 private static final String TAG_BACKUP = TAG + POSTFIX_BACKUP;
466 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
467 private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP;
468 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
469 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
470 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
471 private static final String TAG_LOCKSCREEN = TAG + POSTFIX_LOCKSCREEN;
472 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
473 private static final String TAG_LRU = TAG + POSTFIX_LRU;
474 private static final String TAG_MU = TAG + POSTFIX_MU;
475 private static final String TAG_NETWORK = TAG + POSTFIX_NETWORK;
476 private static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ;
477 private static final String TAG_POWER = TAG + POSTFIX_POWER;
478 private static final String TAG_PROCESS_OBSERVERS = TAG + POSTFIX_PROCESS_OBSERVERS;
479 private static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES;
480 private static final String TAG_PROVIDER = TAG + POSTFIX_PROVIDER;
481 private static final String TAG_PSS = TAG + POSTFIX_PSS;
482 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
483 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
484 private static final String TAG_STACK = TAG + POSTFIX_STACK;
485 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
486 private static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS;
487 private static final String TAG_URI_PERMISSION = TAG + POSTFIX_URI_PERMISSION;
488 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
489 private static final String TAG_VISIBLE_BEHIND = TAG + POSTFIX_VISIBLE_BEHIND;

trigger idle action字符串

 491    // Mock "pretend we're idle now" broadcast action to the job scheduler; declared
492 // here so that while the job scheduler can depend on AMS, the other way around
493 // need not be the case.
494 public static final String ACTION_TRIGGER_IDLE = "com.android.server.ACTION_TRIGGER_IDLE";

monitor cpu时间间隔与状态

 496    /** Control over CPU and battery monitoring */
497 // write battery stats every 30 minutes.
498 static final long BATTERY_STATS_TIME = 30 * 60 * 1000;
499 static final boolean MONITOR_CPU_USAGE = true;
500 // don't sample cpu less than every 5 seconds.
501 static final long MONITOR_CPU_MIN_TIME = 5 * 1000;
502 // wait possibly forever for next cpu sample.
503 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff;
504 static final boolean MONITOR_THREAD_CPU_USAGE = false;

出货的package manager flag

 505
506 // The flags that are set for all calls we make to the package manager.
507 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;

是否可以调试属性

 509    static final String SYSTEM_DEBUGGABLE = "ro.debuggable";

是否是user版本

 511    static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);

相应的时间配置

 513    // Amount of time after a call to stopAppSwitches() during which we will
514 // prevent further untrusted switches from happening.
515 static final long APP_SWITCH_DELAY_TIME = 5*1000;
516
517 // How long we wait for a launched process to attach to the activity manager
518 // before we decide it's never going to come up for real.
519 static final int PROC_START_TIMEOUT = 10*1000;
520 // How long we wait for an attached process to publish its content providers
521 // before we decide it must be hung.
522 static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT = 10*1000;
523
524 // How long we wait for a launched process to attach to the activity manager
525 // before we decide it's never going to come up for real, when the process was
526 // started with a wrapper for instrumentation (such as Valgrind) because it
527 // could take much longer than usual.
528 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000;
529
530 // How long we allow a receiver to run before giving up on it.
531 static final int BROADCAST_FG_TIMEOUT = 10*1000;
532 static final int BROADCAST_BG_TIMEOUT = 60*1000;
533
534 // How long we wait until we timeout on key dispatching.
535 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
536
537 // How long we wait until we timeout on key dispatching during instrumentation.
538 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
539
540 // How long to wait in getAssistContextExtras for the activity and foreground services
541 // to respond with the result.
542 static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
543
544 // How long top wait when going through the modern assist (which doesn't need to block
545 // on getting this result before starting to launch its UI).
546 static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
547
548 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
549 static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;

一个package最大可被授权的权限数量

 551    // Maximum number of persisted Uri grants a package is allowed
552 static final int MAX_PERSISTED_URI_GRANTS = 128;

my pid

 554    static final int MY_PID = myPid();

空String数组

 556    static final String[] EMPTY_STRING_ARRAY = new String[0];

dropbox大小,logcat line的保留byte数

 558    // How many bytes to write into the dropbox log before truncating
559 static final int DROPBOX_MAX_SIZE = 192 * 1024;
560 // Assumes logcat entries average around 100 bytes; that's not perfect stack traces count
561 // as one line, but close enough for now.
562 static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100;

处理即将使用的用户的模式

 564    // Access modes for handleIncomingUser.
565 static final int ALLOW_NON_FULL = 0;
566 static final int ALLOW_NON_FULL_IN_PROFILE = 1;
567 static final int ALLOW_FULL_ONLY = 2;

persistent app的flag

 569    // Necessary ApplicationInfo flags to mark an app as persistent
570 private static final int PERSISTENT_MASK =
571 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT;

bugreport finish Intent

 573    // Intent sent when remote bugreport collection has been completed
574 private static final String INTENT_REMOTE_BUGREPORT_FINISHED =
575 "com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED";

是否做动画,是否录屏

 577    // Used to indicate that an app transition should be animated.
578 static final boolean ANIMATE = true;
579
580 // Determines whether to take full screen screenshots
581 static final boolean TAKE_FULLSCREEN_SCREENSHOTS = true;

网络状态

 583    /**
584 * Default value for {@link Settings.Global#NETWORK_ACCESS_TIMEOUT_MS}.
585 */
586 private static final long NETWORK_ACCESS_TIMEOUT_DEFAULT_MS = 200; // 0.2 sec
587
588 /**
589 * State indicating that there is no need for any blocking for network.
590 */
591 @VisibleForTesting
592 static final int NETWORK_STATE_NO_CHANGE = 0;
593
594 /**
595 * State indicating that the main thread needs to be informed about the network wait.
596 */
597 @VisibleForTesting
598 static final int NETWORK_STATE_BLOCK = 1;
599
600 /**
601 * State indicating that any threads waiting for network state to get updated can be unblocked.
602 */
603 @VisibleForTesting
604 static final int NETWORK_STATE_UNBLOCK = 2;

bug report最大title size

 606    // Max character limit for a notification title. If the notification title is larger than this
607 // the notification will not be legible to the user.
608 private static final int MAX_BUGREPORT_TITLE_SIZE = 50;

所有的系统服务和辅助工具

 610    /** All system services */
611 SystemServiceManager mSystemServiceManager;
612 AssistUtils mAssistUtils;

安装器

 614    private Installer mInstaller;

activity stack管理者,锁屏,activity starter,task变更通知控制器,性能测试reporter,ActiveInstrumentation列表,IntentFirewall

 616    /** Run all ActivityStacks through this */
617 final ActivityStackSupervisor mStackSupervisor;
618 private final KeyguardController mKeyguardController;
619
620 final ActivityStarter mActivityStarter;
621
622 final TaskChangeNotificationController mTaskChangeNotificationController;
623
624 final InstrumentationReporter mInstrumentationReporter = new InstrumentationReporter();
625
626 final ArrayList<ActiveInstrumentation> mActiveInstrumentation = new ArrayList<>();
627
628 public final IntentFirewall mIntentFirewall;

是否显示dialog

 630    // Whether we should show our dialogs (ANR, crash, etc) or just perform their
631 // default action automatically. Important for devices without direct input
632 // devices.
633 private boolean mShowDialogs = true;

vr控制器和其display

 635    private final VrController mVrController;
636
637 // VR Vr2d Display Id.
638 int mVr2dDisplayId = INVALID_DISPLAY;

是否对ui线程使用fifo

 640    // Whether we should use SCHED_FIFO for UI and RenderThreads.
641 private boolean mUseFifoUiScheduling = false;

broadcast queue和状态

 643    BroadcastQueue mFgBroadcastQueue;
644 BroadcastQueue mBgBroadcastQueue;
645 // Convenient for easy iteration over the queues. Foreground is first
646 // so that dispatch of foreground broadcasts gets precedence.
647 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
648
649 BroadcastStats mLastBroadcastStats;
650 BroadcastStats mCurBroadcastStats;
651
652 BroadcastQueue broadcastQueueForIntent(Intent intent) {
653 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
654 if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST,
655 "Broadcast intent " + intent + " on "
656 + (isFg ? "foreground" : "background") + " queue");
657 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
658 }
659

相应的组件历史记录

 660    /**
661 * The last resumed activity. This is identical to the current resumed activity most
662 * of the time but could be different when we're pausing one activity before we resume
663 * another activity.
664 */
665 private ActivityRecord mLastResumedActivity;
666
667 /**
668 * If non-null, we are tracking the time the user spends in the currently focused app.
669 */
670 private AppTimeTracker mCurAppTimeTracker;
671
672 /**
673 * List of intents that were used to start the most recent tasks.
674 */
675 final RecentTasks mRecentTasks;
676
677 /**
678 * For addAppTask: cached of the last activity component that was added.
679 */
680 ComponentName mLastAddedTaskComponent;
681
682 /**
683 * For addAppTask: cached of the last activity uid that was added.
684 */
685 int mLastAddedTaskUid;
686
687 /**
688 * For addAppTask: cached of the last ActivityInfo that was added.
689 */
690 ActivityInfo mLastAddedTaskActivity;
691
692 /**
693 * List of packages whitelisted by DevicePolicyManager for locktask. Indexed by userId.
694 */
695 SparseArray<String[]> mLockTaskPackages = new SparseArray<>();
696
697 /**
698 * The package name of the DeviceOwner. This package is not permitted to have its data cleared.
699 */
700 String mDeviceOwnerName;
701
702 final UserController mUserController;
703
704 final AppErrors mAppErrors;
705
706 /**
707 * Dump of the activity state at the time of the last ANR. Cleared after
708 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
709 */
710 String mLastANRState;

网络等待超时时长

 712    /**
713 * Indicates the maximum time spent waiting for the network rules to get updated.
714 */
715 @VisibleForTesting
716 long mWaitForNetworkTimeoutMs;

是否显示错误对话框

 718    public boolean canShowErrorDialogs() {
719 return mShowDialogs && !mSleeping && !mShuttingDown
720 && !mKeyguardController.isKeyguardShowing();
721 }

线程优先级booster

 723    private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster(
724 THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_ACTIVITY);
725
726 static void boostPriorityForLockedSection() {
727 sThreadPriorityBooster.boost();
728 }
729
730 static void resetPriorityAfterLockedSection() {
731 sThreadPriorityBooster.reset();
732 }

pending辅助类

 34    public class PendingAssistExtras extends Binder implements Runnable {
735 public final ActivityRecord activity;
736 public boolean isHome;
737 public final Bundle extras;
738 public final Intent intent;
739 public final String hint;
740 public final IResultReceiver receiver;
741 public final int userHandle;
742 public boolean haveResult = false;
743 public Bundle result = null;
744 public AssistStructure structure = null;
745 public AssistContent content = null;
746 public Bundle receiverExtras;
747
748 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
749 String _hint, IResultReceiver _receiver, Bundle _receiverExtras, int _userHandle) {
750 activity = _activity;
751 extras = _extras;
752 intent = _intent;
753 hint = _hint;
754 receiver = _receiver;
755 receiverExtras = _receiverExtras;
756 userHandle = _userHandle;
757 }
758
759 @Override
760 public void run() {
761 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
762 synchronized (this) {
763 haveResult = true;
764 notifyAll();
765 }
766 pendingAssistExtrasTimedOut(this);
767 }
768 }
769
770 final ArrayList<PendingAssistExtras> mPendingAssistExtras
771 = new ArrayList<PendingAssistExtras>();
772

进程相关变量

 70    final ArrayList<PendingAssistExtras> mPendingAssistExtras
771 = new ArrayList<PendingAssistExtras>();
772
773 /**
774 * Process management.
775 */
776 final ProcessList mProcessList = new ProcessList();
777
778 /**
779 * All of the applications we currently have running organized by name.
780 * The keys are strings of the application package name (as
781 * returned by the package manager), and the keys are ApplicationRecord
782 * objects.
783 */
784 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
785
786 /**
787 * Tracking long-term execution of processes to look for abuse and other
788 * bad app behavior.
789 */
790 final ProcessStatsService mProcessStats;
791
792 /**
793 * The currently running isolated processes.
794 */
795 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
796
797 /**
798 * Counter for assigning isolated process uids, to avoid frequently reusing the
799 * same ones.
800 */
801 int mNextIsolatedProcessUid = 0;
802
803 /**
804 * The currently running heavy-weight process, if any.
805 */
806 ProcessRecord mHeavyWeightProcess = null;
807
808 /**
809 * Non-persistent appId whitelist for background restrictions
810 */
811 int[] mBackgroundAppIdWhitelist = new int[] {
812 BLUETOOTH_UID
813 };
814
815 /**
816 * Broadcast actions that will always be deliverable to unlaunched/background apps
817 */
818 ArraySet<String> mBackgroundLaunchBroadcasts;
819
820 /**
821 * All of the processes we currently have running organized by pid.
822 * The keys are the pid running the application.
823 *
824 * <p>NOTE: This object is protected by its own lock, NOT the global
825 * activity manager lock!
826 */
827 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();

重要进程的token身份,包括名字, IBinder和原因

 829    /**
830 * All of the processes that have been forced to be important. The key
831 * is the pid of the caller who requested it (we hold a death
832 * link on it).
833 */
834 abstract class ImportanceToken implements IBinder.DeathRecipient {
835 final int pid;
836 final IBinder token;
837 final String reason;
838
839 ImportanceToken(int _pid, IBinder _token, String _reason) {
840 pid = _pid;
841 token = _token;
842 reason = _reason;
843 }
844
845 @Override
846 public String toString() {
847 return "ImportanceToken { " + Integer.toHexString(System.identityHashCode(this))
848 + " " + reason + " " + pid + " " + token + " }";
849 }
850 }

重要进程列表

 851    final SparseArray<ImportanceToken> mImportantProcesses = new SparseArray<ImportanceToken>();

等待系统初始化完毕后启动的进程列表

 853    /**
854 * List of records for processes that someone had tried to start before the
855 * system was ready. We don't start them at that point, but ensure they
856 * are started by the time booting is complete.
857 */
858 final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>();

其他相关的进程信息

 860    /**
861 * List of persistent applications that are in the process
862 * of being started.
863 */
864 final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>();
865
866 /**
867 * Processes that are being forcibly torn down.
868 */
869 final ArrayList<ProcessRecord> mRemovedProcesses = new ArrayList<ProcessRecord>();
870
871 /**
872 * List of running applications, sorted by recent usage.
873 * The first entry in the list is the least recently used.
874 */
875 final ArrayList<ProcessRecord> mLruProcesses = new ArrayList<ProcessRecord>();
876
877 /**
878 * Where in mLruProcesses that the processes hosting activities start.
879 */
880 int mLruProcessActivityStart = 0;
881
882 /**
883 * Where in mLruProcesses that the processes hosting services start.
884 * This is after (lower index) than mLruProcessesActivityStart.
885 */
886 int mLruProcessServiceStart = 0;
887
888 /**
889 * List of processes that should gc as soon as things are idle.
890 */
891 final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>();
892
893 /**
894 * Processes we want to collect PSS data from.
895 */
896 final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>();
897
898 private boolean mBinderTransactionTrackingEnabled = false;
899
900 /**
901 * Last time we requested PSS data of all processes.
902 */
903 long mLastFullPssTime = SystemClock.uptimeMillis();
904
905 /**
906 * If set, the next time we collect PSS data we should do a full collection
907 * with data from native processes and the kernel.
908 */
909 boolean mFullPssPending = false;
910
911 /**
912 * This is the process holding what we currently consider to be
913 * the "home" activity.
914 */
915 ProcessRecord mHomeProcess;
916
917 /**
918 * This is the process holding the activity the user last visited that
919 * is in a different process from the one they are currently in.
920 */
921 ProcessRecord mPreviousProcess;
922
923 /**
924 * The time at which the previous process was last visible.
925 */
926 long mPreviousProcessVisibleTime;

Uid相关

 928    /**
929 * Track all uids that have actively running processes.
930 */
931 final SparseArray<UidRecord> mActiveUids = new SparseArray<>();
932
933 /**
934 * This is for verifying the UID report flow.
935 */
936 static final boolean VALIDATE_UID_STATES = true;
937 final SparseArray<UidRecord> mValidateUids = new SparseArray<>();

兼容模式包

 939    /**
940 * Packages that the user has asked to have run in screen size
941 * compatibility mode instead of filling the screen.
942 */
943 final CompatModePackages mCompatModePackages;
944

Intent发送记录

 945    /**
946 * Set of IntentSenderRecord objects that are currently active.
947 */
948 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
949 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();

已经记录的违规log

 951    /**
952 * Fingerprints (hashCode()) of stack traces that we've
953 * already logged DropBox entries for. Guarded by itself. If
954 * something (rogue user app) forces this over
955 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
956 */
957 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
958 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;

strict mode buffer

 960    /**
961 * Strict Mode background batched logging state.
962 *
963 * The string buffer is guarded by itself, and its lock is also
964 * used to determine if another batched write is already
965 * in-flight.
966 */
967 private final StringBuilder mStrictModeBuffer = new StringBuilder();

已经注册的receiver

 969    /**
970 * Keeps track of all IIntentReceivers that have been registered for broadcasts.
971 * Hash keys are the receiver IBinder, hash value is a ReceiverList.
972 */
973 final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>();
974

intent解析器

 975    /**
976 * Resolver for broadcast intents to registered receivers.
977 * Holds BroadcastFilter (subclass of IntentFilter).
978 */
979 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
980 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
981 @Override
982 protected boolean allowFilterResult(
983 BroadcastFilter filter, List<BroadcastFilter> dest) {
984 IBinder target = filter.receiverList.receiver.asBinder();
985 for (int i = dest.size() - 1; i >= 0; i--) {
986 if (dest.get(i).receiverList.receiver.asBinder() == target) {
987 return false;
988 }
989 }
990 return true;
991 }
992
993 @Override
994 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
995 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
996 || userId == filter.owningUserId) {
997 return super.newResult(filter, match, userId);
998 }
999 return null;
1000 }
1001
1002 @Override
1003 protected BroadcastFilter[] newArray(int size) {
1004 return new BroadcastFilter[size];
1005 }
1006
1007 @Override
1008 protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) {
1009 return packageName.equals(filter.packageName);
1010 }
1011 };
1012

严格广播

 1013    /**
1014 * State of all active sticky broadcasts per user. Keys are the action of the
1015 * sticky Intent, values are an ArrayList of all broadcasted intents with
1016 * that action (which should usually be one). The SparseArray is keyed
1017 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
1018 * for stickies that are sent to all users.
1019 */
1020 final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts =
1021 new SparseArray<ArrayMap<String, ArrayList<Intent>>>();
1022

活跃的service

 1023    final ActiveServices mServices;

进程间的关联

 1025    final static class Association {
1026 final int mSourceUid;
1027 final String mSourceProcess;
1028 final int mTargetUid;
1029 final ComponentName mTargetComponent;
1030 final String mTargetProcess;
1031
1032 int mCount;
1033 long mTime;
1034
1035 int mNesting;
1036 long mStartTime;
1037
1038 // states of the source process when the bind occurred.
1039 int mLastState = ActivityManager.MAX_PROCESS_STATE + 1;
1040 long mLastStateUptime;
1041 long[] mStateTimes = new long[ActivityManager.MAX_PROCESS_STATE
1042 - ActivityManager.MIN_PROCESS_STATE+1];
1043
1044 Association(int sourceUid, String sourceProcess, int targetUid,
1045 ComponentName targetComponent, String targetProcess) {
1046 mSourceUid = sourceUid;
1047 mSourceProcess = sourceProcess;
1048 mTargetUid = targetUid;
1049 mTargetComponent = targetComponent;
1050 mTargetProcess = targetProcess;
1051 }
1052 }

关联的列表和状态

 1054    /**
1055 * When service association tracking is enabled, this is all of the associations we
1056 * have seen. Mapping is target uid -> target component -> source uid -> source process name
1057 * -> association data.
1058 */
1059 final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>>
1060 mAssociations = new SparseArray<>();
1061 boolean mTrackingAssociations;

back名字和目标

 1063    /**
1064 * Backup/restore process management
1065 */
1066 String mBackupAppName = null;
1067 BackupRecord mBackupTarget = null;

provider map

 1069    final ProviderMap mProviderMap;

contentprovider 列表

 1071    /**
1072 * List of content providers who have clients waiting for them. The
1073 * application is currently being launched and the provider will be
1074 * removed from this list once it is published.
1075 */
1076 final ArrayList<ContentProviderRecord> mLaunchingProviders
1077 = new ArrayList<ContentProviderRecord>();
1078

授权文件其其相关tag和java bean类

 1079    /**
1080 * File storing persisted {@link #mGrantedUriPermissions}.
1081 */
1082 private final AtomicFile mGrantFile;
1083
1084 /** XML constants used in {@link #mGrantFile} */
1085 private static final String TAG_URI_GRANTS = "uri-grants";
1086 private static final String TAG_URI_GRANT = "uri-grant";
1087 private static final String ATTR_USER_HANDLE = "userHandle";
1088 private static final String ATTR_SOURCE_USER_ID = "sourceUserId";
1089 private static final String ATTR_TARGET_USER_ID = "targetUserId";
1090 private static final String ATTR_SOURCE_PKG = "sourcePkg";
1091 private static final String ATTR_TARGET_PKG = "targetPkg";
1092 private static final String ATTR_URI = "uri";
1093 private static final String ATTR_MODE_FLAGS = "modeFlags";
1094 private static final String ATTR_CREATED_TIME = "createdTime";
1095 private static final String ATTR_PREFIX = "prefix";
1096
1097 /**
1098 * Global set of specific {@link Uri} permissions that have been granted.
1099 * This optimized lookup structure maps from {@link UriPermission#targetUid}
1100 * to {@link UriPermission#uri} to {@link UriPermission}.
1101 */
1102 @GuardedBy("this")
1103 private final SparseArray<ArrayMap<GrantUri, UriPermission>>
1104 mGrantedUriPermissions = new SparseArray<ArrayMap<GrantUri, UriPermission>>();
1105
1106 public static class GrantUri {
1107 public final int sourceUserId;
1108 public final Uri uri;
1109 public boolean prefix;
1110
1111 public GrantUri(int sourceUserId, Uri uri, boolean prefix) {
1112 this.sourceUserId = sourceUserId;
1113 this.uri = uri;
1114 this.prefix = prefix;
1115 }
1116
1117 @Override
1118 public int hashCode() {
1119 int hashCode = 1;
1120 hashCode = 31 * hashCode + sourceUserId;
1121 hashCode = 31 * hashCode + uri.hashCode();
1122 hashCode = 31 * hashCode + (prefix ? 1231 : 1237);
1123 return hashCode;
1124 }
1125
1126 @Override
1127 public boolean equals(Object o) {
1128 if (o instanceof GrantUri) {
1129 GrantUri other = (GrantUri) o;
1130 return uri.equals(other.uri) && (sourceUserId == other.sourceUserId)
1131 && prefix == other.prefix;
1132 }
1133 return false;
1134 }
1135
1136 @Override
1137 public String toString() {
1138 String result = uri.toString() + " [user " + sourceUserId + "]";
1139 if (prefix) result += " [prefix]";
1140 return result;
1141 }
1142
1143 public String toSafeString() {
1144 String result = uri.toSafeString() + " [user " + sourceUserId + "]";
1145 if (prefix) result += " [prefix]";
1146 return result;
1147 }
1148
1149 public static GrantUri resolve(int defaultSourceUserHandle, Uri uri) {
1150 return new GrantUri(ContentProvider.getUserIdFromUri(uri, defaultSourceUserHandle),
1151 ContentProvider.getUriWithoutUserId(uri), false);
1152 }
1153 }

核心设置observer和字体缩放设置observer

 1155    CoreSettingsObserver mCoreSettingsObserver;
1156
1157 FontScaleSettingObserver mFontScaleSettingObserver;

font scale observer类

 1159    private final class FontScaleSettingObserver extends ContentObserver {
1160 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
1161
1162 public FontScaleSettingObserver() {
1163 super(mHandler);
1164 ContentResolver resolver = mContext.getContentResolver();
1165 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
1166 }
1167
1168 @Override
1169 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
1170 if (mFontScaleUri.equals(uri)) {
1171 updateFontScaleIfNeeded(userId);
1172 }
1173 }
1174 }

内部类身份

 1176    /**
1177 * Thread-local storage used to carry caller permissions over through
1178 * indirect content-provider access.
1179 */
1180 private class Identity {
1181 public final IBinder token;
1182 public final int pid;
1183 public final int uid;
1184
1185 Identity(IBinder _token, int _pid, int _uid) {
1186 token = _token;
1187 pid = _pid;
1188 uid = _uid;
1189 }
1190 }

调用者身份

 1192    private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();

battery 和 usage stats  service

 1194    /**
1195 * All information we have collected about the runtime performance of
1196 * any user id that can impact battery performance.
1197 */
1198 final BatteryStatsService mBatteryStatsService;
1199
1200 /**
1201 * Information about component usage
1202 */
1203 UsageStatsManagerInternal mUsageStatsService;

device idle controller 和白名单

 1205    /**
1206 * Access to DeviceIdleController service.
1207 */
1208 DeviceIdleController.LocalService mLocalDeviceIdleController;
1209
1210 /**
1211 * Set of app ids that are whitelisted for device idle and thus background check.
1212 */
1213 int[] mDeviceIdleWhitelist = new int[0];
1214
1215 /**
1216 * Set of app ids that are temporarily allowed to escape bg check due to high-pri message
1217 */
1218 int[] mDeviceIdleTempWhitelist = new int[0];

延迟白名单

 1220    static final class PendingTempWhitelist {
1221 final int targetUid;
1222 final long duration;
1223 final String tag;
1224
1225 PendingTempWhitelist(int _targetUid, long _duration, String _tag) {
1226 targetUid = _targetUid;
1227 duration = _duration;
1228 tag = _tag;
1229 }
1230 }
1231
1232 final SparseArray<PendingTempWhitelist> mPendingTempWhitelist = new SparseArray<>();

app ops service

 1234    /**
1235 * Information about and control over application operations
1236 */
1237 final AppOpsService mAppOpsService;

config seq

 1239    /** Current sequencing integer of the configuration, for skipping old configurations. */
1240 private int mConfigurationSeq;
1241

临时config

 1242    /**
1243 * Temp object used when global and/or display override configuration is updated. It is also
1244 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
1245 * anyone...
1246 */
1247 private Configuration mTempConfig = new Configuration();

临时更新config result

 1249    private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
1250 new UpdateConfigurationResult();
 1251    private static final class UpdateConfigurationResult {
1252 // Configuration changes that were updated.
1253 int changes;
1254 // If the activity was relaunched to match the new configuration.
1255 boolean activityRelaunched;
1256
1257 void reset() {
1258 changes = 0;
1259 activityRelaunched = false;
1260 }
1261 }

是否抑制resize config change

 1263    boolean mSuppressResizeConfigChanges;
1264

open gl es版本

 1265    /**
1266 * Hardware-reported OpenGLES version.
1267 */
1268 final int GL_ES_VERSION;

app binding args

 1270    /**
1271 * List of initialization arguments to pass to all processes when binding applications to them.
1272 * For example, references to the commonly used services.
1273 */
1274 HashMap<String, IBinder> mAppBindArgs;
1275 HashMap<String, IBinder> mIsolatedAppBindArgs;

string builder

 1277    /**
1278 * Temporary to avoid allocations. Protected by main lock.
1279 */
1280 final StringBuilder mStringBuilder = new StringBuilder(256);

顶端组件,action,data

 1282    /**
1283 * Used to control how we initialize the service.
1284 */
1285 ComponentName mTopComponent;
1286 String mTopAction = Intent.ACTION_MAIN;
1287 String mTopData;
1288

进程、系统等是否ready flag

 1289    volatile boolean mProcessesReady = false;
1290 volatile boolean mSystemReady = false;
1291 volatile boolean mOnBattery = false;
1292 volatile int mFactoryTest;
1293
1294 @GuardedBy("this") boolean mBooting = false;
1295 @GuardedBy("this") boolean mCallFinishBooting = false;
1296 @GuardedBy("this") boolean mBootAnimationComplete = false;
1297 @GuardedBy("this") boolean mLaunchWarningShown = false;
1298 @GuardedBy("this") boolean mCheckedForSetup = false;

context和ui context

 1300    final Context mContext;
1301
1302 /**
1303 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
1304 * change at runtime. Use mContext for non-UI purposes.
1305 */
1306 final Context mUiContext;

app切换

 1308    /**
1309 * The time at which we will allow normal application switches again,
1310 * after a call to {@link #stopAppSwitches()}.
1311 */
1312 long mAppSwitchesAllowedTime;
1313
1314 /**
1315 * This is set to true after the first switch after mAppSwitchesAllowedTime
1316 * is set; any switches after that will clear the time.
1317 */
1318 boolean mDidAppSwitch;
1319

睡眠状态

 1320    /**
1321 * Last time (in realtime) at which we checked for power usage.
1322 */
1323 long mLastPowerCheckRealtime;
1324
1325 /**
1326 * Last time (in uptime) at which we checked for power usage.
1327 */
1328 long mLastPowerCheckUptime;
1329
1330 /**
1331 * Set while we are wanting to sleep, to prevent any
1332 * activities from being started/resumed.
1333 *
1334 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
1335 *
1336 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
1337 * while in the sleep state until there is a pending transition out of sleep, in which case
1338 * mSleeping is set to false, and remains false while awake.
1339 *
1340 * Whether mSleeping can quickly toggled between true/false without the device actually
1341 * display changing states is undefined.
1342 */
1343 private boolean mSleeping = false;

进程状态

 1345    /**
1346 * The process state used for processes that are running the top activities.
1347 * This changes between TOP and TOP_SLEEPING to following mSleeping.
1348 */
1349 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;

运行的voice

 1351    /**
1352 * Set while we are running a voice interaction. This overrides
1353 * sleeping while it is active.
1354 */
1355 private IVoiceInteractionSession mRunningVoice;

local power manager

 1357    /**
1358 * For some direct access we need to power manager.
1359 */
1360 PowerManagerInternal mLocalPowerManager;

voice wakelock

 1362    /**
1363 * We want to hold a wake lock while running a voice interaction session, since
1364 * this may happen with the screen off and we need to keep the CPU running to
1365 * be able to continue to interact with the user.
1366 */
1367 PowerManager.WakeLock mVoiceWakeLock;
1368

唤醒程度

 1369    /**
1370 * State of external calls telling us if the device is awake or asleep.
1371 */
1372 private int mWakefulness = PowerManagerInternal.WAKEFULNESS_AWAKE;

睡眠token列表

 1374    /**
1375 * A list of tokens that cause the top activity to be put to sleep.
1376 * They are used by components that may hide and block interaction with underlying
1377 * activities.
1378 */
1379 final ArrayList<SleepToken> mSleepTokens = new ArrayList<SleepToken>();
1380

是否关机

 1381    /**
1382 * Set if we are shutting down the system, similar to sleeping.
1383 */
1384 boolean mShuttingDown = false;

adj,lru seq

 1386    /**
1387 * Current sequence id for oom_adj computation traversal.
1388 */
1389 int mAdjSeq = 0;
1390
1391 /**
1392 * Current sequence id for process LRU updating.
1393 */
1394 int mLruSeq = 0;

cache process数量

 1396    /**
1397 * Keep track of the non-cached/empty process we last found, to help
1398 * determine how to distribute cached/empty processes next time.
1399 */
1400 int mNumNonCachedProcs = 0;
1401
1402 /**
1403 * Keep track of the number of cached hidden procs, to balance oom adj
1404 * distribution between those and empty procs.
1405 */
1406 int mNumCachedHiddenProcs = 0;

进程数量

 1408    /**
1409 * Keep track of the number of service processes we last found, to
1410 * determine on the next iteration which should be B services.
1411 */
1412 int mNumServiceProcs = 0;
1413 int mNewNumAServiceProcs = 0;
1414 int mNewNumServiceProcs = 0;

允许的memory level

 1416    /**
1417 * Allow the current computed overall memory level of the system to go down?
1418 * This is set to false when we are killing processes for reasons other than
1419 * memory management, so that the now smaller process list will not be taken as
1420 * an indication that memory is tighter.
1421 */
1422 boolean mAllowLowerMemLevel = false;
1423

上一次的内存级别与进程数量

 1424    /**
1425 * The last computed memory level, for holding when we are in a state that
1426 * processes are going away for other reasons.
1427 */
1428 int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1429
1430 /**
1431 * The last total number of process we have, to determine if changes actually look
1432 * like a shrinking number of process due to lower RAM.
1433 */
1434 int mLastNumProcesses;
1435

上一次idle时间

 1437     * The uptime of the last time we performed idle maintenance.
1438 */
1439 long mLastIdleTime = SystemClock.uptimeMillis();

自从idle后低内存时间

 1441    /**
1442 * Total time spent with RAM that has been added in the past since the last idle time.
1443 */
1444 long mLowRamTimeSinceLastIdle = 0;

上一次低内存开始时间

 1446    /**
1447 * If RAM is currently low, when that horrible situation started.
1448 */
1449 long mLowRamStartTime = 0;

当前恢复的pacakge,当前恢复的uid

 1451    /**
1452 * For reporting to battery stats the current top application.
1453 */
1454 private String mCurResumedPackage = null;
1455 private int mCurResumedUid = -1;

前台运行的包

 1457    /**
1458 * For reporting to battery stats the apps currently running foreground
1459 * service. The ProcessMap is package/uid tuples; each of these contain
1460 * an array of the currently foreground processes.
1461 */
1462 final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages
1463 = new ProcessMap<ArrayList<ProcessRecord>>();

是否做了dexopt

 1465    /**
1466 * This is set if we had to do a delayed dexopt of an app before launching
1467 * it, to increase the ANR timeouts in that case.
1468 */
1469 boolean mDidDexOpt;

是否是安全模式

 1471    /**
1472 * Set if the systemServer made a call to enterSafeMode.
1473 */
1474 boolean mSafeMode;

是否是test pss模式

 1476    /**
1477 * If true, we are running under a test environment so will sample PSS from processes
1478 * much more rapidly to try to collect better data when the tests are rapidly
1479 * running through apps.
1480 */
1481 boolean mTestPssMode = false;

debug相关

 1483    String mDebugApp = null;
1484 boolean mWaitForDebugger = false;
1485 boolean mDebugTransient = false;
1486 String mOrigDebugApp = null;
1487 boolean mOrigWaitForDebugger = false;

是否总是总是activity;是否强制resize activity

 1488    boolean mAlwaysFinishActivities = false;
1489 boolean mForceResizableActivities;

支持的特性

 1490    /**
1491 * Flag that indicates if multi-window is enabled.
1492 *
1493 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
1494 * in {@link com.android.internal.R.bool.config_supportsMultiWindow} config or
1495 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
1496 * At least one of the forms of multi-window must be enabled in order for this flag to be
1497 * initialized to 'true'.
1498 *
1499 * @see #mSupportsSplitScreenMultiWindow
1500 * @see #mSupportsFreeformWindowManagement
1501 * @see #mSupportsPictureInPicture
1502 * @see #mSupportsMultiDisplay
1503 */
1504 boolean mSupportsMultiWindow;
1505 boolean mSupportsSplitScreenMultiWindow;
1506 boolean mSupportsFreeformWindowManagement;
1507 boolean mSupportsPictureInPicture;
1508 boolean mSupportsMultiDisplay;
1509 boolean mSupportsLeanbackOnly;

activity controller

 1510    IActivityController mController = null;

controller是否是monkey

 1511    boolean mControllerIsAMonkey = false;

profile,memory watch相关

 1512    String mProfileApp = null;
1513 ProcessRecord mProfileProc = null;
1514 String mProfileFile;
1515 ParcelFileDescriptor mProfileFd;
1516 int mSamplingInterval = 0;
1517 boolean mAutoStopProfiler = false;
1518 boolean mStreamingOutput = false;
1519 int mProfileType = 0;
1520 final ProcessMap<Pair<Long, String>> mMemWatchProcesses = new ProcessMap<>();
1521 String mMemWatchDumpProcName;
1522 String mMemWatchDumpFile;
1523 int mMemWatchDumpPid;
1524 int mMemWatchDumpUid;
1525 String mTrackAllocationApp = null;
1526 String mNativeDebuggingApp = null;

两个临时long

 1528    final long[] mTmpLong = new long[2];

临时广播队列

 1530    private final ArraySet<BroadcastQueue> mTmpBroadcastQueue = new ArraySet();
1531

进程状态序号计数器

 1532    /**
1533 * A global counter for generating sequence numbers.
1534 * This value will be used when incrementing sequence numbers in individual uidRecords.
1535 *
1536 * Having a global counter ensures that seq numbers are monotonically increasing for a
1537 * particular uid even when the uidRecord is re-created.
1538 */
1539 @GuardedBy("this")
1540 @VisibleForTesting
1541 long mProcStateSeqCounter = 0;

Injector类

 1543    private final Injector mInjector;

进程改变项内部类

 1545    static final class ProcessChangeItem {
1546 static final int CHANGE_ACTIVITIES = 1<<0;
1547 int changes;
1548 int uid;
1549 int pid;
1550 int processState;
1551 boolean foregroundActivities;
1552 }

uid观察者注册器

 1554    static final class UidObserverRegistration {
1555 final int uid;
1556 final String pkg;
1557 final int which;
1558 final int cutpoint;
1559
1560 final SparseIntArray lastProcStates;
1561
1562 UidObserverRegistration(int _uid, String _pkg, int _which, int _cutpoint) {
1563 uid = _uid;
1564 pkg = _pkg;
1565 which = _which;
1566 cutpoint = _cutpoint;
1567 if (cutpoint >= ActivityManager.MIN_PROCESS_STATE) {
1568 lastProcStates = new SparseIntArray();
1569 } else {
1570 lastProcStates = null;
1571 }
1572 }
1573 }

进程观察者和进程改变项数组

 1575    final RemoteCallbackList<IProcessObserver> mProcessObservers = new RemoteCallbackList<>();
1576 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];

延迟的和可用的进程变化

 1578    final ArrayList<ProcessChangeItem> mPendingProcessChanges = new ArrayList<>();
1579 final ArrayList<ProcessChangeItem> mAvailProcessChanges = new ArrayList<>();

uid观察者和uid变化

 1581    final RemoteCallbackList<IUidObserver> mUidObservers = new RemoteCallbackList<>();
1582 UidRecord.ChangeItem[] mActiveUidChanges = new UidRecord.ChangeItem[5];

延迟的uid change和可用的uid change

 1584    final ArrayList<UidRecord.ChangeItem> mPendingUidChanges = new ArrayList<>();
1585 final ArrayList<UidRecord.ChangeItem> mAvailUidChanges = new ArrayList<>();
1586

进程cpu所运行的线程

 1587    /**
1588 * Runtime CPU use collection thread. This object's lock is used to
1589 * perform synchronization with the thread (notifying it to run).
1590 */
1591 final Thread mProcessCpuThread;

进程使用cpu跟踪相关

 1593    /**
1594 * Used to collect per-process CPU use for ANRs, battery stats, etc.
1595 * Must acquire this object's lock when accessing it.
1596 * NOTE: this lock will be held while doing long operations (trawling
1597 * through all processes in /proc), so it should never be acquired by
1598 * any critical paths such as when holding the main activity manager lock.
1599 */
1600 final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker(
1601 MONITOR_THREAD_CPU_USAGE);
1602 final AtomicLong mLastCpuTime = new AtomicLong(0);
1603 final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true);
1604 final CountDownLatch mProcessCpuInitLatch = new CountDownLatch(1);

上一次写入时间

 1606    long mLastWriteTime = 0;

更新锁

 1608    /**
1609 * Used to retain an update lock when the foreground activity is in
1610 * immersive mode.
1611 */
1612 final UpdateLock mUpdateLock = new UpdateLock("immersive");

是否完成boot

 1614    /**
1615 * Set to true after the system has finished booting.
1616 */
1617 boolean mBooted = false;

Window Manger Service和System Server所在ActivityThread

 1619    WindowManagerService mWindowManager;
1620 final ActivityThread mSystemThread;

app死亡通知

 1622    private final class AppDeathRecipient implements IBinder.DeathRecipient {
1623 final ProcessRecord mApp;
1624 final int mPid;
1625 final IApplicationThread mAppThread;
1626
1627 AppDeathRecipient(ProcessRecord app, int pid,
1628 IApplicationThread thread) {
1629 if (DEBUG_ALL) Slog.v(
1630 TAG, "New death recipient " + this
1631 + " for thread " + thread.asBinder());
1632 mApp = app;
1633 mPid = pid;
1634 mAppThread = thread;
1635 }
1636
1637 @Override
1638 public void binderDied() {
1639 if (DEBUG_ALL) Slog.v(
1640 TAG, "Death received in " + this
1641 + " for thread " + mAppThread.asBinder());
1642 synchronized(ActivityManagerService.this) {
1643 appDiedLocked(mApp, mPid, mAppThread, true);
1644 }
1645 }
1646 }

ui handler消息

 1648    static final int SHOW_ERROR_UI_MSG = 1;
1649 static final int SHOW_NOT_RESPONDING_UI_MSG = 2;
1650 static final int SHOW_FACTORY_ERROR_UI_MSG = 3;
1651 static final int UPDATE_CONFIGURATION_MSG = 4;
1652 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
1653 static final int WAIT_FOR_DEBUGGER_UI_MSG = 6;
1654 static final int SERVICE_TIMEOUT_MSG = 12;
1655 static final int UPDATE_TIME_ZONE = 13;
1656 static final int SHOW_UID_ERROR_UI_MSG = 14;
1657 static final int SHOW_FINGERPRINT_ERROR_UI_MSG = 15;
1658 static final int PROC_START_TIMEOUT_MSG = 20;
1659 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
1660 static final int KILL_APPLICATION_MSG = 22;
1661 static final int FINALIZE_PENDING_INTENT_MSG = 23;
1662 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
1663 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
1664 static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26;
1665 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
1666 static final int CLEAR_DNS_CACHE_MSG = 28;
1667 static final int UPDATE_HTTP_PROXY_MSG = 29;
1668 static final int SHOW_COMPAT_MODE_DIALOG_UI_MSG = 30;
1669 static final int DISPATCH_PROCESSES_CHANGED_UI_MSG = 31;
1670 static final int DISPATCH_PROCESS_DIED_UI_MSG = 32;
1671 static final int REPORT_MEM_USAGE_MSG = 33;
1672 static final int REPORT_USER_SWITCH_MSG = 34;
1673 static final int CONTINUE_USER_SWITCH_MSG = 35;
1674 static final int USER_SWITCH_TIMEOUT_MSG = 36;
1675 static final int IMMERSIVE_MODE_LOCK_MSG = 37;
1676 static final int PERSIST_URI_GRANTS_MSG = 38;
1677 static final int REQUEST_ALL_PSS_MSG = 39;
1678 static final int START_PROFILES_MSG = 40;
1679 static final int UPDATE_TIME_PREFERENCE_MSG = 41;
1680 static final int SYSTEM_USER_START_MSG = 42;
1681 static final int SYSTEM_USER_CURRENT_MSG = 43;
1682 static final int ENTER_ANIMATION_COMPLETE_MSG = 44;
1683 static final int FINISH_BOOTING_MSG = 45;
1684 static final int START_USER_SWITCH_UI_MSG = 46;
1685 static final int SEND_LOCALE_TO_MOUNT_DAEMON_MSG = 47;
1686 static final int DISMISS_DIALOG_UI_MSG = 48;
1687 static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 49;
1688 static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 50;
1689 static final int DELETE_DUMPHEAP_MSG = 51;
1690 static final int FOREGROUND_PROFILE_CHANGED_MSG = 52;
1691 static final int DISPATCH_UIDS_CHANGED_UI_MSG = 53;
1692 static final int REPORT_TIME_TRACKER_MSG = 54;
1693 static final int REPORT_USER_SWITCH_COMPLETE_MSG = 55;
1694 static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 56;
1695 static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 57;
1696 static final int IDLE_UIDS_MSG = 58;
1697 static final int SYSTEM_USER_UNLOCK_MSG = 59;
1698 static final int LOG_STACK_STATE = 60;
1699 static final int VR_MODE_CHANGE_MSG = 61;
1700 static final int SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG = 62;
1701 static final int HANDLE_TRUST_STORAGE_UPDATE_MSG = 63;
1702 static final int REPORT_LOCKED_BOOT_COMPLETE_MSG = 64;
1703 static final int NOTIFY_VR_SLEEPING_MSG = 65;
1704 static final int SERVICE_FOREGROUND_TIMEOUT_MSG = 66;
1705 static final int DISPATCH_PENDING_INTENT_CANCEL_MSG = 67;
1706 static final int PUSH_TEMP_WHITELIST_UI_MSG = 68;
1707 static final int SERVICE_FOREGROUND_CRASH_MSG = 69;
1708 static final int START_USER_SWITCH_FG_MSG = 712;

第一个activity stack,broadcast queue,compat mode,supervisor stack消息

 1710    static final int FIRST_ACTIVITY_STACK_MSG = 100;
1711 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
1712 static final int FIRST_COMPAT_MODE_MSG = 300;
1713 static final int FIRST_SUPERVISOR_STACK_MSG = 100;

kill thread和其上的handler

 1715    static ServiceThread sKillThread = null;
1716 static KillHandler sKillHandler = null;
1717

兼容模式对话框,不支持的显示size对话框,上一次内存使用报告时间

 1718    CompatModeDialog mCompatModeDialog;
1719 UnsupportedDisplaySizeDialog mUnsupportedDisplaySizeDialog;
1720 long mLastMemUsageReportTime = 0;

用户是否是monkey

 1722    /**
1723 * Flag whether the current user is a "monkey", i.e. whether
1724 * the UI is driven by a UI automation tool.
1725 */
1726 private boolean mUserIsMonkey;

是否有recent UI

 1728    /** Flag whether the device has a Recents UI */
1729 boolean mHasRecents;

thumb尺寸

 1731    /** The dimensions of the thumbnails in the Recents UI. */
1732 int mThumbnailWidth;
1733 int mThumbnailHeight;
1734 float mFullscreenThumbnailScale;

main handler所在线程,main hander,ui handler

 1736    final ServiceThread mHandlerThread;
1737 final MainHandler mHandler;
1738 final Handler mUiHandler;

ams常量

 1740    final ActivityManagerConstants mConstants;

内部包管理器

 1742    PackageManagerInternal mPackageManagerInt;

voice回话id

 1744    // VoiceInteraction session ID that changes for each new request except when
1745 // being called for multiwindow assist in a single session.
1746 private int mViSessionId = 1000;

权限审查是否需要

 1748    final boolean mPermissionReviewRequired;

获取全局配置

 1750    /**
1751 * Current global configuration information. Contains general settings for the entire system,
1752 * also corresponds to the merged configuration of the default display.
1753 */
1754 Configuration getGlobalConfiguration() {
1755 return mStackSupervisor.getConfiguration();
1756 }
1757

获取全局配置

 1750    /**
1751 * Current global configuration information. Contains general settings for the entire system,
1752 * also corresponds to the merged configuration of the default display.
1753 */
1754 Configuration getGlobalConfiguration() {
1755 return mStackSupervisor.getConfiguration();
1756 }
1757

杀进程handler

 1758    final class KillHandler extends Handler {
1759 static final int KILL_PROCESS_GROUP_MSG = 4000;
1760
1761 public KillHandler(Looper looper) {
1762 super(looper, null, true);
1763 }
1764
1765 @Override
1766 public void handleMessage(Message msg) {
1767 switch (msg.what) {
1768 case KILL_PROCESS_GROUP_MSG:
1769 {
1770 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "killProcessGroup");
1771 Process.killProcessGroup(msg.arg1 /* uid */, msg.arg2 /* pid */);
1772 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1773 }
1774 break;
1775
1776 default:
1777 super.handleMessage(msg);
1778 }
1779 }
1780 }
1781

UI handler

 1782    final class UiHandler extends Handler {
1783 public UiHandler() {
1784 super(com.android.server.UiThread.get().getLooper(), null, true);
1785 }
1786
1787 @Override
1788 public void handleMessage(Message msg) {
1789 switch (msg.what) {
1790 case SHOW_ERROR_UI_MSG: {
1791 mAppErrors.handleShowAppErrorUi(msg);
1792 ensureBootCompleted();
1793 } break;
1794 case SHOW_NOT_RESPONDING_UI_MSG: {
1795 mAppErrors.handleShowAnrUi(msg);
1796 ensureBootCompleted();
1797 } break;
1798 case SHOW_STRICT_MODE_VIOLATION_UI_MSG: {
1799 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1800 synchronized (ActivityManagerService.this) {
1801 ProcessRecord proc = (ProcessRecord) data.get("app");
1802 if (proc == null) {
1803 Slog.e(TAG, "App not found when showing strict mode dialog.");
1804 break;
1805 }
1806 if (proc.crashDialog != null) {
1807 Slog.e(TAG, "App already has strict mode dialog: " + proc);
1808 return;
1809 }
1810 AppErrorResult res = (AppErrorResult) data.get("result");
1811 if (mShowDialogs && !mSleeping && !mShuttingDown) {
1812 Dialog d = new StrictModeViolationDialog(mUiContext,
1813 ActivityManagerService.this, res, proc);
1814 d.show();
1815 proc.crashDialog = d;
1816 } else {
1817 // The device is asleep, so just pretend that the user
1818 // saw a crash dialog and hit "force quit".
1819 res.set(0);
1820 }
1821 }
1822 ensureBootCompleted();
1823 } break;
1824 case SHOW_FACTORY_ERROR_UI_MSG: {
1825 Dialog d = new FactoryErrorDialog(
1826 mUiContext, msg.getData().getCharSequence("msg"));
1827 d.show();
1828 ensureBootCompleted();
1829 } break;
1830 case WAIT_FOR_DEBUGGER_UI_MSG: {
1831 synchronized (ActivityManagerService.this) {
1832 ProcessRecord app = (ProcessRecord)msg.obj;
1833 if (msg.arg1 != 0) {
1834 if (!app.waitedForDebugger) {
1835 Dialog d = new AppWaitingForDebuggerDialog(
1836 ActivityManagerService.this,
1837 mUiContext, app);
1838 app.waitDialog = d;
1839 app.waitedForDebugger = true;
1840 d.show();
1841 }
1842 } else {
1843 if (app.waitDialog != null) {
1844 app.waitDialog.dismiss();
1845 app.waitDialog = null;
1846 }
1847 }
1848 }
1849 } break;
1850 case SHOW_UID_ERROR_UI_MSG: {
1851 if (mShowDialogs) {
1852 AlertDialog d = new BaseErrorDialog(mUiContext);
1853 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1854 d.setCancelable(false);
1855 d.setTitle(mUiContext.getText(R.string.android_system_label));
1856 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
1857 d.setButton(DialogInterface.BUTTON_POSITIVE, mUiContext.getText(R.string.ok),
1858 obtainMessage(DISMISS_DIALOG_UI_MSG, d));
1859 d.show();
1860 }
1861 } break;
1862 case SHOW_FINGERPRINT_ERROR_UI_MSG: {
1863 if (mShowDialogs) {
1864 AlertDialog d = new BaseErrorDialog(mUiContext);
1865 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1866 d.setCancelable(false);
1867 d.setTitle(mUiContext.getText(R.string.android_system_label));
1868 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
1869 d.setButton(DialogInterface.BUTTON_POSITIVE, mUiContext.getText(R.string.ok),
1870 obtainMessage(DISMISS_DIALOG_UI_MSG, d));
1871 d.show();
1872 }
1873 } break;
1874 case SHOW_COMPAT_MODE_DIALOG_UI_MSG: {
1875 synchronized (ActivityManagerService.this) {
1876 ActivityRecord ar = (ActivityRecord) msg.obj;
1877 if (mCompatModeDialog != null) {
1878 if (mCompatModeDialog.mAppInfo.packageName.equals(
1879 ar.info.applicationInfo.packageName)) {
1880 return;
1881 }
1882 mCompatModeDialog.dismiss();
1883 mCompatModeDialog = null;
1884 }
1885 if (ar != null && false) {
1886 if (mCompatModePackages.getPackageAskCompatModeLocked(
1887 ar.packageName)) {
1888 int mode = mCompatModePackages.computeCompatModeLocked(
1889 ar.info.applicationInfo);
1890 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1891 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1892 mCompatModeDialog = new CompatModeDialog(
1893 ActivityManagerService.this, mUiContext,
1894 ar.info.applicationInfo);
1895 mCompatModeDialog.show();
1896 }
1897 }
1898 }
1899 }
1900 break;
1901 }
1902 case SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG: {
1903 synchronized (ActivityManagerService.this) {
1904 final ActivityRecord ar = (ActivityRecord) msg.obj;
1905 if (mUnsupportedDisplaySizeDialog != null) {
1906 mUnsupportedDisplaySizeDialog.dismiss();
1907 mUnsupportedDisplaySizeDialog = null;
1908 }
1909 if (ar != null && mCompatModePackages.getPackageNotifyUnsupportedZoomLocked(
1910 ar.packageName)) {
1911 // TODO(multi-display): Show dialog on appropriate display.
1912 mUnsupportedDisplaySizeDialog = new UnsupportedDisplaySizeDialog(
1913 ActivityManagerService.this, mUiContext, ar.info.applicationInfo);
1914 mUnsupportedDisplaySizeDialog.show();
1915 }
1916 }
1917 break;
1918 }
1919 case START_USER_SWITCH_UI_MSG: {
1920 mUserController.showUserSwitchDialog((Pair<UserInfo, UserInfo>) msg.obj);
1921 break;
1922 }
1923 case DISMISS_DIALOG_UI_MSG: {
1924 final Dialog d = (Dialog) msg.obj;
1925 d.dismiss();
1926 break;
1927 }
1928 case DISPATCH_PROCESSES_CHANGED_UI_MSG: {
1929 dispatchProcessesChanged();
1930 break;
1931 }
1932 case DISPATCH_PROCESS_DIED_UI_MSG: {
1933 final int pid = msg.arg1;
1934 final int uid = msg.arg2;
1935 dispatchProcessDied(pid, uid);
1936 break;
1937 }
1938 case DISPATCH_UIDS_CHANGED_UI_MSG: {
1939 dispatchUidsChanged();
1940 } break;
1941 case PUSH_TEMP_WHITELIST_UI_MSG: {
1942 pushTempWhitelist();
1943 } break;
1944 }
1945 }
1946 }

主handler

 1948    final class MainHandler extends Handler {
1949 public MainHandler(Looper looper) {
1950 super(looper, null, true);
1951 }
1952
1953 @Override
1954 public void handleMessage(Message msg) {
1955 switch (msg.what) {
1956 case UPDATE_CONFIGURATION_MSG: {
1957 final ContentResolver resolver = mContext.getContentResolver();
1958 Settings.System.putConfigurationForUser(resolver, (Configuration) msg.obj,
1959 msg.arg1);
1960 } break;
1961 case GC_BACKGROUND_PROCESSES_MSG: {
1962 synchronized (ActivityManagerService.this) {
1963 performAppGcsIfAppropriateLocked();
1964 }
1965 } break;
1966 case SERVICE_TIMEOUT_MSG: {
1967 if (mDidDexOpt) {
1968 mDidDexOpt = false;
1969 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1970 nmsg.obj = msg.obj;
1971 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
1972 return;
1973 }
1974 mServices.serviceTimeout((ProcessRecord)msg.obj);
1975 } break;
1976 case SERVICE_FOREGROUND_TIMEOUT_MSG: {
1977 mServices.serviceForegroundTimeout((ServiceRecord)msg.obj);
1978 } break;
1979 case SERVICE_FOREGROUND_CRASH_MSG: {
1980 mServices.serviceForegroundCrash((ProcessRecord)msg.obj);
1981 } break;
1982 case DISPATCH_PENDING_INTENT_CANCEL_MSG: {
1983 RemoteCallbackList<IResultReceiver> callbacks
1984 = (RemoteCallbackList<IResultReceiver>)msg.obj;
1985 int N = callbacks.beginBroadcast();
1986 for (int i = 0; i < N; i++) {
1987 try {
1988 callbacks.getBroadcastItem(i).send(Activity.RESULT_CANCELED, null);
1989 } catch (RemoteException e) {
1990 }
1991 }
1992 callbacks.finishBroadcast();
1993 } break;
1994 case UPDATE_TIME_ZONE: {
1995 synchronized (ActivityManagerService.this) {
1996 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1997 ProcessRecord r = mLruProcesses.get(i);
1998 if (r.thread != null) {
1999 try {
2000 r.thread.updateTimeZone();
2001 } catch (RemoteException ex) {
2002 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
2003 }
2004 }
2005 }
2006 }
2007 } break;
2008 case CLEAR_DNS_CACHE_MSG: {
2009 synchronized (ActivityManagerService.this) {
2010 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
2011 ProcessRecord r = mLruProcesses.get(i);
2012 if (r.thread != null) {
2013 try {
2014 r.thread.clearDnsCache();
2015 } catch (RemoteException ex) {
2016 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
2017 }
2018 }
2019 }
2020 }
2021 } break;
2022 case UPDATE_HTTP_PROXY_MSG: {
2023 ProxyInfo proxy = (ProxyInfo)msg.obj;
2024 String host = "";
2025 String port = "";
2026 String exclList = "";
2027 Uri pacFileUrl = Uri.EMPTY;
2028 if (proxy != null) {
2029 host = proxy.getHost();
2030 port = Integer.toString(proxy.getPort());
2031 exclList = proxy.getExclusionListAsString();
2032 pacFileUrl = proxy.getPacFileUrl();
2033 }
2034 synchronized (ActivityManagerService.this) {
2035 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
2036 ProcessRecord r = mLruProcesses.get(i);
2037 if (r.thread != null) {
2038 try {
2039 r.thread.setHttpProxy(host, port, exclList, pacFileUrl);
2040 } catch (RemoteException ex) {
2041 Slog.w(TAG, "Failed to update http proxy for: " +
2042 r.info.processName);
2043 }
2044 }
2045 }
2046 }
2047 } break;
2048 case PROC_START_TIMEOUT_MSG: {
2049 if (mDidDexOpt) {
2050 mDidDexOpt = false;
2051 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2052 nmsg.obj = msg.obj;
2053 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
2054 return;
2055 }
2056 ProcessRecord app = (ProcessRecord)msg.obj;
2057 synchronized (ActivityManagerService.this) {
2058 processStartTimedOutLocked(app);
2059 }
2060 } break;
2061 case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: {
2062 ProcessRecord app = (ProcessRecord)msg.obj;
2063 synchronized (ActivityManagerService.this) {
2064 processContentProviderPublishTimedOutLocked(app);
2065 }
2066 } break;
2067 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
2068 synchronized (ActivityManagerService.this) {
2069 mActivityStarter.doPendingActivityLaunchesLocked(true);
2070 }
2071 } break;
2072 case KILL_APPLICATION_MSG: {
2073 synchronized (ActivityManagerService.this) {
2074 final int appId = msg.arg1;
2075 final int userId = msg.arg2;
2076 Bundle bundle = (Bundle)msg.obj;
2077 String pkg = bundle.getString("pkg");
2078 String reason = bundle.getString("reason");
2079 forceStopPackageLocked(pkg, appId, false, false, true, false,
2080 false, userId, reason);
2081 }
2082 } break;
2083 case FINALIZE_PENDING_INTENT_MSG: {
2084 ((PendingIntentRecord)msg.obj).completeFinalize();
2085 } break;
2086 case POST_HEAVY_NOTIFICATION_MSG: {
2087 INotificationManager inm = NotificationManager.getService();
2088 if (inm == null) {
2089 return;
2090 }
2091
2092 ActivityRecord root = (ActivityRecord)msg.obj;
2093 ProcessRecord process = root.app;
2094 if (process == null) {
2095 return;
2096 }
2097
2098 try {
2099 Context context = mContext.createPackageContext(process.info.packageName, 0);
2100 String text = mContext.getString(R.string.heavy_weight_notification,
2101 context.getApplicationInfo().loadLabel(context.getPackageManager()));
2102 Notification notification =
2103 new Notification.Builder(context, SystemNotificationChannels.DEVELOPER)
2104 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
2105 .setWhen(0)
2106 .setOngoing(true)
2107 .setTicker(text)
2108 .setColor(mContext.getColor(
2109 com.android.internal.R.color.system_notification_accent_color))
2110 .setContentTitle(text)
2111 .setContentText(
2112 mContext.getText(R.string.heavy_weight_notification_detail))
2113 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
2114 root.intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
2115 new UserHandle(root.userId)))
2116 .build();
2117 try {
2118 inm.enqueueNotificationWithTag("android", "android", null,
2119 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION,
2120 notification, root.userId);
2121 } catch (RuntimeException e) {
2122 Slog.w(ActivityManagerService.TAG,
2123 "Error showing notification for heavy-weight app", e);
2124 } catch (RemoteException e) {
2125 }
2126 } catch (NameNotFoundException e) {
2127 Slog.w(TAG, "Unable to create context for heavy notification", e);
2128 }
2129 } break;
2130 case CANCEL_HEAVY_NOTIFICATION_MSG: {
2131 INotificationManager inm = NotificationManager.getService();
2132 if (inm == null) {
2133 return;
2134 }
2135 try {
2136 inm.cancelNotificationWithTag("android", null,
2137 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, msg.arg1);
2138 } catch (RuntimeException e) {
2139 Slog.w(ActivityManagerService.TAG,
2140 "Error canceling notification for service", e);
2141 } catch (RemoteException e) {
2142 }
2143 } break;
2144 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
2145 synchronized (ActivityManagerService.this) {
2146 checkExcessivePowerUsageLocked(true);
2147 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
2148 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
2149 sendMessageDelayed(nmsg, mConstants.POWER_CHECK_DELAY);
2150 }
2151 } break;
2152 case REPORT_MEM_USAGE_MSG: {
2153 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj;
2154 Thread thread = new Thread() {
2155 @Override public void run() {
2156 reportMemUsage(memInfos);
2157 }
2158 };
2159 thread.start();
2160 break;
2161 }
2162 case START_USER_SWITCH_FG_MSG: {
2163 mUserController.startUserInForeground(msg.arg1);
2164 break;
2165 }
2166 case REPORT_USER_SWITCH_MSG: {
2167 mUserController.dispatchUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2);
2168 break;
2169 }
2170 case CONTINUE_USER_SWITCH_MSG: {
2171 mUserController.continueUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2);
2172 break;
2173 }
2174 case USER_SWITCH_TIMEOUT_MSG: {
2175 mUserController.timeoutUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2);
2176 break;
2177 }
2178 case IMMERSIVE_MODE_LOCK_MSG: {
2179 final boolean nextState = (msg.arg1 != 0);
2180 if (mUpdateLock.isHeld() != nextState) {
2181 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
2182 "Applying new update lock state '" + nextState
2183 + "' for " + (ActivityRecord)msg.obj);
2184 if (nextState) {
2185 mUpdateLock.acquire();
2186 } else {
2187 mUpdateLock.release();
2188 }
2189 }
2190 break;
2191 }
2192 case PERSIST_URI_GRANTS_MSG: {
2193 writeGrantedUriPermissions();
2194 break;
2195 }
2196 case REQUEST_ALL_PSS_MSG: {
2197 synchronized (ActivityManagerService.this) {
2198 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
2199 }
2200 break;
2201 }
2202 case START_PROFILES_MSG: {
2203 synchronized (ActivityManagerService.this) {
2204 mUserController.startProfilesLocked();
2205 }
2206 break;
2207 }
2208 case UPDATE_TIME_PREFERENCE_MSG: {
2209 // The user's time format preference might have changed.
2210 // For convenience we re-use the Intent extra values.
2211 synchronized (ActivityManagerService.this) {
2212 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
2213 ProcessRecord r = mLruProcesses.get(i);
2214 if (r.thread != null) {
2215 try {
2216 r.thread.updateTimePrefs(msg.arg1);
2217 } catch (RemoteException ex) {
2218 Slog.w(TAG, "Failed to update preferences for: "
2219 + r.info.processName);
2220 }
2221 }
2222 }
2223 }
2224 break;
2225 }
2226 case SYSTEM_USER_START_MSG: {
2227 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
2228 Integer.toString(msg.arg1), msg.arg1);
2229 mSystemServiceManager.startUser(msg.arg1);
2230 break;
2231 }
2232 case SYSTEM_USER_UNLOCK_MSG: {
2233 final int userId = msg.arg1;
2234 mSystemServiceManager.unlockUser(userId);
2235 synchronized (ActivityManagerService.this) {
2236 mRecentTasks.loadUserRecentsLocked(userId);
2237 }
2238 if (userId == UserHandle.USER_SYSTEM) {
2239 startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
2240 }
2241 installEncryptionUnawareProviders(userId);
2242 mUserController.finishUserUnlocked((UserState) msg.obj);
2243 break;
2244 }
2245 case SYSTEM_USER_CURRENT_MSG: {
2246 mBatteryStatsService.noteEvent(
2247 BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_FINISH,
2248 Integer.toString(msg.arg2), msg.arg2);
2249 mBatteryStatsService.noteEvent(
2250 BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
2251 Integer.toString(msg.arg1), msg.arg1);
2252 mSystemServiceManager.switchUser(msg.arg1);
2253 break;
2254 }
2255 case ENTER_ANIMATION_COMPLETE_MSG: {
2256 synchronized (ActivityManagerService.this) {
2257 ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
2258 if (r != null && r.app != null && r.app.thread != null) {
2259 try {
2260 r.app.thread.scheduleEnterAnimationComplete(r.appToken);
2261 } catch (RemoteException e) {
2262 }
2263 }
2264 }
2265 break;
2266 }
2267 case FINISH_BOOTING_MSG: {
2268 if (msg.arg1 != 0) {
2269 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "FinishBooting");
2270 finishBooting();
2271 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2272 }
2273 if (msg.arg2 != 0) {
2274 enableScreenAfterBoot();
2275 }
2276 break;
2277 }
2278 case SEND_LOCALE_TO_MOUNT_DAEMON_MSG: {
2279 try {
2280 Locale l = (Locale) msg.obj;
2281 IBinder service = ServiceManager.getService("mount");
2282 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
2283 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
2284 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
2285 } catch (RemoteException e) {
2286 Log.e(TAG, "Error storing locale for decryption UI", e);
2287 }
2288 break;
2289 }
2290 case NOTIFY_CLEARTEXT_NETWORK_MSG: {
2291 final int uid = msg.arg1;
2292 final byte[] firstPacket = (byte[]) msg.obj;
2293
2294 synchronized (mPidsSelfLocked) {
2295 for (int i = 0; i < mPidsSelfLocked.size(); i++) {
2296 final ProcessRecord p = mPidsSelfLocked.valueAt(i);
2297 if (p.uid == uid) {
2298 try {
2299 p.thread.notifyCleartextNetwork(firstPacket);
2300 } catch (RemoteException ignored) {
2301 }
2302 }
2303 }
2304 }
2305 break;
2306 }
2307 case POST_DUMP_HEAP_NOTIFICATION_MSG: {
2308 final String procName;
2309 final int uid;
2310 final long memLimit;
2311 final String reportPackage;
2312 synchronized (ActivityManagerService.this) {
2313 procName = mMemWatchDumpProcName;
2314 uid = mMemWatchDumpUid;
2315 Pair<Long, String> val = mMemWatchProcesses.get(procName, uid);
2316 if (val == null) {
2317 val = mMemWatchProcesses.get(procName, 0);
2318 }
2319 if (val != null) {
2320 memLimit = val.first;
2321 reportPackage = val.second;
2322 } else {
2323 memLimit = 0;
2324 reportPackage = null;
2325 }
2326 }
2327 if (procName == null) {
2328 return;
2329 }
2330
2331 if (DEBUG_PSS) Slog.d(TAG_PSS,
2332 "Showing dump heap notification from " + procName + "/" + uid);
2333
2334 INotificationManager inm = NotificationManager.getService();
2335 if (inm == null) {
2336 return;
2337 }
2338
2339 String text = mContext.getString(R.string.dump_heap_notification, procName);
2340
2341
2342 Intent deleteIntent = new Intent();
2343 deleteIntent.setAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP);
2344 Intent intent = new Intent();
2345 intent.setClassName("android", DumpHeapActivity.class.getName());
2346 intent.putExtra(DumpHeapActivity.KEY_PROCESS, procName);
2347 intent.putExtra(DumpHeapActivity.KEY_SIZE, memLimit);
2348 if (reportPackage != null) {
2349 intent.putExtra(DumpHeapActivity.KEY_DIRECT_LAUNCH, reportPackage);
2350 }
2351 int userId = UserHandle.getUserId(uid);
2352 Notification notification =
2353 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER)
2354 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
2355 .setWhen(0)
2356 .setOngoing(true)
2357 .setAutoCancel(true)
2358 .setTicker(text)
2359 .setColor(mContext.getColor(
2360 com.android.internal.R.color.system_notification_accent_color))
2361 .setContentTitle(text)
2362 .setContentText(
2363 mContext.getText(R.string.dump_heap_notification_detail))
2364 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
2365 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
2366 new UserHandle(userId)))
2367 .setDeleteIntent(PendingIntent.getBroadcastAsUser(mContext, 0,
2368 deleteIntent, 0, UserHandle.SYSTEM))
2369 .build();
2370
2371 try {
2372 inm.enqueueNotificationWithTag("android", "android", null,
2373 SystemMessage.NOTE_DUMP_HEAP_NOTIFICATION,
2374 notification, userId);
2375 } catch (RuntimeException e) {
2376 Slog.w(ActivityManagerService.TAG,
2377 "Error showing notification for dump heap", e);
2378 } catch (RemoteException e) {
2379 }
2380 } break;
2381 case DELETE_DUMPHEAP_MSG: {
2382 revokeUriPermission(ActivityThread.currentActivityThread().getApplicationThread(),
2383 null, DumpHeapActivity.JAVA_URI,
2384 Intent.FLAG_GRANT_READ_URI_PERMISSION
2385 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
2386 UserHandle.myUserId());
2387 synchronized (ActivityManagerService.this) {
2388 mMemWatchDumpFile = null;
2389 mMemWatchDumpProcName = null;
2390 mMemWatchDumpPid = -1;
2391 mMemWatchDumpUid = -1;
2392 }
2393 } break;
2394 case FOREGROUND_PROFILE_CHANGED_MSG: {
2395 mUserController.dispatchForegroundProfileChanged(msg.arg1);
2396 } break;
2397 case REPORT_TIME_TRACKER_MSG: {
2398 AppTimeTracker tracker = (AppTimeTracker)msg.obj;
2399 tracker.deliverResult(mContext);
2400 } break;
2401 case REPORT_USER_SWITCH_COMPLETE_MSG: {
2402 mUserController.dispatchUserSwitchComplete(msg.arg1);
2403 } break;
2404 case REPORT_LOCKED_BOOT_COMPLETE_MSG: {
2405 mUserController.dispatchLockedBootComplete(msg.arg1);
2406 } break;
2407 case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: {
2408 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj;
2409 try {
2410 connection.shutdown();
2411 } catch (RemoteException e) {
2412 Slog.w(TAG, "Error shutting down UiAutomationConnection");
2413 }
2414 // Only a UiAutomation can set this flag and now that
2415 // it is finished we make sure it is reset to its default.
2416 mUserIsMonkey = false;
2417 } break;
2418 case IDLE_UIDS_MSG: {
2419 idleUids();
2420 } break;
2421 case VR_MODE_CHANGE_MSG: {
2422 if (!mVrController.onVrModeChanged((ActivityRecord) msg.obj)) {
2423 return;
2424 }
2425 synchronized (ActivityManagerService.this) {
2426 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
2427 mWindowManager.disableNonVrUi(disableNonVrUi);
2428 if (disableNonVrUi) {
2429 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
2430 // then remove the pinned stack.
2431 final PinnedActivityStack pinnedStack = mStackSupervisor.getStack(
2432 PINNED_STACK_ID);
2433 if (pinnedStack != null) {
2434 mStackSupervisor.removeStackLocked(PINNED_STACK_ID);
2435 }
2436 }
2437 }
2438 } break;
2439 case NOTIFY_VR_SLEEPING_MSG: {
2440 notifyVrManagerOfSleepState(msg.arg1 != 0);
2441 } break;
2442 case HANDLE_TRUST_STORAGE_UPDATE_MSG: {
2443 synchronized (ActivityManagerService.this) {
2444 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
2445 ProcessRecord r = mLruProcesses.get(i);
2446 if (r.thread != null) {
2447 try {
2448 r.thread.handleTrustStorageUpdate();
2449 } catch (RemoteException ex) {
2450 Slog.w(TAG, "Failed to handle trust storage update for: " +
2451 r.info.processName);
2452 }
2453 }
2454 }
2455 }
2456 } break;
2457 }
2458 }
2459 };

后台收集pss消息

 2461    static final int COLLECT_PSS_BG_MSG = 1;

bg handler

 2463    final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) {
2464 @Override
2465 public void handleMessage(Message msg) {
2466 switch (msg.what) {
2467 case COLLECT_PSS_BG_MSG: {
2468 long start = SystemClock.uptimeMillis();
2469 MemInfoReader memInfo = null;
2470 synchronized (ActivityManagerService.this) {
2471 if (mFullPssPending) {
2472 mFullPssPending = false;
2473 memInfo = new MemInfoReader();
2474 }
2475 }
2476 if (memInfo != null) {
2477 updateCpuStatsNow();
2478 long nativeTotalPss = 0;
2479 final List<ProcessCpuTracker.Stats> stats;
2480 synchronized (mProcessCpuTracker) {
2481 stats = mProcessCpuTracker.getStats( (st)-> {
2482 return st.vsize > 0 && st.uid < FIRST_APPLICATION_UID;
2483 });
2484 }
2485 final int N = stats.size();
2486 for (int j = 0; j < N; j++) {
2487 synchronized (mPidsSelfLocked) {
2488 if (mPidsSelfLocked.indexOfKey(stats.get(j).pid) >= 0) {
2489 // This is one of our own processes; skip it.
2490 continue;
2491 }
2492 }
2493 nativeTotalPss += Debug.getPss(stats.get(j).pid, null, null);
2494 }
2495 memInfo.readMemInfo();
2496 synchronized (ActivityManagerService.this) {
2497 if (DEBUG_PSS) Slog.d(TAG_PSS, "Collected native and kernel memory in "
2498 + (SystemClock.uptimeMillis()-start) + "ms");
2499 final long cachedKb = memInfo.getCachedSizeKb();
2500 final long freeKb = memInfo.getFreeSizeKb();
2501 final long zramKb = memInfo.getZramTotalSizeKb();
2502 final long kernelKb = memInfo.getKernelUsedSizeKb();
2503 EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024,
2504 kernelKb*1024, nativeTotalPss*1024);
2505 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
2506 nativeTotalPss);
2507 }
2508 }
2509
2510 int num = 0;
2511 long[] tmp = new long[2];
2512 do {
2513 ProcessRecord proc;
2514 int procState;
2515 int pid;
2516 long lastPssTime;
2517 synchronized (ActivityManagerService.this) {
2518 if (mPendingPssProcesses.size() <= 0) {
2519 if (mTestPssMode || DEBUG_PSS) Slog.d(TAG_PSS,
2520 "Collected PSS of " + num + " processes in "
2521 + (SystemClock.uptimeMillis() - start) + "ms");
2522 mPendingPssProcesses.clear();
2523 return;
2524 }
2525 proc = mPendingPssProcesses.remove(0);
2526 procState = proc.pssProcState;
2527 lastPssTime = proc.lastPssTime;
2528 if (proc.thread != null && procState == proc.setProcState
2529 && (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE)
2530 < SystemClock.uptimeMillis()) {
2531 pid = proc.pid;
2532 } else {
2533 proc = null;
2534 pid = 0;
2535 }
2536 }
2537 if (proc != null) {
2538 long pss = Debug.getPss(pid, tmp, null);
2539 synchronized (ActivityManagerService.this) {
2540 if (pss != 0 && proc.thread != null && proc.setProcState == procState
2541 && proc.pid == pid && proc.lastPssTime == lastPssTime) {
2542 num++;
2543 recordPssSampleLocked(proc, procState, pss, tmp[0], tmp[1],
2544 SystemClock.uptimeMillis());
2545 }
2546 }
2547 }
2548 } while (true);
2549 }
2550 }
2551 }
2552 };

设置为系统进程

 2554    public void setSystemProcess() {
2555 try {
2556 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
2557 ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
2558 ServiceManager.addService("meminfo", new MemBinder(this));
2559 ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
2560 ServiceManager.addService("dbinfo", new DbBinder(this));
2561 if (MONITOR_CPU_USAGE) {
2562 ServiceManager.addService("cpuinfo", new CpuBinder(this));
2563 }
2564 ServiceManager.addService("permission", new PermissionController(this));
2565 ServiceManager.addService("processinfo", new ProcessInfoService(this));
2566
2567 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
2568 "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
2569 mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
2570
2571 synchronized (this) {
2572 ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
2573 app.persistent = true;
2574 app.pid = MY_PID;
2575 app.maxAdj = ProcessList.SYSTEM_ADJ;
2576 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
2577 synchronized (mPidsSelfLocked) {
2578 mPidsSelfLocked.put(app.pid, app);
2579 }
2580 updateLruProcessLocked(app, false, null);
2581 updateOomAdjLocked();
2582 }
2583 } catch (PackageManager.NameNotFoundException e) {
2584 throw new RuntimeException(
2585 "Unable to find android system package", e);
2586 }
2587 }

设置window manager

 2589    public void setWindowManager(WindowManagerService wm) {
2590 mWindowManager = wm;
2591 mStackSupervisor.setWindowManager(wm);
2592 mActivityStarter.setWindowManager(wm);
2593 }

设置usage stats manager

 2595    public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
2596 mUsageStatsService = usageStatsManager;
2597 }

开始观察本地crash;获取app ops service

 2599    public void startObservingNativeCrashes() {
2600 final NativeCrashListener ncl = new NativeCrashListener(this);
2601 ncl.start();
2602 }
2603
2604 public IAppOpsService getAppOpsService() {
2605 return mAppOpsService;
2606 }

mem binder

 2608    static class MemBinder extends Binder {
2609 ActivityManagerService mActivityManagerService;
2610 MemBinder(ActivityManagerService activityManagerService) {
2611 mActivityManagerService = activityManagerService;
2612 }
2613
2614 @Override
2615 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2616 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2617 "meminfo", pw)) return;
2618 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args, false, null);
2619 }
2620 }

graphics binder

 2622    static class GraphicsBinder extends Binder {
2623 ActivityManagerService mActivityManagerService;
2624 GraphicsBinder(ActivityManagerService activityManagerService) {
2625 mActivityManagerService = activityManagerService;
2626 }
2627
2628 @Override
2629 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2630 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2631 "gfxinfo", pw)) return;
2632 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
2633 }
2634 }

db binder

 2636    static class DbBinder extends Binder {
2637 ActivityManagerService mActivityManagerService;
2638 DbBinder(ActivityManagerService activityManagerService) {
2639 mActivityManagerService = activityManagerService;
2640 }
2641
2642 @Override
2643 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2644 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2645 "dbinfo", pw)) return;
2646 mActivityManagerService.dumpDbInfo(fd, pw, args);
2647 }
2648 }

cpu binder

 2650    static class CpuBinder extends Binder {
2651 ActivityManagerService mActivityManagerService;
2652 CpuBinder(ActivityManagerService activityManagerService) {
2653 mActivityManagerService = activityManagerService;
2654 }
2655
2656 @Override
2657 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2658 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2659 "cpuinfo", pw)) return;
2660 synchronized (mActivityManagerService.mProcessCpuTracker) {
2661 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad());
2662 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState(
2663 SystemClock.uptimeMillis()));
2664 }
2665 }
2666 }

lifecycle

 2668    public static final class Lifecycle extends SystemService {
2669 private final ActivityManagerService mService;
2670
2671 public Lifecycle(Context context) {
2672 super(context);
2673 mService = new ActivityManagerService(context);
2674 }
2675
2676 @Override
2677 public void onStart() {
2678 mService.start();
2679 }
2680
2681 public ActivityManagerService getService() {
2682 return mService;
2683 }
2684 }

构造方法

 2686    @VisibleForTesting
2687 public ActivityManagerService(Injector injector) {
2688 mInjector = injector;
2689 mContext = mInjector.getContext();
2690 mUiContext = null;
2691 GL_ES_VERSION = 0;
2692 mActivityStarter = null;
2693 mAppErrors = null;
2694 mAppOpsService = mInjector.getAppOpsService(null, null);
2695 mBatteryStatsService = null;
2696 mCompatModePackages = null;
2697 mConstants = null;
2698 mGrantFile = null;
2699 mHandler = null;
2700 mHandlerThread = null;
2701 mIntentFirewall = null;
2702 mKeyguardController = null;
2703 mPermissionReviewRequired = false;
2704 mProcessCpuThread = null;
2705 mProcessStats = null;
2706 mProviderMap = null;
2707 mRecentTasks = null;
2708 mServices = null;
2709 mStackSupervisor = null;
2710 mSystemThread = null;
2711 mTaskChangeNotificationController = null;
2712 mUiHandler = injector.getUiHandler(null);
2713 mUserController = null;
2714 mVrController = null;
2715 }
2716
2717 // Note: This method is invoked on the main thread but may need to attach various
2718 // handlers to other threads. So take care to be explicit about the looper.
2719 public ActivityManagerService(Context systemContext) {
2720 LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
2721 mInjector = new Injector();
2722 mContext = systemContext;
2723
2724 mFactoryTest = FactoryTest.getMode();
2725 mSystemThread = ActivityThread.currentActivityThread();
2726 mUiContext = mSystemThread.getSystemUiContext();
2727
2728 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
2729
2730 mPermissionReviewRequired = mContext.getResources().getBoolean(
2731 com.android.internal.R.bool.config_permissionReviewRequired);
2732
2733 mHandlerThread = new ServiceThread(TAG,
2734 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
2735 mHandlerThread.start();
2736 mHandler = new MainHandler(mHandlerThread.getLooper());
2737 mUiHandler = mInjector.getUiHandler(this);
2738
2739 mConstants = new ActivityManagerConstants(this, mHandler);
2740
2741 /* static; one-time init here */
2742 if (sKillHandler == null) {
2743 sKillThread = new ServiceThread(TAG + ":kill",
2744 THREAD_PRIORITY_BACKGROUND, true /* allowIo */);
2745 sKillThread.start();
2746 sKillHandler = new KillHandler(sKillThread.getLooper());
2747 }
2748
2749 mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
2750 "foreground", BROADCAST_FG_TIMEOUT, false);
2751 mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
2752 "background", BROADCAST_BG_TIMEOUT, true);
2753 mBroadcastQueues[0] = mFgBroadcastQueue;
2754 mBroadcastQueues[1] = mBgBroadcastQueue;
2755
2756 mServices = new ActiveServices(this);
2757 mProviderMap = new ProviderMap(this);
2758 mAppErrors = new AppErrors(mUiContext, this);
2759
2760 // TODO: Move creation of battery stats service outside of activity manager service.
2761 File dataDir = Environment.getDataDirectory();
2762 File systemDir = new File(dataDir, "system");
2763 systemDir.mkdirs();
2764 mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);
2765 mBatteryStatsService.getActiveStatistics().readLocked();
2766 mBatteryStatsService.scheduleWriteToDisk();
2767 mOnBattery = DEBUG_POWER ? true
2768 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
2769 mBatteryStatsService.getActiveStatistics().setCallback(this);
2770
2771 mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
2772
2773 mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
2774 mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
2775 new IAppOpsCallback.Stub() {
2776 @Override public void opChanged(int op, int uid, String packageName) {
2777 if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
2778 if (mAppOpsService.checkOperation(op, uid, packageName)
2779 != AppOpsManager.MODE_ALLOWED) {
2780 runInBackgroundDisabled(uid);
2781 }
2782 }
2783 }
2784 });
2785
2786 mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));
2787
2788 mUserController = new UserController(this);
2789
2790 mVrController = new VrController(this);
2791
2792 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
2793 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
2794
2795 if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
2796 mUseFifoUiScheduling = true;
2797 }
2798
2799 mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
2800 mTempConfig.setToDefaults();
2801 mTempConfig.setLocales(LocaleList.getDefault());
2802 mConfigurationSeq = mTempConfig.seq = 1;
2803 mStackSupervisor = createStackSupervisor();
2804 mStackSupervisor.onConfigurationChanged(mTempConfig);
2805 mKeyguardController = mStackSupervisor.mKeyguardController;
2806 mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
2807 mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
2808 mTaskChangeNotificationController =
2809 new TaskChangeNotificationController(this, mStackSupervisor, mHandler);
2810 mActivityStarter = new ActivityStarter(this, mStackSupervisor);
2811 mRecentTasks = new RecentTasks(this, mStackSupervisor);
2812
2813 mProcessCpuThread = new Thread("CpuTracker") {
2814 @Override
2815 public void run() {
2816 synchronized (mProcessCpuTracker) {
2817 mProcessCpuInitLatch.countDown();
2818 mProcessCpuTracker.init();
2819 }
2820 while (true) {
2821 try {
2822 try {
2823 synchronized(this) {
2824 final long now = SystemClock.uptimeMillis();
2825 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
2826 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
2827 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
2828 // + ", write delay=" + nextWriteDelay);
2829 if (nextWriteDelay < nextCpuDelay) {
2830 nextCpuDelay = nextWriteDelay;
2831 }
2832 if (nextCpuDelay > 0) {
2833 mProcessCpuMutexFree.set(true);
2834 this.wait(nextCpuDelay);
2835 }
2836 }
2837 } catch (InterruptedException e) {
2838 }
2839 updateCpuStatsNow();
2840 } catch (Exception e) {
2841 Slog.e(TAG, "Unexpected exception collecting process stats", e);
2842 }
2843 }
2844 }
2845 };
2846
2847 Watchdog.getInstance().addMonitor(this);
2848 Watchdog.getInstance().addThread(mHandler);
2849 }
2850

创建stack supervisior

 2851    protected ActivityStackSupervisor createStackSupervisor() {
2852 return new ActivityStackSupervisor(this, mHandler.getLooper());
2853 }

设置System Service Manager

 2855    public void setSystemServiceManager(SystemServiceManager mgr) {
2856 mSystemServiceManager = mgr;
2857 }

设置installer

 2859    public void setInstaller(Installer installer) {
2860 mInstaller = installer;
2861 }

start方法

 2863    private void start() {
2864 removeAllProcessGroups();
2865 mProcessCpuThread.start();
2866
2867 mBatteryStatsService.publish(mContext);
2868 mAppOpsService.publish(mContext);
2869 Slog.d("AppOps", "AppOpsService published");
2870 LocalServices.addService(ActivityManagerInternal.class, new LocalService());
2871 // Wait for the synchronized block started in mProcessCpuThread,
2872 // so that any other acccess to mProcessCpuTracker from main thread
2873 // will be blocked during mProcessCpuTracker initialization.
2874 try {
2875 mProcessCpuInitLatch.await();
2876 } catch (InterruptedException e) {
2877 Slog.wtf(TAG, "Interrupted wait during start", e);
2878 Thread.currentThread().interrupt();
2879 throw new IllegalStateException("Interrupted wait during start");
2880 }
2881 }

用户stop回调

 2883    void onUserStoppedLocked(int userId) {
2884 mRecentTasks.unloadUserDataFromMemoryLocked(userId);
2885 }

初始化power manager

 2887    public void initPowerManagement() {
2888 mStackSupervisor.initPowerManagement();
2889 mBatteryStatsService.initPowerManagement();
2890 mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
2891 PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
2892 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
2893 mVoiceWakeLock.setReferenceCounted(false);
2894 }

获取后台启动广播

 2896    private ArraySet<String> getBackgroundLaunchBroadcasts() {
2897 if (mBackgroundLaunchBroadcasts == null) {
2898 mBackgroundLaunchBroadcasts = SystemConfig.getInstance().getAllowImplicitBroadcasts();
2899 }
2900 return mBackgroundLaunchBroadcasts;
2901 }

onTransact

 2903    @Override
2904 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2905 throws RemoteException {
2906 if (code == SYSPROPS_TRANSACTION) {
2907 // We need to tell all apps about the system property change.
2908 ArrayList<IBinder> procs = new ArrayList<IBinder>();
2909 synchronized(this) {
2910 final int NP = mProcessNames.getMap().size();
2911 for (int ip=0; ip<NP; ip++) {
2912 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
2913 final int NA = apps.size();
2914 for (int ia=0; ia<NA; ia++) {
2915 ProcessRecord app = apps.valueAt(ia);
2916 if (app.thread != null) {
2917 procs.add(app.thread.asBinder());
2918 }
2919 }
2920 }
2921 }
2922
2923 int N = procs.size();
2924 for (int i=0; i<N; i++) {
2925 Parcel data2 = Parcel.obtain();
2926 try {
2927 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null,
2928 Binder.FLAG_ONEWAY);
2929 } catch (RemoteException e) {
2930 }
2931 data2.recycle();
2932 }
2933 }
2934 try {
2935 return super.onTransact(code, data, reply, flags);
2936 } catch (RuntimeException e) {
2937 // The activity manager only throws security exceptions, so let's
2938 // log all others.
2939 if (!(e instanceof SecurityException)) {
2940 Slog.wtf(TAG, "Activity Manager Crash."
2941 + " UID:" + Binder.getCallingUid()
2942 + " PID:" + Binder.getCallingPid()
2943 + " TRANS:" + code, e);
2944 }
2945 throw e;
2946 }
2947 }
2948

更新cpu状态

 2949    void updateCpuStats() {
2950 final long now = SystemClock.uptimeMillis();
2951 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
2952 return;
2953 }
2954 if (mProcessCpuMutexFree.compareAndSet(true, false)) {
2955 synchronized (mProcessCpuThread) {
2956 mProcessCpuThread.notify();
2957 }
2958 }
2959 }
2960
2961 void updateCpuStatsNow() {
2962 synchronized (mProcessCpuTracker) {
2963 mProcessCpuMutexFree.set(false);
2964 final long now = SystemClock.uptimeMillis();
2965 boolean haveNewCpuStats = false;
2966
2967 if (MONITOR_CPU_USAGE &&
2968 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
2969 mLastCpuTime.set(now);
2970 mProcessCpuTracker.update();
2971 if (mProcessCpuTracker.hasGoodLastStats()) {
2972 haveNewCpuStats = true;
2973 //Slog.i(TAG, mProcessCpu.printCurrentState());
2974 //Slog.i(TAG, "Total CPU usage: "
2975 // + mProcessCpu.getTotalCpuPercent() + "%");
2976
2977 // Slog the cpu usage if the property is set.
2978 if ("true".equals(SystemProperties.get("events.cpu"))) {
2979 int user = mProcessCpuTracker.getLastUserTime();
2980 int system = mProcessCpuTracker.getLastSystemTime();
2981 int iowait = mProcessCpuTracker.getLastIoWaitTime();
2982 int irq = mProcessCpuTracker.getLastIrqTime();
2983 int softIrq = mProcessCpuTracker.getLastSoftIrqTime();
2984 int idle = mProcessCpuTracker.getLastIdleTime();
2985
2986 int total = user + system + iowait + irq + softIrq + idle;
2987 if (total == 0) total = 1;
2988
2989 EventLog.writeEvent(EventLogTags.CPU,
2990 ((user+system+iowait+irq+softIrq) * 100) / total,
2991 (user * 100) / total,
2992 (system * 100) / total,
2993 (iowait * 100) / total,
2994 (irq * 100) / total,
2995 (softIrq * 100) / total);
2996 }
2997 }
2998 }
2999
3000 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
3001 synchronized(bstats) {
3002 synchronized(mPidsSelfLocked) {
3003 if (haveNewCpuStats) {
3004 if (bstats.startAddingCpuLocked()) {
3005 int totalUTime = 0;
3006 int totalSTime = 0;
3007 final int N = mProcessCpuTracker.countStats();
3008 for (int i=0; i<N; i++) {
3009 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
3010 if (!st.working) {
3011 continue;
3012 }
3013 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
3014 totalUTime += st.rel_utime;
3015 totalSTime += st.rel_stime;
3016 if (pr != null) {
3017 BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats;
3018 if (ps == null || !ps.isActive()) {
3019 pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked(
3020 pr.info.uid, pr.processName);
3021 }
3022 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
3023 pr.curCpuTime += st.rel_utime + st.rel_stime;
3024 } else {
3025 BatteryStatsImpl.Uid.Proc ps = st.batteryStats;
3026 if (ps == null || !ps.isActive()) {
3027 st.batteryStats = ps = bstats.getProcessStatsLocked(
3028 bstats.mapUid(st.uid), st.name);
3029 }
3030 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
3031 }
3032 }
3033 final int userTime = mProcessCpuTracker.getLastUserTime();
3034 final int systemTime = mProcessCpuTracker.getLastSystemTime();
3035 final int iowaitTime = mProcessCpuTracker.getLastIoWaitTime();
3036 final int irqTime = mProcessCpuTracker.getLastIrqTime();
3037 final int softIrqTime = mProcessCpuTracker.getLastSoftIrqTime();
3038 final int idleTime = mProcessCpuTracker.getLastIdleTime();
3039 bstats.finishAddingCpuLocked(totalUTime, totalSTime, userTime,
3040 systemTime, iowaitTime, irqTime, softIrqTime, idleTime);
3041 }
3042 }
3043 }
3044
3045 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
3046 mLastWriteTime = now;
3047 mBatteryStatsService.scheduleWriteToDisk();
3048 }
3049 }
3050 }
3051 }
3052

battery相关

 3053    @Override
3054 public void batteryNeedsCpuUpdate() {
3055 updateCpuStatsNow();
3056 }
3057
3058 @Override
3059 public void batteryPowerChanged(boolean onBattery) {
3060 // When plugging in, update the CPU stats first before changing
3061 // the plug state.
3062 updateCpuStatsNow();
3063 synchronized (this) {
3064 synchronized(mPidsSelfLocked) {
3065 mOnBattery = DEBUG_POWER ? true : onBattery;
3066 }
3067 }
3068 }
3069
3070 @Override
3071 public void batterySendBroadcast(Intent intent) {
3072 synchronized (this) {
3073 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
3074 AppOpsManager.OP_NONE, null, false, false,
3075 -1, SYSTEM_UID, UserHandle.USER_ALL);
3076 }
3077 }

获取common service

 3079    /**
3080 * Initialize the application bind args. These are passed to each
3081 * process when the bindApplication() IPC is sent to the process. They're
3082 * lazily setup to make sure the services are running when they're asked for.
3083 */
3084 private HashMap<String, IBinder> getCommonServicesLocked(boolean isolated) {
3085 // Isolated processes won't get this optimization, so that we don't
3086 // violate the rules about which services they have access to.
3087 if (isolated) {
3088 if (mIsolatedAppBindArgs == null) {
3089 mIsolatedAppBindArgs = new HashMap<>();
3090 mIsolatedAppBindArgs.put("package", ServiceManager.getService("package"));
3091 }
3092 return mIsolatedAppBindArgs;
3093 }
3094
3095 if (mAppBindArgs == null) {
3096 mAppBindArgs = new HashMap<>();
3097
3098 // Setup the application init args
3099 mAppBindArgs.put("package", ServiceManager.getService("package"));
3100 mAppBindArgs.put("window", ServiceManager.getService("window"));
3101 mAppBindArgs.put(Context.ALARM_SERVICE,
3102 ServiceManager.getService(Context.ALARM_SERVICE));
3103 }
3104 return mAppBindArgs;
3105 }

设置resumed activity,焦点stack,焦点task

 3107    /**
3108 * Update AMS states when an activity is resumed. This should only be called by
3109 * {@link ActivityStack#setResumedActivityLocked} when an activity is resumed.
3110 */
3111 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
3112 final TaskRecord task = r.getTask();
3113 if (task.isApplicationTask()) {
3114 if (mCurAppTimeTracker != r.appTimeTracker) {
3115 // We are switching app tracking. Complete the current one.
3116 if (mCurAppTimeTracker != null) {
3117 mCurAppTimeTracker.stop();
3118 mHandler.obtainMessage(
3119 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
3120 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
3121 mCurAppTimeTracker = null;
3122 }
3123 if (r.appTimeTracker != null) {
3124 mCurAppTimeTracker = r.appTimeTracker;
3125 startTimeTrackingFocusedActivityLocked();
3126 }
3127 } else {
3128 startTimeTrackingFocusedActivityLocked();
3129 }
3130 } else {
3131 r.appTimeTracker = null;
3132 }
3133 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
3134 // TODO: Probably not, because we don't want to resume voice on switching
3135 // back to this activity
3136 if (task.voiceInteractor != null) {
3137 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
3138 } else {
3139 finishRunningVoiceLocked();
3140
3141 if (mLastResumedActivity != null) {
3142 final IVoiceInteractionSession session;
3143
3144 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask();
3145 if (lastResumedActivityTask != null
3146 && lastResumedActivityTask.voiceSession != null) {
3147 session = lastResumedActivityTask.voiceSession;
3148 } else {
3149 session = mLastResumedActivity.voiceSession;
3150 }
3151
3152 if (session != null) {
3153 // We had been in a voice interaction session, but now focused has
3154 // move to something different. Just finish the session, we can't
3155 // return to it and retain the proper state and synchronization with
3156 // the voice interaction service.
3157 finishVoiceTask(session);
3158 }
3159 }
3160 }
3161
3162 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) {
3163 mHandler.removeMessages(FOREGROUND_PROFILE_CHANGED_MSG);
3164 mHandler.obtainMessage(
3165 FOREGROUND_PROFILE_CHANGED_MSG, r.userId, 0).sendToTarget();
3166 }
3167 mLastResumedActivity = r;
3168
3169 mWindowManager.setFocusedApp(r.appToken, true);
3170
3171 applyUpdateLockStateLocked(r);
3172 applyUpdateVrModeLocked(r);
3173
3174 EventLogTags.writeAmSetResumedActivity(
3175 r == null ? -1 : r.userId,
3176 r == null ? "NULL" : r.shortComponentName,
3177 reason);
3178 }
3179
3180 @Override
3181 public void setFocusedStack(int stackId) {
3182 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
3183 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
3184 final long callingId = Binder.clearCallingIdentity();
3185 try {
3186 synchronized (this) {
3187 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3188 if (stack == null) {
3189 return;
3190 }
3191 final ActivityRecord r = stack.topRunningActivityLocked();
3192 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(r, "setFocusedStack")) {
3193 mStackSupervisor.resumeFocusedStackTopActivityLocked();
3194 }
3195 }
3196 } finally {
3197 Binder.restoreCallingIdentity(callingId);
3198 }
3199 }
3200
3201 @Override
3202 public void setFocusedTask(int taskId) {
3203 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
3204 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
3205 final long callingId = Binder.clearCallingIdentity();
3206 try {
3207 synchronized (this) {
3208 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
3209 if (task == null) {
3210 return;
3211 }
3212 final ActivityRecord r = task.topRunningActivityLocked();
3213 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(r, "setFocusedTask")) {
3214 mStackSupervisor.resumeFocusedStackTopActivityLocked();
3215 }
3216 }
3217 } finally {
3218 Binder.restoreCallingIdentity(callingId);
3219 }
3220 }
3221

注册、取消注册task stack listener

 3222    /** Sets the task stack listener that gets callbacks when a task stack changes. */
3223 @Override
3224 public void registerTaskStackListener(ITaskStackListener listener) throws RemoteException {
3225 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "registerTaskStackListener()");
3226 mTaskChangeNotificationController.registerTaskStackListener(listener);
3227 }
3228
3229 /**
3230 * Unregister a task stack listener so that it stops receiving callbacks.
3231 */
3232 @Override
3233 public void unregisterTaskStackListener(ITaskStackListener listener) throws RemoteException {
3234 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "unregisterTaskStackListener()");
3235 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
3236 }

通知activity被drawn了

 3238    @Override
3239 public void notifyActivityDrawn(IBinder token) {
3240 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
3241 synchronized (this) {
3242 ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token);
3243 if (r != null) {
3244 r.getStack().notifyActivityDrawnLocked(r);
3245 }
3246 }
3247 }

显示询问兼容模式和不支持zoom对话框

 3277    final void showAskCompatModeDialogLocked(ActivityRecord r) {
3278 Message msg = Message.obtain();
3279 msg.what = SHOW_COMPAT_MODE_DIALOG_UI_MSG;
3280 msg.obj = r.getTask().askedCompatMode ? null : r;
3281 mUiHandler.sendMessage(msg);
3282 }
3283
3284 final void showUnsupportedZoomDialogIfNeededLocked(ActivityRecord r) {
3285 final Configuration globalConfig = getGlobalConfiguration();
3286 if (globalConfig.densityDpi != DisplayMetrics.DENSITY_DEVICE_STABLE
3287 && r.appInfo.requiresSmallestWidthDp > globalConfig.smallestScreenWidthDp) {
3288 final Message msg = Message.obtain();
3289 msg.what = SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG;
3290 msg.obj = r;
3291 mUiHandler.sendMessage(msg);
3292 }
3293 }

更新内部lru进程

 3295    private int updateLruProcessInternalLocked(ProcessRecord app, long now, int index,
3296 String what, Object obj, ProcessRecord srcApp) {
3297 app.lastActivityTime = now;
3298
3299 if (app.activities.size() > 0) {
3300 // Don't want to touch dependent processes that are hosting activities.
3301 return index;
3302 }
3303
3304 int lrui = mLruProcesses.lastIndexOf(app);
3305 if (lrui < 0) {
3306 Slog.wtf(TAG, "Adding dependent process " + app + " not on LRU list: "
3307 + what + " " + obj + " from " + srcApp);
3308 return index;
3309 }
3310
3311 if (lrui >= index) {
3312 // Don't want to cause this to move dependent processes *back* in the
3313 // list as if they were less frequently used.
3314 return index;
3315 }
3316
3317 if (lrui >= mLruProcessActivityStart) {
3318 // Don't want to touch dependent processes that are hosting activities.
3319 return index;
3320 }
3321
3322 mLruProcesses.remove(lrui);
3323 if (index > 0) {
3324 index--;
3325 }
3326 if (DEBUG_LRU) Slog.d(TAG_LRU, "Moving dep from " + lrui + " to " + index
3327 + " in LRU list: " + app);
3328 mLruProcesses.add(index, app);
3329 return index;
3330 }

杀掉进程组

 3332    static void killProcessGroup(int uid, int pid) {
3333 if (sKillHandler != null) {
3334 sKillHandler.sendMessage(
3335 sKillHandler.obtainMessage(KillHandler.KILL_PROCESS_GROUP_MSG, uid, pid));
3336 } else {
3337 Slog.w(TAG, "Asked to kill process group before system bringup!");
3338 Process.killProcessGroup(uid, pid);
3339 }
3340 }

移除lru进程

 3342    final void removeLruProcessLocked(ProcessRecord app) {
3343 int lrui = mLruProcesses.lastIndexOf(app);
3344 if (lrui >= 0) {
3345 if (!app.killed) {
3346 Slog.wtfStack(TAG, "Removing process that hasn't been killed: " + app);
3347 killProcessQuiet(app.pid);
3348 killProcessGroup(app.uid, app.pid);
3349 }
3350 if (lrui <= mLruProcessActivityStart) {
3351 mLruProcessActivityStart--;
3352 }
3353 if (lrui <= mLruProcessServiceStart) {
3354 mLruProcessServiceStart--;
3355 }
3356 mLruProcesses.remove(lrui);
3357 }
3358 }

更新lru进程

 3360    final void updateLruProcessLocked(ProcessRecord app, boolean activityChange,
3361 ProcessRecord client) {
3362 final boolean hasActivity = app.activities.size() > 0 || app.hasClientActivities
3363 || app.treatLikeActivity;
3364 final boolean hasService = false; // not impl yet. app.services.size() > 0;
3365 if (!activityChange && hasActivity) {
3366 // The process has activities, so we are only allowing activity-based adjustments
3367 // to move it. It should be kept in the front of the list with other
3368 // processes that have activities, and we don't want those to change their
3369 // order except due to activity operations.
3370 return;
3371 }
3372
3373 mLruSeq++;
3374 final long now = SystemClock.uptimeMillis();
3375 app.lastActivityTime = now;
3376
3377 // First a quick reject: if the app is already at the position we will
3378 // put it, then there is nothing to do.
3379 if (hasActivity) {
3380 final int N = mLruProcesses.size();
3381 if (N > 0 && mLruProcesses.get(N-1) == app) {
3382 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, already top activity: " + app);
3383 return;
3384 }
3385 } else {
3386 if (mLruProcessServiceStart > 0
3387 && mLruProcesses.get(mLruProcessServiceStart-1) == app) {
3388 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, already top other: " + app);
3389 return;
3390 }
3391 }
3392
3393 int lrui = mLruProcesses.lastIndexOf(app);
3394
3395 if (app.persistent && lrui >= 0) {
3396 // We don't care about the position of persistent processes, as long as
3397 // they are in the list.
3398 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, persistent: " + app);
3399 return;
3400 }
3401
3402 /* In progress: compute new position first, so we can avoid doing work
3403 if the process is not actually going to move. Not yet working.
3404 int addIndex;
3405 int nextIndex;
3406 boolean inActivity = false, inService = false;
3407 if (hasActivity) {
3408 // Process has activities, put it at the very tipsy-top.
3409 addIndex = mLruProcesses.size();
3410 nextIndex = mLruProcessServiceStart;
3411 inActivity = true;
3412 } else if (hasService) {
3413 // Process has services, put it at the top of the service list.
3414 addIndex = mLruProcessActivityStart;
3415 nextIndex = mLruProcessServiceStart;
3416 inActivity = true;
3417 inService = true;
3418 } else {
3419 // Process not otherwise of interest, it goes to the top of the non-service area.
3420 addIndex = mLruProcessServiceStart;
3421 if (client != null) {
3422 int clientIndex = mLruProcesses.lastIndexOf(client);
3423 if (clientIndex < 0) Slog.d(TAG, "Unknown client " + client + " when updating "
3424 + app);
3425 if (clientIndex >= 0 && addIndex > clientIndex) {
3426 addIndex = clientIndex;
3427 }
3428 }
3429 nextIndex = addIndex > 0 ? addIndex-1 : addIndex;
3430 }
3431
3432 Slog.d(TAG, "Update LRU at " + lrui + " to " + addIndex + " (act="
3433 + mLruProcessActivityStart + "): " + app);
3434 */
3435
3436 if (lrui >= 0) {
3437 if (lrui < mLruProcessActivityStart) {
3438 mLruProcessActivityStart--;
3439 }
3440 if (lrui < mLruProcessServiceStart) {
3441 mLruProcessServiceStart--;
3442 }
3443 /*
3444 if (addIndex > lrui) {
3445 addIndex--;
3446 }
3447 if (nextIndex > lrui) {
3448 nextIndex--;
3449 }
3450 */
3451 mLruProcesses.remove(lrui);
3452 }
3453
3454 /*
3455 mLruProcesses.add(addIndex, app);
3456 if (inActivity) {
3457 mLruProcessActivityStart++;
3458 }
3459 if (inService) {
3460 mLruProcessActivityStart++;
3461 }
3462 */
3463
3464 int nextIndex;
3465 if (hasActivity) {
3466 final int N = mLruProcesses.size();
3467 if (app.activities.size() == 0 && mLruProcessActivityStart < (N - 1)) {
3468 // Process doesn't have activities, but has clients with
3469 // activities... move it up, but one below the top (the top
3470 // should always have a real activity).
3471 if (DEBUG_LRU) Slog.d(TAG_LRU,
3472 "Adding to second-top of LRU activity list: " + app);
3473 mLruProcesses.add(N - 1, app);
3474 // To keep it from spamming the LRU list (by making a bunch of clients),
3475 // we will push down any other entries owned by the app.
3476 final int uid = app.info.uid;
3477 for (int i = N - 2; i > mLruProcessActivityStart; i--) {
3478 ProcessRecord subProc = mLruProcesses.get(i);
3479 if (subProc.info.uid == uid) {
3480 // We want to push this one down the list. If the process after
3481 // it is for the same uid, however, don't do so, because we don't
3482 // want them internally to be re-ordered.
3483 if (mLruProcesses.get(i - 1).info.uid != uid) {
3484 if (DEBUG_LRU) Slog.d(TAG_LRU,
3485 "Pushing uid " + uid + " swapping at " + i + ": "
3486 + mLruProcesses.get(i) + " : " + mLruProcesses.get(i - 1));
3487 ProcessRecord tmp = mLruProcesses.get(i);
3488 mLruProcesses.set(i, mLruProcesses.get(i - 1));
3489 mLruProcesses.set(i - 1, tmp);
3490 i--;
3491 }
3492 } else {
3493 // A gap, we can stop here.
3494 break;
3495 }
3496 }
3497 } else {
3498 // Process has activities, put it at the very tipsy-top.
3499 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding to top of LRU activity list: " + app);
3500 mLruProcesses.add(app);
3501 }
3502 nextIndex = mLruProcessServiceStart;
3503 } else if (hasService) {
3504 // Process has services, put it at the top of the service list.
3505 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding to top of LRU service list: " + app);
3506 mLruProcesses.add(mLruProcessActivityStart, app);
3507 nextIndex = mLruProcessServiceStart;
3508 mLruProcessActivityStart++;
3509 } else {
3510 // Process not otherwise of interest, it goes to the top of the non-service area.
3511 int index = mLruProcessServiceStart;
3512 if (client != null) {
3513 // If there is a client, don't allow the process to be moved up higher
3514 // in the list than that client.
3515 int clientIndex = mLruProcesses.lastIndexOf(client);
3516 if (DEBUG_LRU && clientIndex < 0) Slog.d(TAG_LRU, "Unknown client " + client
3517 + " when updating " + app);
3518 if (clientIndex <= lrui) {
3519 // Don't allow the client index restriction to push it down farther in the
3520 // list than it already is.
3521 clientIndex = lrui;
3522 }
3523 if (clientIndex >= 0 && index > clientIndex) {
3524 index = clientIndex;
3525 }
3526 }
3527 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding at " + index + " of LRU list: " + app);
3528 mLruProcesses.add(index, app);
3529 nextIndex = index-1;
3530 mLruProcessActivityStart++;
3531 mLruProcessServiceStart++;
3532 }
3533
3534 // If the app is currently using a content provider or service,
3535 // bump those processes as well.
3536 for (int j=app.connections.size()-1; j>=0; j--) {
3537 ConnectionRecord cr = app.connections.valueAt(j);
3538 if (cr.binding != null && !cr.serviceDead && cr.binding.service != null
3539 && cr.binding.service.app != null
3540 && cr.binding.service.app.lruSeq != mLruSeq
3541 && !cr.binding.service.app.persistent) {
3542 nextIndex = updateLruProcessInternalLocked(cr.binding.service.app, now, nextIndex,
3543 "service connection", cr, app);
3544 }
3545 }
3546 for (int j=app.conProviders.size()-1; j>=0; j--) {
3547 ContentProviderRecord cpr = app.conProviders.get(j).provider;
3548 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq && !cpr.proc.persistent) {
3549 nextIndex = updateLruProcessInternalLocked(cpr.proc, now, nextIndex,
3550 "provider reference", cpr, app);
3551 }
3552 }
3553 }

获取进程record

 3555    final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean keepIfLarge) {
3556 if (uid == SYSTEM_UID) {
3557 // The system gets to run in any process. If there are multiple
3558 // processes with the same uid, just pick the first (this
3559 // should never happen).
3560 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(processName);
3561 if (procs == null) return null;
3562 final int procCount = procs.size();
3563 for (int i = 0; i < procCount; i++) {
3564 final int procUid = procs.keyAt(i);
3565 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
3566 // Don't use an app process or different user process for system component.
3567 continue;
3568 }
3569 return procs.valueAt(i);
3570 }
3571 }
3572 ProcessRecord proc = mProcessNames.get(processName, uid);
3573 if (false && proc != null && !keepIfLarge
3574 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY
3575 && proc.lastCachedPss >= 4000) {
3576 // Turn this condition on to cause killing to happen regularly, for testing.
3577 if (proc.baseProcessTracker != null) {
3578 proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss);
3579 }
3580 proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true);
3581 } else if (proc != null && !keepIfLarge
3582 && mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL
3583 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
3584 if (DEBUG_PSS) Slog.d(TAG_PSS, "May not keep " + proc + ": pss=" + proc.lastCachedPss);
3585 if (proc.lastCachedPss >= mProcessList.getCachedRestoreThresholdKb()) {
3586 if (proc.baseProcessTracker != null) {
3587 proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss);
3588 }
3589 proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true);
3590 }
3591 }
3592 return proc;
3593 }
3594

通知pkms package被使用

 3595    void notifyPackageUse(String packageName, int reason) {
3596 IPackageManager pm = AppGlobals.getPackageManager();
3597 try {
3598 pm.notifyPackageUse(packageName, reason);
3599 } catch (RemoteException e) {
3600 }
3601 }

是否下一个window变迁被提前

 3603    boolean isNextTransitionForward() {
3604 int transit = mWindowManager.getPendingAppTransition();
3605 return transit == TRANSIT_ACTIVITY_OPEN
3606 || transit == TRANSIT_TASK_OPEN
3607 || transit == TRANSIT_TASK_TO_FRONT;
3608 }

启动isolate进程

 610    int startIsolatedProcess(String entryPoint, String[] entryPointArgs,
3611 String processName, String abiOverride, int uid, Runnable crashHandler) {
3612 synchronized(this) {
3613 ApplicationInfo info = new ApplicationInfo();
3614 // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid.
3615 // For isolated processes, the former contains the parent's uid and the latter the
3616 // actual uid of the isolated process.
3617 // In the special case introduced by this method (which is, starting an isolated
3618 // process directly from the SystemServer without an actual parent app process) the
3619 // closest thing to a parent's uid is SYSTEM_UID.
3620 // The only important thing here is to keep AI.uid != PR.uid, in order to trigger
3621 // the |isolated| logic in the ProcessRecord constructor.
3622 info.uid = SYSTEM_UID;
3623 info.processName = processName;
3624 info.className = entryPoint;
3625 info.packageName = "android";
3626 info.seInfoUser = SELinuxUtil.COMPLETE_STR;
3627 ProcessRecord proc = startProcessLocked(processName, info /* info */,
3628 false /* knownToBeDead */, 0 /* intentFlags */, "" /* hostingType */,
3629 null /* hostingName */, true /* allowWhileBooting */, true /* isolated */,
3630 uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs,
3631 crashHandler);
3632 return proc != null ? proc.pid : 0;
3633 }
3634 }
3635

启动进程

 3636    final ProcessRecord startProcessLocked(String processName,
3637 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
3638 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
3639 boolean isolated, boolean keepIfLarge) {
3640 return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
3641 hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
3642 null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
3643 null /* crashHandler */);
3644 }
3645
3646 final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
3647 boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
3648 boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
3649 String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
3650 long startTime = SystemClock.elapsedRealtime();
3651 ProcessRecord app;
3652 if (!isolated) {
3653 app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
3654 checkTime(startTime, "startProcess: after getProcessRecord");
3655
3656 if ((intentFlags & Intent.FLAG_FROM_BACKGROUND) != 0) {
3657 // If we are in the background, then check to see if this process
3658 // is bad. If so, we will just silently fail.
3659 if (mAppErrors.isBadProcessLocked(info)) {
3660 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
3661 + "/" + info.processName);
3662 return null;
3663 }
3664 } else {
3665 // When the user is explicitly starting a process, then clear its
3666 // crash count so that we won't make it bad until they see at
3667 // least one crash dialog again, and make the process good again
3668 // if it had been bad.
3669 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
3670 + "/" + info.processName);
3671 mAppErrors.resetProcessCrashTimeLocked(info);
3672 if (mAppErrors.isBadProcessLocked(info)) {
3673 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
3674 UserHandle.getUserId(info.uid), info.uid,
3675 info.processName);
3676 mAppErrors.clearBadProcessLocked(info);
3677 if (app != null) {
3678 app.bad = false;
3679 }
3680 }
3681 }
3682 } else {
3683 // If this is an isolated process, it can't re-use an existing process.
3684 app = null;
3685 }
3686
3687 // We don't have to do anything more if:
3688 // (1) There is an existing application record; and
3689 // (2) The caller doesn't think it is dead, OR there is no thread
3690 // object attached to it so we know it couldn't have crashed; and
3691 // (3) There is a pid assigned to it, so it is either starting or
3692 // already running.
3693 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "startProcess: name=" + processName
3694 + " app=" + app + " knownToBeDead=" + knownToBeDead
3695 + " thread=" + (app != null ? app.thread : null)
3696 + " pid=" + (app != null ? app.pid : -1));
3697 if (app != null && app.pid > 0) {
3698 if ((!knownToBeDead && !app.killed) || app.thread == null) {
3699 // We already have the app running, or are waiting for it to
3700 // come up (we have a pid but not yet its thread), so keep it.
3701 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "App already running: " + app);
3702 // If this is a new package in the process, add the package to the list
3703 app.addPackage(info.packageName, info.versionCode, mProcessStats);
3704 checkTime(startTime, "startProcess: done, added package to proc");
3705 return app;
3706 }
3707
3708 // An application record is attached to a previous process,
3709 // clean it up now.
3710 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_PROCESSES, "App died: " + app);
3711 checkTime(startTime, "startProcess: bad proc running, killing");
3712 killProcessGroup(app.uid, app.pid);
3713 handleAppDiedLocked(app, true, true);
3714 checkTime(startTime, "startProcess: done killing old proc");
3715 }
3716
3717 String hostingNameStr = hostingName != null
3718 ? hostingName.flattenToShortString() : null;
3719
3720 if (app == null) {
3721 checkTime(startTime, "startProcess: creating new process record");
3722 app = newProcessRecordLocked(info, processName, isolated, isolatedUid);
3723 if (app == null) {
3724 Slog.w(TAG, "Failed making new process record for "
3725 + processName + "/" + info.uid + " isolated=" + isolated);
3726 return null;
3727 }
3728 app.crashHandler = crashHandler;
3729 checkTime(startTime, "startProcess: done creating new process record");
3730 } else {
3731 // If this is a new package in the process, add the package to the list
3732 app.addPackage(info.packageName, info.versionCode, mProcessStats);
3733 checkTime(startTime, "startProcess: added package to existing proc");
3734 }
3735
3736 // If the system is not ready yet, then hold off on starting this
3737 // process until it is.
3738 if (!mProcessesReady
3739 && !isAllowedWhileBooting(info)
3740 && !allowWhileBooting) {
3741 if (!mProcessesOnHold.contains(app)) {
3742 mProcessesOnHold.add(app);
3743 }
3744 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES,
3745 "System not ready, putting on hold: " + app);
3746 checkTime(startTime, "startProcess: returning with proc on hold");
3747 return app;
3748 }
3749
3750 checkTime(startTime, "startProcess: stepping in to startProcess");
3751 startProcessLocked(
3752 app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs);
3753 checkTime(startTime, "startProcess: done starting proc!");
3754 return (app.pid != 0) ? app : null;
3755 }
3756

是否是persist进程

 3757    boolean isAllowedWhileBooting(ApplicationInfo ai) {
3758 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
3759 }

lock下启动进程

 3761    private final void startProcessLocked(ProcessRecord app,
3762 String hostingType, String hostingNameStr) {
3763 startProcessLocked(app, hostingType, hostingNameStr, null /* abiOverride */,
3764 null /* entryPoint */, null /* entryPointArgs */);
3765 }
3766
3767 private final void startProcessLocked(ProcessRecord app, String hostingType,
3768 String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
3769 long startTime = SystemClock.elapsedRealtime();
3770 if (app.pid > 0 && app.pid != MY_PID) {
3771 checkTime(startTime, "startProcess: removing from pids map");
3772 synchronized (mPidsSelfLocked) {
3773 mPidsSelfLocked.remove(app.pid);
3774 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3775 }
3776 checkTime(startTime, "startProcess: done removing from pids map");
3777 app.setPid(0);
3778 }
3779
3780 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES,
3781 "startProcessLocked removing on hold: " + app);
3782 mProcessesOnHold.remove(app);
3783
3784 checkTime(startTime, "startProcess: starting to update cpu stats");
3785 updateCpuStats();
3786 checkTime(startTime, "startProcess: done updating cpu stats");
3787
3788 try {
3789 try {
3790 final int userId = UserHandle.getUserId(app.uid);
3791 AppGlobals.getPackageManager().checkPackageStartable(app.info.packageName, userId);
3792 } catch (RemoteException e) {
3793 throw e.rethrowAsRuntimeException();
3794 }
3795
3796 int uid = app.uid;
3797 int[] gids = null;
3798 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
3799 if (!app.isolated) {
3800 int[] permGids = null;
3801 try {
3802 checkTime(startTime, "startProcess: getting gids from package manager");
3803 final IPackageManager pm = AppGlobals.getPackageManager();
3804 permGids = pm.getPackageGids(app.info.packageName,
3805 MATCH_DEBUG_TRIAGED_MISSING, app.userId);
3806 StorageManagerInternal storageManagerInternal = LocalServices.getService(
3807 StorageManagerInternal.class);
3808 mountExternal = storageManagerInternal.getExternalStorageMountMode(uid,
3809 app.info.packageName);
3810 } catch (RemoteException e) {
3811 throw e.rethrowAsRuntimeException();
3812 }
3813
3814 /*
3815 * Add shared application and profile GIDs so applications can share some
3816 * resources like shared libraries and access user-wide resources
3817 */
3818 if (ArrayUtils.isEmpty(permGids)) {
3819 gids = new int[3];
3820 } else {
3821 gids = new int[permGids.length + 3];
3822 System.arraycopy(permGids, 0, gids, 3, permGids.length);
3823 }
3824 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
3825 gids[1] = UserHandle.getCacheAppGid(UserHandle.getAppId(uid));
3826 gids[2] = UserHandle.getUserGid(UserHandle.getUserId(uid));
3827 }
3828 checkTime(startTime, "startProcess: building args");
3829 if (mFactoryTest != FactoryTest.FACTORY_TEST_OFF) {
3830 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
3831 && mTopComponent != null
3832 && app.processName.equals(mTopComponent.getPackageName())) {
3833 uid = 0;
3834 }
3835 if (mFactoryTest == FactoryTest.FACTORY_TEST_HIGH_LEVEL
3836 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
3837 uid = 0;
3838 }
3839 }
3840 int debugFlags = 0;
3841 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3842 debugFlags |= Zygote.DEBUG_ENABLE_JDWP;
3843 debugFlags |= Zygote.DEBUG_JAVA_DEBUGGABLE;
3844 // Also turn on CheckJNI for debuggable apps. It's quite
3845 // awkward to turn on otherwise.
3846 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
3847 }
3848 // Run the app in safe mode if its manifest requests so or the
3849 // system is booted in safe mode.
3850 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
3851 mSafeMode == true) {
3852 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
3853 }
3854 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
3855 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
3856 }
3857 String genDebugInfoProperty = SystemProperties.get("debug.generate-debug-info");
3858 if ("true".equals(genDebugInfoProperty)) {
3859 debugFlags |= Zygote.DEBUG_GENERATE_DEBUG_INFO;
3860 }
3861 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
3862 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
3863 }
3864 if ("1".equals(SystemProperties.get("debug.assert"))) {
3865 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
3866 }
3867 if (mNativeDebuggingApp != null && mNativeDebuggingApp.equals(app.processName)) {
3868 // Enable all debug flags required by the native debugger.
3869 debugFlags |= Zygote.DEBUG_ALWAYS_JIT; // Don't interpret anything
3870 debugFlags |= Zygote.DEBUG_GENERATE_DEBUG_INFO; // Generate debug info
3871 debugFlags |= Zygote.DEBUG_NATIVE_DEBUGGABLE; // Disbale optimizations
3872 mNativeDebuggingApp = null;
3873 }
3874
3875 String invokeWith = null;
3876 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3877 // Debuggable apps may include a wrapper script with their library directory.
3878 String wrapperFileName = app.info.nativeLibraryDir + "/wrap.sh";
3879 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3880 try {
3881 if (new File(wrapperFileName).exists()) {
3882 invokeWith = "/system/bin/logwrapper " + wrapperFileName;
3883 }
3884 } finally {
3885 StrictMode.setThreadPolicy(oldPolicy);
3886 }
3887 }
3888
3889 String requiredAbi = (abiOverride != null) ? abiOverride : app.info.primaryCpuAbi;
3890 if (requiredAbi == null) {
3891 requiredAbi = Build.SUPPORTED_ABIS[0];
3892 }
3893
3894 String instructionSet = null;
3895 if (app.info.primaryCpuAbi != null) {
3896 instructionSet = VMRuntime.getInstructionSet(app.info.primaryCpuAbi);
3897 }
3898
3899 app.gids = gids;
3900 app.requiredAbi = requiredAbi;
3901 app.instructionSet = instructionSet;
3902
3903 // the per-user SELinux context must be set
3904 if (TextUtils.isEmpty(app.info.seInfoUser)) {
3905 Slog.wtf(TAG, "SELinux tag not defined",
3906 new IllegalStateException("SELinux tag not defined for "
3907 + app.info.packageName + " (uid " + app.uid + ")"));
3908 }
3909 final String seInfo = app.info.seInfo
3910 + (TextUtils.isEmpty(app.info.seInfoUser) ? "" : app.info.seInfoUser);
3911 // Start the process. It will either succeed and return a result containing
3912 // the PID of the new process, or else throw a RuntimeException.
3913 boolean isActivityProcess = (entryPoint == null);
3914 if (entryPoint == null) entryPoint = "android.app.ActivityThread";
3915 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " +
3916 app.processName);
3917 checkTime(startTime, "startProcess: asking zygote to start proc");
3918 ProcessStartResult startResult;
3919 if (hostingType.equals("webview_service")) {
3920 startResult = startWebView(entryPoint,
3921 app.processName, uid, uid, gids, debugFlags, mountExternal,
3922 app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
3923 app.info.dataDir, null, entryPointArgs);
3924 } else {
3925 startResult = Process.start(entryPoint,
3926 app.processName, uid, uid, gids, debugFlags, mountExternal,
3927 app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
3928 app.info.dataDir, invokeWith, entryPointArgs);
3929 }
3930 checkTime(startTime, "startProcess: returned from zygote!");
3931 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
3932
3933 mBatteryStatsService.noteProcessStart(app.processName, app.info.uid);
3934 checkTime(startTime, "startProcess: done updating battery stats");
3935
3936 EventLog.writeEvent(EventLogTags.AM_PROC_START,
3937 UserHandle.getUserId(uid), startResult.pid, uid,
3938 app.processName, hostingType,
3939 hostingNameStr != null ? hostingNameStr : "");
3940
3941 try {
3942 AppGlobals.getPackageManager().logAppProcessStartIfNeeded(app.processName, app.uid,
3943 seInfo, app.info.sourceDir, startResult.pid);
3944 } catch (RemoteException ex) {
3945 // Ignore
3946 }
3947
3948 if (app.persistent) {
3949 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
3950 }
3951
3952 checkTime(startTime, "startProcess: building log message");
3953 StringBuilder buf = mStringBuilder;
3954 buf.setLength(0);
3955 buf.append("Start proc ");
3956 buf.append(startResult.pid);
3957 buf.append(':');
3958 buf.append(app.processName);
3959 buf.append('/');
3960 UserHandle.formatUid(buf, uid);
3961 if (!isActivityProcess) {
3962 buf.append(" [");
3963 buf.append(entryPoint);
3964 buf.append("]");
3965 }
3966 buf.append(" for ");
3967 buf.append(hostingType);
3968 if (hostingNameStr != null) {
3969 buf.append(" ");
3970 buf.append(hostingNameStr);
3971 }
3972 Slog.i(TAG, buf.toString());
3973 app.setPid(startResult.pid);
3974 app.usingWrapper = startResult.usingWrapper;
3975 app.removed = false;
3976 app.killed = false;
3977 app.killedByAm = false;
3978 checkTime(startTime, "startProcess: starting to update pids map");
3979 ProcessRecord oldApp;
3980 synchronized (mPidsSelfLocked) {
3981 oldApp = mPidsSelfLocked.get(startResult.pid);
3982 }
3983 // If there is already an app occupying that pid that hasn't been cleaned up
3984 if (oldApp != null && !app.isolated) {
3985 // Clean up anything relating to this pid first
3986 Slog.w(TAG, "Reusing pid " + startResult.pid
3987 + " while app is still mapped to it");
3988 cleanUpApplicationRecordLocked(oldApp, false, false, -1,
3989 true /*replacingPid*/);
3990 }
3991 synchronized (mPidsSelfLocked) {
3992 this.mPidsSelfLocked.put(startResult.pid, app);
3993 if (isActivityProcess) {
3994 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
3995 msg.obj = app;
3996 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
3997 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
3998 }
3999 }
4000 checkTime(startTime, "startProcess: done updating pids map");
4001 } catch (RuntimeException e) {
4002 Slog.e(TAG, "Failure starting process " + app.processName, e);
4003
4004 // Something went very wrong while trying to start this process; one
4005 // common case is when the package is frozen due to an active
4006 // upgrade. To recover, clean up any active bookkeeping related to
4007 // starting this process. (We already invoked this method once when
4008 // the package was initially frozen through KILL_APPLICATION_MSG, so
4009 // it doesn't hurt to use it again.)
4010 forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid), false,
4011 false, true, false, false, UserHandle.getUserId(app.userId), "start failure");
4012 }
4013 }
4014

更新使用状态

 4015    void updateUsageStats(ActivityRecord component, boolean resumed) {
4016 if (DEBUG_SWITCH) Slog.d(TAG_SWITCH,
4017 "updateUsageStats: comp=" + component + "res=" + resumed);
4018 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
4019 if (resumed) {
4020 if (mUsageStatsService != null) {
4021 mUsageStatsService.reportEvent(component.realActivity, component.userId,
4022 UsageEvents.Event.MOVE_TO_FOREGROUND);
4023 }
4024 synchronized (stats) {
4025 stats.noteActivityResumedLocked(component.app.uid);
4026 }
4027 } else {
4028 if (mUsageStatsService != null) {
4029 mUsageStatsService.reportEvent(component.realActivity, component.userId,
4030 UsageEvents.Event.MOVE_TO_BACKGROUND);
4031 }
4032 synchronized (stats) {
4033 stats.noteActivityPausedLocked(component.app.uid);
4034 }
4035 }
4036 }

获取home intent

 4038    Intent getHomeIntent() {
4039 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
4040 intent.setComponent(mTopComponent);
4041 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
4042 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
4043 intent.addCategory(Intent.CATEGORY_HOME);
4044 }
4045 return intent;
4046 }
4047

启动home activity

 4048    boolean startHomeActivityLocked(int userId, String reason) {
4049 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
4050 && mTopAction == null) {
4051 // We are running in factory test mode, but unable to find
4052 // the factory test app, so just sit around displaying the
4053 // error message and don't try to start anything.
4054 return false;
4055 }
4056 Intent intent = getHomeIntent();
4057 ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
4058 if (aInfo != null) {
4059 intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
4060 // Don't do this if the home app is currently being
4061 // instrumented.
4062 aInfo = new ActivityInfo(aInfo);
4063 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
4064 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
4065 aInfo.applicationInfo.uid, true);
4066 if (app == null || app.instr == null) {
4067 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
4068 final int resolvedUserId = UserHandle.getUserId(aInfo.applicationInfo.uid);
4069 // For ANR debugging to verify if the user activity is the one that actually
4070 // launched.
4071 final String myReason = reason + ":" + userId + ":" + resolvedUserId;
4072 mActivityStarter.startHomeActivityLocked(intent, aInfo, myReason);
4073 }
4074 } else {
4075 Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());
4076 }
4077
4078 return true;
4079 }

解析ActivityInfo

 4081    private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
4082 ActivityInfo ai = null;
4083 ComponentName comp = intent.getComponent();
4084 try {
4085 if (comp != null) {
4086 // Factory test.
4087 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
4088 } else {
4089 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
4090 intent,
4091 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
4092 flags, userId);
4093
4094 if (info != null) {
4095 ai = info.activityInfo;
4096 }
4097 }
4098 } catch (RemoteException e) {
4099 // ignore
4100 }
4101
4102 return ai;
4103 }

启动设置activity

 4105    /**
4106 * Starts the "new version setup screen" if appropriate.
4107 */
4108 void startSetupActivityLocked() {
4109 // Only do this once per boot.
4110 if (mCheckedForSetup) {
4111 return;
4112 }
4113
4114 // We will show this screen if the current one is a different
4115 // version than the last one shown, and we are not running in
4116 // low-level factory test mode.
4117 final ContentResolver resolver = mContext.getContentResolver();
4118 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL &&
4119 Settings.Global.getInt(resolver,
4120 Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
4121 mCheckedForSetup = true;
4122
4123 // See if we should be showing the platform update setup UI.
4124 final Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
4125 final List<ResolveInfo> ris = mContext.getPackageManager().queryIntentActivities(intent,
4126 PackageManager.MATCH_SYSTEM_ONLY | PackageManager.GET_META_DATA);
4127 if (!ris.isEmpty()) {
4128 final ResolveInfo ri = ris.get(0);
4129 String vers = ri.activityInfo.metaData != null
4130 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
4131 : null;
4132 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
4133 vers = ri.activityInfo.applicationInfo.metaData.getString(
4134 Intent.METADATA_SETUP_VERSION);
4135 }
4136 String lastVers = Settings.Secure.getString(
4137 resolver, Settings.Secure.LAST_SETUP_SHOWN);
4138 if (vers != null && !vers.equals(lastVers)) {
4139 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4140 intent.setComponent(new ComponentName(
4141 ri.activityInfo.packageName, ri.activityInfo.name));
4142 mActivityStarter.startActivityLocked(null, intent, null /*ephemeralIntent*/,
4143 null, ri.activityInfo, null /*rInfo*/, null, null, null, null, 0, 0, 0,
4144 null, 0, 0, 0, null, false, false, null, null, null,
4145 "startSetupActivity");
4146 }
4147 }
4148 }
4149 }

获取兼容信息

 4151    CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
4152 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
4153 }

强制不要是isolated调用者

 4155    void enforceNotIsolatedCaller(String caller) {
4156 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4157 throw new SecurityException("Isolated process not allowed to call " + caller);
4158 }
4159 }

获取、设置前台activity、package屏幕兼容模式,package询问屏幕兼容模式,是否有使用使用统计信息权限,获取进程状态

 4170    @Override
4171 public int getFrontActivityScreenCompatMode() {
4172 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
4173 synchronized (this) {
4174 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
4175 }
4176 }
4177
4178 @Override
4179 public void setFrontActivityScreenCompatMode(int mode) {
4180 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4181 "setFrontActivityScreenCompatMode");
4182 synchronized (this) {
4183 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
4184 }
4185 }
4186
4187 @Override
4188 public int getPackageScreenCompatMode(String packageName) {
4189 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4190 synchronized (this) {
4191 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4192 }
4193 }
4194
4195 @Override
4196 public void setPackageScreenCompatMode(String packageName, int mode) {
4197 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4198 "setPackageScreenCompatMode");
4199 synchronized (this) {
4200 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4201 }
4202 }
4203
4204 @Override
4205 public boolean getPackageAskScreenCompat(String packageName) {
4206 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4207 synchronized (this) {
4208 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4209 }
4210 }
4211
4212 @Override
4213 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4214 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4215 "setPackageAskScreenCompat");
4216 synchronized (this) {
4217 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4218 }
4219 }
4220
4221 private boolean hasUsageStatsPermission(String callingPackage) {
4222 final int mode = mAppOpsService.checkOperation(AppOpsManager.OP_GET_USAGE_STATS,
4223 Binder.getCallingUid(), callingPackage);
4224 if (mode == AppOpsManager.MODE_DEFAULT) {
4225 return checkCallingPermission(Manifest.permission.PACKAGE_USAGE_STATS)
4226 == PackageManager.PERMISSION_GRANTED;
4227 }
4228 return mode == AppOpsManager.MODE_ALLOWED;
4229 }
4230
4231 @Override
4232 public int getPackageProcessState(String packageName, String callingPackage) {
4233 if (!hasUsageStatsPermission(callingPackage)) {
4234 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
4235 "getPackageProcessState");
4236 }
4237
4238 int procState = ActivityManager.PROCESS_STATE_NONEXISTENT;
4239 synchronized (this) {
4240 for (int i=mLruProcesses.size()-1; i>=0; i--) {
4241 final ProcessRecord proc = mLruProcesses.get(i);
4242 if (procState > proc.setProcState) {
4243 if (proc.pkgList.containsKey(packageName) ||
4244 (proc.pkgDeps != null && proc.pkgDeps.contains(packageName))) {
4245 procState = proc.setProcState;
4246 }
4247 }
4248 }
4249 }
4250 return procState;
4251 }

设置进程trim level

 4253    @Override
4254 public boolean setProcessMemoryTrimLevel(String process, int userId, int level)
4255 throws RemoteException {
4256 synchronized (this) {
4257 final ProcessRecord app = findProcessLocked(process, userId, "setProcessMemoryTrimLevel");
4258 if (app == null) {
4259 throw new IllegalArgumentException("Unknown process: " + process);
4260 }
4261 if (app.thread == null) {
4262 throw new IllegalArgumentException("Process has no app thread");
4263 }
4264 if (app.trimMemoryLevel >= level) {
4265 throw new IllegalArgumentException(
4266 "Unable to set a higher trim level than current level");
4267 }
4268 if (!(level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN ||
4269 app.curProcState > ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND)) {
4270 throw new IllegalArgumentException("Unable to set a background trim level "
4271 + "on a foreground process");
4272 }
4273 app.thread.scheduleTrimMemory(level);
4274 app.trimMemoryLevel = level;
4275 return true;
4276 }
4277 }

分发进程状态改变,进程死亡,进程Uid改变,进程Uid为观察者改变,

 4279    private void dispatchProcessesChanged() {
4280 int N;
4281 synchronized (this) {
4282 N = mPendingProcessChanges.size();
4283 if (mActiveProcessChanges.length < N) {
4284 mActiveProcessChanges = new ProcessChangeItem[N];
4285 }
4286 mPendingProcessChanges.toArray(mActiveProcessChanges);
4287 mPendingProcessChanges.clear();
4288 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
4289 "*** Delivering " + N + " process changes");
4290 }
4291
4292 int i = mProcessObservers.beginBroadcast();
4293 while (i > 0) {
4294 i--;
4295 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
4296 if (observer != null) {
4297 try {
4298 for (int j=0; j<N; j++) {
4299 ProcessChangeItem item = mActiveProcessChanges[j];
4300 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
4301 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
4302 "ACTIVITIES CHANGED pid=" + item.pid + " uid="
4303 + item.uid + ": " + item.foregroundActivities);
4304 observer.onForegroundActivitiesChanged(item.pid, item.uid,
4305 item.foregroundActivities);
4306 }
4307 }
4308 } catch (RemoteException e) {
4309 }
4310 }
4311 }
4312 mProcessObservers.finishBroadcast();
4313
4314 synchronized (this) {
4315 for (int j=0; j<N; j++) {
4316 mAvailProcessChanges.add(mActiveProcessChanges[j]);
4317 }
4318 }
4319 }
4320
4321 private void dispatchProcessDied(int pid, int uid) {
4322 int i = mProcessObservers.beginBroadcast();
4323 while (i > 0) {
4324 i--;
4325 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
4326 if (observer != null) {
4327 try {
4328 observer.onProcessDied(pid, uid);
4329 } catch (RemoteException e) {
4330 }
4331 }
4332 }
4333 mProcessObservers.finishBroadcast();
4334 }
4335
4336 @VisibleForTesting
4337 void dispatchUidsChanged() {
4338 int N;
4339 synchronized (this) {
4340 N = mPendingUidChanges.size();
4341 if (mActiveUidChanges.length < N) {
4342 mActiveUidChanges = new UidRecord.ChangeItem[N];
4343 }
4344 for (int i=0; i<N; i++) {
4345 final UidRecord.ChangeItem change = mPendingUidChanges.get(i);
4346 mActiveUidChanges[i] = change;
4347 if (change.uidRecord != null) {
4348 change.uidRecord.pendingChange = null;
4349 change.uidRecord = null;
4350 }
4351 }
4352 mPendingUidChanges.clear();
4353 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
4354 "*** Delivering " + N + " uid changes");
4355 }
4356
4357 int i = mUidObservers.beginBroadcast();
4358 while (i > 0) {
4359 i--;
4360 dispatchUidsChangedForObserver(mUidObservers.getBroadcastItem(i),
4361 (UidObserverRegistration) mUidObservers.getBroadcastCookie(i), N);
4362 }
4363 mUidObservers.finishBroadcast();
4364
4365 if (VALIDATE_UID_STATES && mUidObservers.getRegisteredCallbackCount() > 0) {
4366 for (int j = 0; j < N; ++j) {
4367 final UidRecord.ChangeItem item = mActiveUidChanges[j];
4368 if (item.change == UidRecord.CHANGE_GONE
4369 || item.change == UidRecord.CHANGE_GONE_IDLE) {
4370 mValidateUids.remove(item.uid);
4371 } else {
4372 UidRecord validateUid = mValidateUids.get(item.uid);
4373 if (validateUid == null) {
4374 validateUid = new UidRecord(item.uid);
4375 mValidateUids.put(item.uid, validateUid);
4376 }
4377 if (item.change == UidRecord.CHANGE_IDLE) {
4378 validateUid.idle = true;
4379 } else if (item.change == UidRecord.CHANGE_ACTIVE) {
4380 validateUid.idle = false;
4381 }
4382 validateUid.curProcState = validateUid.setProcState = item.processState;
4383 validateUid.lastDispatchedProcStateSeq = item.procStateSeq;
4384 }
4385 }
4386 }
4387
4388 synchronized (this) {
4389 for (int j = 0; j < N; j++) {
4390 mAvailUidChanges.add(mActiveUidChanges[j]);
4391 }
4392 }
4393 }
4394
4395 private void dispatchUidsChangedForObserver(IUidObserver observer,
4396 UidObserverRegistration reg, int changesSize) {
4397 if (observer == null) {
4398 return;
4399 }
4400 try {
4401 for (int j = 0; j < changesSize; j++) {
4402 UidRecord.ChangeItem item = mActiveUidChanges[j];
4403 final int change = item.change;
4404 if (change == UidRecord.CHANGE_IDLE
4405 || change == UidRecord.CHANGE_GONE_IDLE) {
4406 if ((reg.which & ActivityManager.UID_OBSERVER_IDLE) != 0) {
4407 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
4408 "UID idle uid=" + item.uid);
4409 observer.onUidIdle(item.uid, item.ephemeral);
4410 }
4411 } else if (change == UidRecord.CHANGE_ACTIVE) {
4412 if ((reg.which & ActivityManager.UID_OBSERVER_ACTIVE) != 0) {
4413 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
4414 "UID active uid=" + item.uid);
4415 observer.onUidActive(item.uid);
4416 }
4417 }
4418 if (change == UidRecord.CHANGE_GONE
4419 || change == UidRecord.CHANGE_GONE_IDLE) {
4420 if ((reg.which & ActivityManager.UID_OBSERVER_GONE) != 0) {
4421 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
4422 "UID gone uid=" + item.uid);
4423 observer.onUidGone(item.uid, item.ephemeral);
4424 }
4425 if (reg.lastProcStates != null) {
4426 reg.lastProcStates.delete(item.uid);
4427 }
4428 } else {
4429 if ((reg.which & ActivityManager.UID_OBSERVER_PROCSTATE) != 0) {
4430 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
4431 "UID CHANGED uid=" + item.uid
4432 + ": " + item.processState);
4433 boolean doReport = true;
4434 if (reg.cutpoint >= ActivityManager.MIN_PROCESS_STATE) {
4435 final int lastState = reg.lastProcStates.get(item.uid,
4436 ActivityManager.PROCESS_STATE_UNKNOWN);
4437 if (lastState != ActivityManager.PROCESS_STATE_UNKNOWN) {
4438 final boolean lastAboveCut = lastState <= reg.cutpoint;
4439 final boolean newAboveCut = item.processState <= reg.cutpoint;
4440 doReport = lastAboveCut != newAboveCut;
4441 } else {
4442 doReport = item.processState
4443 != ActivityManager.PROCESS_STATE_NONEXISTENT;
4444 }
4445 }
4446 if (doReport) {
4447 if (reg.lastProcStates != null) {
4448 reg.lastProcStates.put(item.uid, item.processState);
4449 }
4450 observer.onUidStateChanged(item.uid, item.processState,
4451 item.procStateSeq);
4452 }
4453 }
4454 }
4455 }
4456 } catch (RemoteException e) {
4457 }
4458 }
4459

启动Activity相关

 4459
4460 @Override
4461 public final int startActivity(IApplicationThread caller, String callingPackage,
4462 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
4463 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
4464 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
4465 resultWho, requestCode, startFlags, profilerInfo, bOptions,
4466 UserHandle.getCallingUserId());
4467 }
4468
4469 final int startActivity(Intent intent, ActivityStackSupervisor.ActivityContainer container) {
4470 enforceNotIsolatedCaller("ActivityContainer.startActivity");
4471 final int userId = mUserController.handleIncomingUser(Binder.getCallingPid(),
4472 Binder.getCallingUid(), mStackSupervisor.mCurrentUser, false,
4473 ActivityManagerService.ALLOW_FULL_ONLY, "ActivityContainer", null);
4474
4475 // TODO: Switch to user app stacks here.
4476 String mimeType = intent.getType();
4477 final Uri data = intent.getData();
4478 if (mimeType == null && data != null && "content".equals(data.getScheme())) {
4479 mimeType = getProviderMimeType(data, userId);
4480 }
4481 container.checkEmbeddedAllowedInner(userId, intent, mimeType);
4482
4483 intent.addFlags(FORCE_NEW_TASK_FLAGS);
4484 return mActivityStarter.startActivityMayWait(null, -1, null, intent, mimeType, null, null,
4485 null, null, 0, 0, null, null, null, null, false, userId, container, null,
4486 "startActivity");
4487 }
4488
4489 @Override
4490 public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
4491 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
4492 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
4493 enforceNotIsolatedCaller("startActivity");
4494 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
4495 userId, false, ALLOW_FULL_ONLY, "startActivity", null);
4496 // TODO: Switch to user app stacks here.
4497 return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
4498 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
4499 profilerInfo, null, null, bOptions, false, userId, null, null,
4500 "startActivityAsUser");
4501 }
4502
4503 @Override
4504 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
4505 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
4506 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, boolean ignoreTargetSecurity,
4507 int userId) {
4508
4509 // This is very dangerous -- it allows you to perform a start activity (including
4510 // permission grants) as any app that may launch one of your own activities. So
4511 // we will only allow this to be done from activities that are part of the core framework,
4512 // and then only when they are running as the system.
4513 final ActivityRecord sourceRecord;
4514 final int targetUid;
4515 final String targetPackage;
4516 synchronized (this) {
4517 if (resultTo == null) {
4518 throw new SecurityException("Must be called from an activity");
4519 }
4520 sourceRecord = mStackSupervisor.isInAnyStackLocked(resultTo);
4521 if (sourceRecord == null) {
4522 throw new SecurityException("Called with bad activity token: " + resultTo);
4523 }
4524 if (!sourceRecord.info.packageName.equals("android")) {
4525 throw new SecurityException(
4526 "Must be called from an activity that is declared in the android package");
4527 }
4528 if (sourceRecord.app == null) {
4529 throw new SecurityException("Called without a process attached to activity");
4530 }
4531 if (UserHandle.getAppId(sourceRecord.app.uid) != SYSTEM_UID) {
4532 // This is still okay, as long as this activity is running under the
4533 // uid of the original calling activity.
4534 if (sourceRecord.app.uid != sourceRecord.launchedFromUid) {
4535 throw new SecurityException(
4536 "Calling activity in uid " + sourceRecord.app.uid
4537 + " must be system uid or original calling uid "
4538 + sourceRecord.launchedFromUid);
4539 }
4540 }
4541 if (ignoreTargetSecurity) {
4542 if (intent.getComponent() == null) {
4543 throw new SecurityException(
4544 "Component must be specified with ignoreTargetSecurity");
4545 }
4546 if (intent.getSelector() != null) {
4547 throw new SecurityException(
4548 "Selector not allowed with ignoreTargetSecurity");
4549 }
4550 }
4551 targetUid = sourceRecord.launchedFromUid;
4552 targetPackage = sourceRecord.launchedFromPackage;
4553 }
4554
4555 if (userId == UserHandle.USER_NULL) {
4556 userId = UserHandle.getUserId(sourceRecord.app.uid);
4557 }
4558
4559 // TODO: Switch to user app stacks here.
4560 try {
4561 int ret = mActivityStarter.startActivityMayWait(null, targetUid, targetPackage, intent,
4562 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, null,
4563 null, null, bOptions, ignoreTargetSecurity, userId, null, null,
4564 "startActivityAsCaller");
4565 return ret;
4566 } catch (SecurityException e) {
4567 // XXX need to figure out how to propagate to original app.
4568 // A SecurityException here is generally actually a fault of the original
4569 // calling activity (such as a fairly granting permissions), so propagate it
4570 // back to them.
4571 /*
4572 StringBuilder msg = new StringBuilder();
4573 msg.append("While launching");
4574 msg.append(intent.toString());
4575 msg.append(": ");
4576 msg.append(e.getMessage());
4577 */
4578 throw e;
4579 }
4580 }
4581
4582 @Override
4583 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
4584 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
4585 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
4586 enforceNotIsolatedCaller("startActivityAndWait");
4587 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
4588 userId, false, ALLOW_FULL_ONLY, "startActivityAndWait", null);
4589 WaitResult res = new WaitResult();
4590 // TODO: Switch to user app stacks here.
4591 mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
4592 null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, res, null,
4593 bOptions, false, userId, null, null, "startActivityAndWait");
4594 return res;
4595 }
4596
4597 @Override
4598 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
4599 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
4600 int startFlags, Configuration config, Bundle bOptions, int userId) {
4601 enforceNotIsolatedCaller("startActivityWithConfig");
4602 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
4603 userId, false, ALLOW_FULL_ONLY, "startActivityWithConfig", null);
4604 // TODO: Switch to user app stacks here.
4605 int ret = mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
4606 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
4607 null, null, config, bOptions, false, userId, null, null, "startActivityWithConfig");
4608 return ret;
4609 }
4610
4611 @Override
4612 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
4613 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
4614 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions)
4615 throws TransactionTooLargeException {
4616 enforceNotIsolatedCaller("startActivityIntentSender");
4617 // Refuse possible leaked file descriptors
4618 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
4619 throw new IllegalArgumentException("File descriptors passed in Intent");
4620 }
4621
4622 if (!(target instanceof PendingIntentRecord)) {
4623 throw new IllegalArgumentException("Bad PendingIntent object");
4624 }
4625
4626 PendingIntentRecord pir = (PendingIntentRecord)target;
4627
4628 synchronized (this) {
4629 // If this is coming from the currently resumed activity, it is
4630 // effectively saying that app switches are allowed at this point.
4631 final ActivityStack stack = getFocusedStack();
4632 if (stack.mResumedActivity != null &&
4633 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
4634 mAppSwitchesAllowedTime = 0;
4635 }
4636 }
4637 int ret = pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
4638 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions, null);
4639 return ret;
4640 }
4641
4642 @Override
4643 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
4644 Intent intent, String resolvedType, IVoiceInteractionSession session,
4645 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
4646 Bundle bOptions, int userId) {
4647 if (checkCallingPermission(Manifest.permission.BIND_VOICE_INTERACTION)
4648 != PackageManager.PERMISSION_GRANTED) {
4649 String msg = "Permission Denial: startVoiceActivity() from pid="
4650 + Binder.getCallingPid()
4651 + ", uid=" + Binder.getCallingUid()
4652 + " requires " + android.Manifest.permission.BIND_VOICE_INTERACTION;
4653 Slog.w(TAG, msg);
4654 throw new SecurityException(msg);
4655 }
4656 if (session == null || interactor == null) {
4657 throw new NullPointerException("null session or interactor");
4658 }
4659 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
4660 ALLOW_FULL_ONLY, "startVoiceActivity", null);
4661 // TODO: Switch to user app stacks here.
4662 return mActivityStarter.startActivityMayWait(null, callingUid, callingPackage, intent,
4663 resolvedType, session, interactor, null, null, 0, startFlags, profilerInfo, null,
4664 null, bOptions, false, userId, null, null, "startVoiceActivity");
4665 }
4666
4667 @Override
4668 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
4669 Intent intent, String resolvedType, Bundle bOptions, int userId) {
4670 if (checkCallingPermission(Manifest.permission.BIND_VOICE_INTERACTION)
4671 != PackageManager.PERMISSION_GRANTED) {
4672 final String msg = "Permission Denial: startAssistantActivity() from pid="
4673 + Binder.getCallingPid()
4674 + ", uid=" + Binder.getCallingUid()
4675 + " requires " + Manifest.permission.BIND_VOICE_INTERACTION;
4676 Slog.w(TAG, msg);
4677 throw new SecurityException(msg);
4678 }
4679 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
4680 ALLOW_FULL_ONLY, "startAssistantActivity", null);
4681 return mActivityStarter.startActivityMayWait(null, callingUid, callingPackage, intent,
4682 resolvedType, null, null, null, null, 0, 0, null, null, null, bOptions, false,
4683 userId, null, null, "startAssistantActivity");
4684 }
4685

start,stop本地音频交互

 4686    @Override
4687 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options)
4688 throws RemoteException {
4689 Slog.i(TAG, "Activity tried to startVoiceInteraction");
4690 synchronized (this) {
4691 ActivityRecord activity = getFocusedStack().topActivity();
4692 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4693 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4694 }
4695 if (mRunningVoice != null || activity.getTask().voiceSession != null
4696 || activity.voiceSession != null) {
4697 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4698 return;
4699 }
4700 if (activity.pendingVoiceInteractionStart) {
4701 Slog.w(TAG, "Pending start of voice interaction already.");
4702 return;
4703 }
4704 activity.pendingVoiceInteractionStart = true;
4705 }
4706 LocalServices.getService(VoiceInteractionManagerInternal.class)
4707 .startLocalVoiceInteraction(callingActivity, options);
4708 }
4709
4710 @Override
4711 public void stopLocalVoiceInteraction(IBinder callingActivity) throws RemoteException {
4712 LocalServices.getService(VoiceInteractionManagerInternal.class)
4713 .stopLocalVoiceInteraction(callingActivity);
4714 }
4715

语音相关

 4716    @Override
4717 public boolean supportsLocalVoiceInteraction() throws RemoteException {
4718 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4719 .supportsLocalVoiceInteraction();
4720 }
4721
4722 void onLocalVoiceInteractionStartedLocked(IBinder activity,
4723 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
4724 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
4725 if (activityToCallback == null) return;
4726 activityToCallback.setVoiceSessionLocked(voiceSession);
4727
4728 // Inform the activity
4729 try {
4730 activityToCallback.app.thread.scheduleLocalVoiceInteractionStarted(activity,
4731 voiceInteractor);
4732 long token = Binder.clearCallingIdentity();
4733 try {
4734 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
4735 } finally {
4736 Binder.restoreCallingIdentity(token);
4737 }
4738 // TODO: VI Should we cache the activity so that it's easier to find later
4739 // rather than scan through all the stacks and activities?
4740 } catch (RemoteException re) {
4741 activityToCallback.clearVoiceSessionLocked();
4742 // TODO: VI Should this terminate the voice session?
4743 }
4744 }
4745
4746 @Override
4747 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
4748 synchronized (this) {
4749 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
4750 if (keepAwake) {
4751 mVoiceWakeLock.acquire();
4752 } else {
4753 mVoiceWakeLock.release();
4754 }
4755 }
4756 }
4757 }

start activity相关

 4759    @Override
4760 public boolean startNextMatchingActivity(IBinder callingActivity,
4761 Intent intent, Bundle bOptions) {
4762 // Refuse possible leaked file descriptors
4763 if (intent != null && intent.hasFileDescriptors() == true) {
4764 throw new IllegalArgumentException("File descriptors passed in Intent");
4765 }
4766 ActivityOptions options = ActivityOptions.fromBundle(bOptions);
4767
4768 synchronized (this) {
4769 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
4770 if (r == null) {
4771 ActivityOptions.abort(options);
4772 return false;
4773 }
4774 if (r.app == null || r.app.thread == null) {
4775 // The caller is not running... d'oh!
4776 ActivityOptions.abort(options);
4777 return false;
4778 }
4779 intent = new Intent(intent);
4780 // The caller is not allowed to change the data.
4781 intent.setDataAndType(r.intent.getData(), r.intent.getType());
4782 // And we are resetting to find the next component...
4783 intent.setComponent(null);
4784
4785 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4786
4787 ActivityInfo aInfo = null;
4788 try {
4789 List<ResolveInfo> resolves =
4790 AppGlobals.getPackageManager().queryIntentActivities(
4791 intent, r.resolvedType,
4792 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
4793 UserHandle.getCallingUserId()).getList();
4794
4795 // Look for the original activity in the list...
4796 final int N = resolves != null ? resolves.size() : 0;
4797 for (int i=0; i<N; i++) {
4798 ResolveInfo rInfo = resolves.get(i);
4799 if (rInfo.activityInfo.packageName.equals(r.packageName)
4800 && rInfo.activityInfo.name.equals(r.info.name)) {
4801 // We found the current one... the next matching is
4802 // after it.
4803 i++;
4804 if (i<N) {
4805 aInfo = resolves.get(i).activityInfo;
4806 }
4807 if (debug) {
4808 Slog.v(TAG, "Next matching activity: found current " + r.packageName
4809 + "/" + r.info.name);
4810 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
4811 ? "null" : aInfo.packageName + "/" + aInfo.name));
4812 }
4813 break;
4814 }
4815 }
4816 } catch (RemoteException e) {
4817 }
4818
4819 if (aInfo == null) {
4820 // Nobody who is next!
4821 ActivityOptions.abort(options);
4822 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
4823 return false;
4824 }
4825
4826 intent.setComponent(new ComponentName(
4827 aInfo.applicationInfo.packageName, aInfo.name));
4828 intent.setFlags(intent.getFlags()&~(
4829 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
4830 Intent.FLAG_ACTIVITY_CLEAR_TOP|
4831 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
4832 Intent.FLAG_ACTIVITY_NEW_TASK));
4833
4834 // Okay now we need to start the new activity, replacing the
4835 // currently running activity. This is a little tricky because
4836 // we want to start the new one as if the current one is finished,
4837 // but not finish the current one first so that there is no flicker.
4838 // And thus...
4839 final boolean wasFinishing = r.finishing;
4840 r.finishing = true;
4841
4842 // Propagate reply information over to the new activity.
4843 final ActivityRecord resultTo = r.resultTo;
4844 final String resultWho = r.resultWho;
4845 final int requestCode = r.requestCode;
4846 r.resultTo = null;
4847 if (resultTo != null) {
4848 resultTo.removeResultsLocked(r, resultWho, requestCode);
4849 }
4850
4851 final long origId = Binder.clearCallingIdentity();
4852 int res = mActivityStarter.startActivityLocked(r.app.thread, intent,
4853 null /*ephemeralIntent*/, r.resolvedType, aInfo, null /*rInfo*/, null,
4854 null, resultTo != null ? resultTo.appToken : null, resultWho, requestCode, -1,
4855 r.launchedFromUid, r.launchedFromPackage, -1, r.launchedFromUid, 0, options,
4856 false, false, null, null, null, "startNextMatchingActivity");
4857 Binder.restoreCallingIdentity(origId);
4858
4859 r.finishing = wasFinishing;
4860 if (res != ActivityManager.START_SUCCESS) {
4861 return false;
4862 }
4863 return true;
4864 }
4865 }
4866
4867 @Override
4868 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
4869 if (checkCallingPermission(START_TASKS_FROM_RECENTS) != PackageManager.PERMISSION_GRANTED) {
4870 String msg = "Permission Denial: startActivityFromRecents called without " +
4871 START_TASKS_FROM_RECENTS;
4872 Slog.w(TAG, msg);
4873 throw new SecurityException(msg);
4874 }
4875 final long origId = Binder.clearCallingIdentity();
4876 try {
4877 synchronized (this) {
4878 return mStackSupervisor.startActivityFromRecentsInner(taskId, bOptions);
4879 }
4880 } finally {
4881 Binder.restoreCallingIdentity(origId);
4882 }
4883 }
4884
4885 final int startActivityInPackage(int uid, String callingPackage,
4886 Intent intent, String resolvedType, IBinder resultTo,
4887 String resultWho, int requestCode, int startFlags, Bundle bOptions, int userId,
4888 IActivityContainer container, TaskRecord inTask, String reason) {
4889
4890 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
4891 userId, false, ALLOW_FULL_ONLY, "startActivityInPackage", null);
4892
4893 // TODO: Switch to user app stacks here.
4894 int ret = mActivityStarter.startActivityMayWait(null, uid, callingPackage, intent,
4895 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
4896 null, null, null, bOptions, false, userId, container, inTask, reason);
4897 return ret;
4898 }
4899
4900 @Override
4901 public final int startActivities(IApplicationThread caller, String callingPackage,
4902 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
4903 int userId) {
4904 final String reason = "startActivities";
4905 enforceNotIsolatedCaller(reason);
4906 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
4907 userId, false, ALLOW_FULL_ONLY, reason, null);
4908 // TODO: Switch to user app stacks here.
4909 int ret = mActivityStarter.startActivities(caller, -1, callingPackage, intents,
4910 resolvedTypes, resultTo, bOptions, userId, reason);
4911 return ret;
4912 }
4913
4914 final int startActivitiesInPackage(int uid, String callingPackage,
4915 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
4916 Bundle bOptions, int userId) {
4917
4918 final String reason = "startActivityInPackage";
4919 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
4920 userId, false, ALLOW_FULL_ONLY, reason, null);
4921 // TODO: Switch to user app stacks here.
4922 int ret = mActivityStarter.startActivities(null, uid, callingPackage, intents, resolvedTypes,
4923 resultTo, bOptions, userId, reason);
4924 return ret;
4925 }

报告activity完全被绘制

 4927    @Override
4928 public void reportActivityFullyDrawn(IBinder token) {
4929 synchronized (this) {
4930 ActivityRecord r = ActivityRecord.isInStackLocked(token);
4931 if (r == null) {
4932 return;
4933 }
4934 r.reportFullyDrawnLocked();
4935 }
4936 }

设置、获取请求的方向

 4938    @Override
4939 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
4940 synchronized (this) {
4941 ActivityRecord r = ActivityRecord.isInStackLocked(token);
4942 if (r == null) {
4943 return;
4944 }
4945 final long origId = Binder.clearCallingIdentity();
4946 try {
4947 r.setRequestedOrientation(requestedOrientation);
4948 } finally {
4949 Binder.restoreCallingIdentity(origId);
4950 }
4951 }
4952 }
4953
4954 @Override
4955 public int getRequestedOrientation(IBinder token) {
4956 synchronized (this) {
4957 ActivityRecord r = ActivityRecord.isInStackLocked(token);
4958 if (r == null) {
4959 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
4960 }
4961 return r.getRequestedOrientation();
4962 }
4963 }

请求activity重新启动

 4965    @Override
4966 public final void requestActivityRelaunch(IBinder token) {
4967 synchronized(this) {
4968 ActivityRecord r = ActivityRecord.isInStackLocked(token);
4969 if (r == null) {
4970 return;
4971 }
4972 final long origId = Binder.clearCallingIdentity();
4973 try {
4974 r.forceNewConfig = true;
4975 r.ensureActivityConfigurationLocked(0 /* globalChanges */,
4976 true /* preserveWindow */);
4977 } finally {
4978 Binder.restoreCallingIdentity(origId);
4979 }
4980 }
4981 }

结束activity

 4983    /**
4984 * This is the internal entry point for handling Activity.finish().
4985 *
4986 * @param token The Binder token referencing the Activity we want to finish.
4987 * @param resultCode Result code, if any, from this Activity.
4988 * @param resultData Result data (Intent), if any, from this Activity.
4989 * @param finishTask Whether to finish the task associated with this Activity.
4990 *
4991 * @return Returns true if the activity successfully finished, or false if it is still running.
4992 */
4993 @Override
4994 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
4995 int finishTask) {
4996 // Refuse possible leaked file descriptors
4997 if (resultData != null && resultData.hasFileDescriptors() == true) {
4998 throw new IllegalArgumentException("File descriptors passed in Intent");
4999 }
5000
5001 synchronized(this) {
5002 ActivityRecord r = ActivityRecord.isInStackLocked(token);
5003 if (r == null) {
5004 return true;
5005 }
5006 // Keep track of the root activity of the task before we finish it
5007 TaskRecord tr = r.getTask();
5008 ActivityRecord rootR = tr.getRootActivity();
5009 if (rootR == null) {
5010 Slog.w(TAG, "Finishing task with all activities already finished");
5011 }
5012 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
5013 // finish.
5014 if (tr.mLockTaskAuth != LOCK_TASK_AUTH_LAUNCHABLE_PRIV && rootR == r &&
5015 mStackSupervisor.isLastLockedTask(tr)) {
5016 Slog.i(TAG, "Not finishing task in lock task mode");
5017 mStackSupervisor.showLockTaskToast();
5018 return false;
5019 }
5020 if (mController != null) {
5021 // Find the first activity that is not finishing.
5022 ActivityRecord next = r.getStack().topRunningActivityLocked(token, 0);
5023 if (next != null) {
5024 // ask watcher if this is allowed
5025 boolean resumeOK = true;
5026 try {
5027 resumeOK = mController.activityResuming(next.packageName);
5028 } catch (RemoteException e) {
5029 mController = null;
5030 Watchdog.getInstance().setActivityController(null);
5031 }
5032
5033 if (!resumeOK) {
5034 Slog.i(TAG, "Not finishing activity because controller resumed");
5035 return false;
5036 }
5037 }
5038 }
5039 final long origId = Binder.clearCallingIdentity();
5040 try {
5041 boolean res;
5042 final boolean finishWithRootActivity =
5043 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
5044 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
5045 || (finishWithRootActivity && r == rootR)) {
5046 // If requested, remove the task that is associated to this activity only if it
5047 // was the root activity in the task. The result code and data is ignored
5048 // because we don't support returning them across task boundaries. Also, to
5049 // keep backwards compatibility we remove the task from recents when finishing
5050 // task with root activity.
5051 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false, finishWithRootActivity);
5052 if (!res) {
5053 Slog.i(TAG, "Removing task failed to finish activity");
5054 }
5055 } else {
5056 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
5057 resultData, "app-request", true);
5058 if (!res) {
5059 Slog.i(TAG, "Failed to finish by app-request");
5060 }
5061 }
5062 return res;
5063 } finally {
5064 Binder.restoreCallingIdentity(origId);
5065 }
5066 }
5067 }

结束高权重程序

 5069    @Override
5070 public final void finishHeavyWeightApp() {
5071 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
5072 != PackageManager.PERMISSION_GRANTED) {
5073 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
5074 + Binder.getCallingPid()
5075 + ", uid=" + Binder.getCallingUid()
5076 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
5077 Slog.w(TAG, msg);
5078 throw new SecurityException(msg);
5079 }
5080
5081 synchronized(this) {
5082 if (mHeavyWeightProcess == null) {
5083 return;
5084 }
5085
5086 ArrayList<ActivityRecord> activities = new ArrayList<>(mHeavyWeightProcess.activities);
5087 for (int i = 0; i < activities.size(); i++) {
5088 ActivityRecord r = activities.get(i);
5089 if (!r.finishing && r.isInStackLocked()) {
5090 r.getStack().finishActivityLocked(r, Activity.RESULT_CANCELED,
5091 null, "finish-heavy", true);
5092 }
5093 }
5094
5095 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
5096 mHeavyWeightProcess.userId, 0));
5097 mHeavyWeightProcess = null;
5098 }
5099 }

崩溃应用程序

 5101    @Override
5102 public void crashApplication(int uid, int initialPid, String packageName, int userId,
5103 String message) {
5104 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
5105 != PackageManager.PERMISSION_GRANTED) {
5106 String msg = "Permission Denial: crashApplication() from pid="
5107 + Binder.getCallingPid()
5108 + ", uid=" + Binder.getCallingUid()
5109 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
5110 Slog.w(TAG, msg);
5111 throw new SecurityException(msg);
5112 }
5113
5114 synchronized(this) {
5115 mAppErrors.scheduleAppCrashLocked(uid, initialPid, packageName, userId, message);
5116 }
5117 }

结束、释放Activity、task

 5119    @Override
5120 public final void finishSubActivity(IBinder token, String resultWho,
5121 int requestCode) {
5122 synchronized(this) {
5123 final long origId = Binder.clearCallingIdentity();
5124 ActivityRecord r = ActivityRecord.isInStackLocked(token);
5125 if (r != null) {
5126 r.getStack().finishSubActivityLocked(r, resultWho, requestCode);
5127 }
5128 Binder.restoreCallingIdentity(origId);
5129 }
5130 }
5131
5132 @Override
5133 public boolean finishActivityAffinity(IBinder token) {
5134 synchronized(this) {
5135 final long origId = Binder.clearCallingIdentity();
5136 try {
5137 ActivityRecord r = ActivityRecord.isInStackLocked(token);
5138 if (r == null) {
5139 return false;
5140 }
5141
5142 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
5143 // can finish.
5144 final TaskRecord task = r.getTask();
5145 if (task.mLockTaskAuth != LOCK_TASK_AUTH_LAUNCHABLE_PRIV &&
5146 mStackSupervisor.isLastLockedTask(task) && task.getRootActivity() == r) {
5147 mStackSupervisor.showLockTaskToast();
5148 return false;
5149 }
5150 return task.getStack().finishActivityAffinityLocked(r);
5151 } finally {
5152 Binder.restoreCallingIdentity(origId);
5153 }
5154 }
5155 }
5156
5157 @Override
5158 public void finishVoiceTask(IVoiceInteractionSession session) {
5159 synchronized (this) {
5160 final long origId = Binder.clearCallingIdentity();
5161 try {
5162 // TODO: VI Consider treating local voice interactions and voice tasks
5163 // differently here
5164 mStackSupervisor.finishVoiceTask(session);
5165 } finally {
5166 Binder.restoreCallingIdentity(origId);
5167 }
5168 }
5169
5170 }
5171
5172 @Override
5173 public boolean releaseActivityInstance(IBinder token) {
5174 synchronized(this) {
5175 final long origId = Binder.clearCallingIdentity();
5176 try {
5177 ActivityRecord r = ActivityRecord.isInStackLocked(token);
5178 if (r == null) {
5179 return false;
5180 }
5181 return r.getStack().safelyDestroyActivityLocked(r, "app-req");
5182 } finally {
5183 Binder.restoreCallingIdentity(origId);
5184 }
5185 }
5186 }
5187
5188 @Override
5189 public void releaseSomeActivities(IApplicationThread appInt) {
5190 synchronized(this) {
5191 final long origId = Binder.clearCallingIdentity();
5192 try {
5193 ProcessRecord app = getRecordForAppLocked(appInt);
5194 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
5195 } finally {
5196 Binder.restoreCallingIdentity(origId);
5197 }
5198 }
5199 }

是否Activity可见

 5201    @Override
5202 public boolean willActivityBeVisible(IBinder token) {
5203 synchronized(this) {
5204 ActivityStack stack = ActivityRecord.getStackLocked(token);
5205 if (stack != null) {
5206 return stack.willActivityBeVisibleLocked(token);
5207 }
5208 return false;
5209 }
5210 }

覆盖延迟的窗口过渡

 5212    @Override
5213 public void overridePendingTransition(IBinder token, String packageName,
5214 int enterAnim, int exitAnim) {
5215 synchronized(this) {
5216 ActivityRecord self = ActivityRecord.isInStackLocked(token);
5217 if (self == null) {
5218 return;
5219 }
5220
5221 final long origId = Binder.clearCallingIdentity();
5222
5223 if (self.state == ActivityState.RESUMED
5224 || self.state == ActivityState.PAUSING) {
5225 mWindowManager.overridePendingAppTransition(packageName,
5226 enterAnim, exitAnim, null);
5227 }
5228
5229 Binder.restoreCallingIdentity(origId);
5230 }
5231 }

处理app死亡

 5233    /**
5234 * Main function for removing an existing process from the activity manager
5235 * as a result of that process going away. Clears out all connections
5236 * to the process.
5237 */
5238 private final void handleAppDiedLocked(ProcessRecord app,
5239 boolean restarting, boolean allowRestart) {
5240 int pid = app.pid;
5241 boolean kept = cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1,
5242 false /*replacingPid*/);
5243 if (!kept && !restarting) {
5244 removeLruProcessLocked(app);
5245 if (pid > 0) {
5246 ProcessList.remove(pid);
5247 }
5248 }
5249
5250 if (mProfileProc == app) {
5251 clearProfilerLocked();
5252 }
5253
5254 // Remove this application's activities from active lists.
5255 boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(app);
5256
5257 app.activities.clear();
5258
5259 if (app.instr != null) {
5260 Slog.w(TAG, "Crash of app " + app.processName
5261 + " running instrumentation " + app.instr.mClass);
5262 Bundle info = new Bundle();
5263 info.putString("shortMsg", "Process crashed.");
5264 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
5265 }
5266
5267 mWindowManager.deferSurfaceLayout();
5268 try {
5269 if (!restarting && hasVisibleActivities
5270 && !mStackSupervisor.resumeFocusedStackTopActivityLocked()) {
5271 // If there was nothing to resume, and we are not already restarting this process, but
5272 // there is a visible activity that is hosted by the process... then make sure all
5273 // visible activities are running, taking care of restarting this process.
5274 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5275 }
5276 } finally {
5277 mWindowManager.continueSurfaceLayout();
5278 }
5279 }

获取app lru record和record

 5281    private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
5282 final IBinder threadBinder = thread.asBinder();
5283 // Find the application record.
5284 for (int i=mLruProcesses.size()-1; i>=0; i--) {
5285 final ProcessRecord rec = mLruProcesses.get(i);
5286 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
5287 return i;
5288 }
5289 }
5290 return -1;
5291 }
5292
5293 final ProcessRecord getRecordForAppLocked(
5294 IApplicationThread thread) {
5295 if (thread == null) {
5296 return null;
5297 }
5298
5299 int appIndex = getLRURecordIndexForAppLocked(thread);
5300 if (appIndex >= 0) {
5301 return mLruProcesses.get(appIndex);
5302 }
5303
5304 // Validation: if it isn't in the LRU list, it shouldn't exist, but let's
5305 // double-check that.
5306 final IBinder threadBinder = thread.asBinder();
5307 final ArrayMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5308 for (int i = pmap.size()-1; i >= 0; i--) {
5309 final SparseArray<ProcessRecord> procs = pmap.valueAt(i);
5310 for (int j = procs.size()-1; j >= 0; j--) {
5311 final ProcessRecord proc = procs.valueAt(j);
5312 if (proc.thread != null && proc.thread.asBinder() == threadBinder) {
5313 Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: "
5314 + proc);
5315 return proc;
5316 }
5317 }
5318 }
5319
5320 return null;
5321 }

做低内存report

 5323    final void doLowMemReportIfNeededLocked(ProcessRecord dyingProc) {
5324 // If there are no longer any background processes running,
5325 // and the app that died was not running instrumentation,
5326 // then tell everyone we are now low on memory.
5327 boolean haveBg = false;
5328 for (int i=mLruProcesses.size()-1; i>=0; i--) {
5329 ProcessRecord rec = mLruProcesses.get(i);
5330 if (rec.thread != null
5331 && rec.setProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) {
5332 haveBg = true;
5333 break;
5334 }
5335 }
5336
5337 if (!haveBg) {
5338 boolean doReport = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
5339 if (doReport) {
5340 long now = SystemClock.uptimeMillis();
5341 if (now < (mLastMemUsageReportTime+5*60*1000)) {
5342 doReport = false;
5343 } else {
5344 mLastMemUsageReportTime = now;
5345 }
5346 }
5347 final ArrayList<ProcessMemInfo> memInfos
5348 = doReport ? new ArrayList<ProcessMemInfo>(mLruProcesses.size()) : null;
5349 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
5350 long now = SystemClock.uptimeMillis();
5351 for (int i=mLruProcesses.size()-1; i>=0; i--) {
5352 ProcessRecord rec = mLruProcesses.get(i);
5353 if (rec == dyingProc || rec.thread == null) {
5354 continue;
5355 }
5356 if (doReport) {
5357 memInfos.add(new ProcessMemInfo(rec.processName, rec.pid, rec.setAdj,
5358 rec.setProcState, rec.adjType, rec.makeAdjReason()));
5359 }
5360 if ((rec.lastLowMemory+mConstants.GC_MIN_INTERVAL) <= now) {
5361 // The low memory report is overriding any current
5362 // state for a GC request. Make sure to do
5363 // heavy/important/visible/foreground processes first.
5364 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
5365 rec.lastRequestedGc = 0;
5366 } else {
5367 rec.lastRequestedGc = rec.lastLowMemory;
5368 }
5369 rec.reportLowMemory = true;
5370 rec.lastLowMemory = now;
5371 mProcessesToGc.remove(rec);
5372 addProcessToGcListLocked(rec);
5373 }
5374 }
5375 if (doReport) {
5376 Message msg = mHandler.obtainMessage(REPORT_MEM_USAGE_MSG, memInfos);
5377 mHandler.sendMessage(msg);
5378 }
5379 scheduleAppGcsLocked();
5380 }
5381 }

app死亡处理

 5383    final void appDiedLocked(ProcessRecord app) {
5384 appDiedLocked(app, app.pid, app.thread, false);
5385 }
5386
5387 final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread,
5388 boolean fromBinderDied) {
5389 // First check if this ProcessRecord is actually active for the pid.
5390 synchronized (mPidsSelfLocked) {
5391 ProcessRecord curProc = mPidsSelfLocked.get(pid);
5392 if (curProc != app) {
5393 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc);
5394 return;
5395 }
5396 }
5397
5398 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
5399 synchronized (stats) {
5400 stats.noteProcessDiedLocked(app.info.uid, pid);
5401 }
5402
5403 if (!app.killed) {
5404 if (!fromBinderDied) {
5405 killProcessQuiet(pid);
5406 }
5407 killProcessGroup(app.uid, pid);
5408 app.killed = true;
5409 }
5410
5411 // Clean up already done if the process has been re-started.
5412 if (app.pid == pid && app.thread != null &&
5413 app.thread.asBinder() == thread.asBinder()) {
5414 boolean doLowMem = app.instr == null;
5415 boolean doOomAdj = doLowMem;
5416 if (!app.killedByAm) {
5417 Slog.i(TAG, "Process " + app.processName + " (pid " + pid + ") has died: "
5418 + ProcessList.makeOomAdjString(app.setAdj)
5419 + ProcessList.makeProcStateString(app.setProcState));
5420 mAllowLowerMemLevel = true;
5421 } else {
5422 // Note that we always want to do oom adj to update our state with the
5423 // new number of procs.
5424 mAllowLowerMemLevel = false;
5425 doLowMem = false;
5426 }
5427 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName,
5428 app.setAdj, app.setProcState);
5429 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
5430 "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder());
5431 handleAppDiedLocked(app, false, true);
5432
5433 if (doOomAdj) {
5434 updateOomAdjLocked();
5435 }
5436 if (doLowMem) {
5437 doLowMemReportIfNeededLocked(app);
5438 }
5439 } else if (app.pid != pid) {
5440 // A new process has already been started.
5441 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
5442 + ") has died and restarted (pid " + app.pid + ").");
5443 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
5444 } else if (DEBUG_PROCESSES) {
5445 Slog.d(TAG_PROCESSES, "Received spurious death notification for thread "
5446 + thread.asBinder());
5447 }
5448 }

dump state

 5450    /**
5451 * If a stack trace dump file is configured, dump process stack traces.
5452 * @param clearTraces causes the dump file to be erased prior to the new
5453 * traces being written, if true; when false, the new traces will be
5454 * appended to any existing file content.
5455 * @param firstPids of dalvik VM processes to dump stack traces for first
5456 * @param lastPids of dalvik VM processes to dump stack traces for last
5457 * @param nativePids optional list of native pids to dump stack crawls
5458 * @return file containing stack traces, or null if no dump file is configured
5459 */
5460 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
5461 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids,
5462 ArrayList<Integer> nativePids) {
5463 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
5464 if (tracesPath == null || tracesPath.length() == 0) {
5465 return null;
5466 }
5467
5468 File tracesFile = new File(tracesPath);
5469 try {
5470 if (clearTraces && tracesFile.exists()) tracesFile.delete();
5471 tracesFile.createNewFile();
5472 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5473 } catch (IOException e) {
5474 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
5475 return null;
5476 }
5477
5478 dumpStackTraces(tracesPath, firstPids, processCpuTracker, lastPids, nativePids);
5479 return tracesFile;
5480 }
5481
5482 public static class DumpStackFileObserver extends FileObserver {
5483 // Keep in sync with frameworks/native/cmds/dumpstate/utils.cpp
5484 private static final int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
5485 static final int NATIVE_DUMP_TIMEOUT_MS = 2000; // 2 seconds;
5486
5487 private final String mTracesPath;
5488 private boolean mClosed;
5489
5490 public DumpStackFileObserver(String tracesPath) {
5491 super(tracesPath, FileObserver.CLOSE_WRITE);
5492 mTracesPath = tracesPath;
5493 }
5494
5495 @Override
5496 public synchronized void onEvent(int event, String path) {
5497 mClosed = true;
5498 notify();
5499 }
5500
5501 public long dumpWithTimeout(int pid, long timeout) {
5502 sendSignal(pid, SIGNAL_QUIT);
5503 final long start = SystemClock.elapsedRealtime();
5504
5505 final long waitTime = Math.min(timeout, TRACE_DUMP_TIMEOUT_MS);
5506 synchronized (this) {
5507 try {
5508 wait(waitTime); // Wait for traces file to be closed.
5509 } catch (InterruptedException e) {
5510 Slog.wtf(TAG, e);
5511 }
5512 }
5513
5514 // This avoids a corner case of passing a negative time to the native
5515 // trace in case we've already hit the overall timeout.
5516 final long timeWaited = SystemClock.elapsedRealtime() - start;
5517 if (timeWaited >= timeout) {
5518 return timeWaited;
5519 }
5520
5521 if (!mClosed) {
5522 Slog.w(TAG, "Didn't see close of " + mTracesPath + " for pid " + pid +
5523 ". Attempting native stack collection.");
5524
5525 final long nativeDumpTimeoutMs = Math.min(
5526 NATIVE_DUMP_TIMEOUT_MS, timeout - timeWaited);
5527
5528 Debug.dumpNativeBacktraceToFileTimeout(pid, mTracesPath,
5529 (int) (nativeDumpTimeoutMs / 1000));
5530 }
5531
5532 final long end = SystemClock.elapsedRealtime();
5533 mClosed = false;
5534
5535 return (end - start);
5536 }
5537 }
5538
5539 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
5540 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids,
5541 ArrayList<Integer> nativePids) {
5542 // Use a FileObserver to detect when traces finish writing.
5543 // The order of traces is considered important to maintain for legibility.
5544 DumpStackFileObserver observer = new DumpStackFileObserver(tracesPath);
5545
5546 // We must complete all stack dumps within 20 seconds.
5547 long remainingTime = 20 * 1000;
5548 try {
5549 observer.startWatching();
5550
5551 // First collect all of the stacks of the most important pids.
5552 if (firstPids != null) {
5553 int num = firstPids.size();
5554 for (int i = 0; i < num; i++) {
5555 if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for pid "
5556 + firstPids.get(i));
5557 final long timeTaken = observer.dumpWithTimeout(firstPids.get(i), remainingTime);
5558
5559 remainingTime -= timeTaken;
5560 if (remainingTime <= 0) {
5561 Slog.e(TAG, "Aborting stack trace dump (current firstPid=" + firstPids.get(i) +
5562 "); deadline exceeded.");
5563 return;
5564 }
5565
5566 if (DEBUG_ANR) {
5567 Slog.d(TAG, "Done with pid " + firstPids.get(i) + " in " + timeTaken + "ms");
5568 }
5569 }
5570 }
5571
5572 // Next collect the stacks of the native pids
5573 if (nativePids != null) {
5574 for (int pid : nativePids) {
5575 if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for native pid " + pid);
5576 final long nativeDumpTimeoutMs = Math.min(
5577 DumpStackFileObserver.NATIVE_DUMP_TIMEOUT_MS, remainingTime);
5578
5579 final long start = SystemClock.elapsedRealtime();
5580 Debug.dumpNativeBacktraceToFileTimeout(
5581 pid, tracesPath, (int) (nativeDumpTimeoutMs / 1000));
5582 final long timeTaken = SystemClock.elapsedRealtime() - start;
5583
5584 remainingTime -= timeTaken;
5585 if (remainingTime <= 0) {
5586 Slog.e(TAG, "Aborting stack trace dump (current native pid=" + pid +
5587 "); deadline exceeded.");
5588 return;
5589 }
5590
5591 if (DEBUG_ANR) {
5592 Slog.d(TAG, "Done with native pid " + pid + " in " + timeTaken + "ms");
5593 }
5594 }
5595 }
5596
5597 // Lastly, measure CPU usage.
5598 if (processCpuTracker != null) {
5599 processCpuTracker.init();
5600 System.gc();
5601 processCpuTracker.update();
5602 try {
5603 synchronized (processCpuTracker) {
5604 processCpuTracker.wait(500); // measure over 1/2 second.
5605 }
5606 } catch (InterruptedException e) {
5607 }
5608 processCpuTracker.update();
5609
5610 // We'll take the stack crawls of just the top apps using CPU.
5611 final int N = processCpuTracker.countWorkingStats();
5612 int numProcs = 0;
5613 for (int i=0; i<N && numProcs<5; i++) {
5614 ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i);
5615 if (lastPids.indexOfKey(stats.pid) >= 0) {
5616 numProcs++;
5617
5618 if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for extra pid " + stats.pid);
5619
5620 final long timeTaken = observer.dumpWithTimeout(stats.pid, remainingTime);
5621 remainingTime -= timeTaken;
5622 if (remainingTime <= 0) {
5623 Slog.e(TAG, "Aborting stack trace dump (current extra pid=" + stats.pid +
5624 "); deadline exceeded.");
5625 return;
5626 }
5627
5628 if (DEBUG_ANR) {
5629 Slog.d(TAG, "Done with extra pid " + stats.pid + " in " + timeTaken + "ms");
5630 }
5631 } else if (DEBUG_ANR) {
5632 Slog.d(TAG, "Skipping next CPU consuming process, not a java proc: "
5633 + stats.pid);
5634 }
5635 }
5636 }
5637 } finally {
5638 observer.stopWatching();
5639 }
5640 }

记录app太慢

 5642    final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
5643 if (true || IS_USER_BUILD) {
5644 return;
5645 }
5646 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
5647 if (tracesPath == null || tracesPath.length() == 0) {
5648 return;
5649 }
5650
5651 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5652 StrictMode.allowThreadDiskWrites();
5653 try {
5654 final File tracesFile = new File(tracesPath);
5655 final File tracesDir = tracesFile.getParentFile();
5656 final File tracesTmp = new File(tracesDir, "__tmp__");
5657 try {
5658 if (tracesFile.exists()) {
5659 tracesTmp.delete();
5660 tracesFile.renameTo(tracesTmp);
5661 }
5662 StringBuilder sb = new StringBuilder();
5663 Time tobj = new Time();
5664 tobj.set(System.currentTimeMillis());
5665 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5666 sb.append(": ");
5667 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5668 sb.append(" since ");
5669 sb.append(msg);
5670 FileOutputStream fos = new FileOutputStream(tracesFile);
5671 fos.write(sb.toString().getBytes());
5672 if (app == null) {
5673 fos.write("\n*** No application process!".getBytes());
5674 }
5675 fos.close();
5676 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5677 } catch (IOException e) {
5678 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
5679 return;
5680 }
5681
5682 if (app != null) {
5683 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5684 firstPids.add(app.pid);
5685 dumpStackTraces(tracesPath, firstPids, null, null, null);
5686 }
5687
5688 File lastTracesFile = null;
5689 File curTracesFile = null;
5690 for (int i=9; i>=0; i--) {
5691 String name = String.format(Locale.US, "slow%02d.txt", i);
5692 curTracesFile = new File(tracesDir, name);
5693 if (curTracesFile.exists()) {
5694 if (lastTracesFile != null) {
5695 curTracesFile.renameTo(lastTracesFile);
5696 } else {
5697 curTracesFile.delete();
5698 }
5699 }
5700 lastTracesFile = curTracesFile;
5701 }
5702 tracesFile.renameTo(curTracesFile);
5703 if (tracesTmp.exists()) {
5704 tracesTmp.renameTo(tracesFile);
5705 }
5706 } finally {
5707 StrictMode.setThreadPolicy(oldPolicy);
5708 }
5709 }

显示启动警告

 5711    final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
5712 if (!mLaunchWarningShown) {
5713 mLaunchWarningShown = true;
5714 mUiHandler.post(new Runnable() {
5715 @Override
5716 public void run() {
5717 synchronized (ActivityManagerService.this) {
5718 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
5719 d.show();
5720 mUiHandler.postDelayed(new Runnable() {
5721 @Override
5722 public void run() {
5723 synchronized (ActivityManagerService.this) {
5724 d.dismiss();
5725 mLaunchWarningShown = false;
5726 }
5727 }
5728 }, 4000);
5729 }
5730 }
5731 });
5732 }
5733 }

清除app用户数据

 5735    @Override
5736 public boolean clearApplicationUserData(final String packageName,
5737 final IPackageDataObserver observer, int userId) {
5738 enforceNotIsolatedCaller("clearApplicationUserData");
5739 int uid = Binder.getCallingUid();
5740 int pid = Binder.getCallingPid();
5741 userId = mUserController.handleIncomingUser(pid, uid, userId, false,
5742 ALLOW_FULL_ONLY, "clearApplicationUserData", null);
5743
5744
5745 long callingId = Binder.clearCallingIdentity();
5746 try {
5747 IPackageManager pm = AppGlobals.getPackageManager();
5748 int pkgUid = -1;
5749 synchronized(this) {
5750 if (getPackageManagerInternalLocked().isPackageDataProtected(
5751 userId, packageName)) {
5752 throw new SecurityException(
5753 "Cannot clear data for a protected package: " + packageName);
5754 }
5755
5756 try {
5757 pkgUid = pm.getPackageUid(packageName, MATCH_UNINSTALLED_PACKAGES, userId);
5758 } catch (RemoteException e) {
5759 }
5760 if (pkgUid == -1) {
5761 Slog.w(TAG, "Invalid packageName: " + packageName);
5762 if (observer != null) {
5763 try {
5764 observer.onRemoveCompleted(packageName, false);
5765 } catch (RemoteException e) {
5766 Slog.i(TAG, "Observer no longer exists.");
5767 }
5768 }
5769 return false;
5770 }
5771 if (uid == pkgUid || checkComponentPermission(
5772 android.Manifest.permission.CLEAR_APP_USER_DATA,
5773 pid, uid, -1, true)
5774 == PackageManager.PERMISSION_GRANTED) {
5775 forceStopPackageLocked(packageName, pkgUid, "clear data");
5776 } else {
5777 throw new SecurityException("PID " + pid + " does not have permission "
5778 + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data"
5779 + " of package " + packageName);
5780 }
5781
5782 // Remove all tasks match the cleared application package and user
5783 for (int i = mRecentTasks.size() - 1; i >= 0; i--) {
5784 final TaskRecord tr = mRecentTasks.get(i);
5785 final String taskPackageName =
5786 tr.getBaseIntent().getComponent().getPackageName();
5787 if (tr.userId != userId) continue;
5788 if (!taskPackageName.equals(packageName)) continue;
5789 mStackSupervisor.removeTaskByIdLocked(tr.taskId, false, REMOVE_FROM_RECENTS);
5790 }
5791 }
5792
5793 final int pkgUidF = pkgUid;
5794 final int userIdF = userId;
5795 final IPackageDataObserver localObserver = new IPackageDataObserver.Stub() {
5796 @Override
5797 public void onRemoveCompleted(String packageName, boolean succeeded)
5798 throws RemoteException {
5799 synchronized (ActivityManagerService.this) {
5800 finishForceStopPackageLocked(packageName, pkgUidF);
5801 }
5802
5803 final Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
5804 Uri.fromParts("package", packageName, null));
5805 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
5806 intent.putExtra(Intent.EXTRA_UID, pkgUidF);
5807 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(pkgUidF));
5808 broadcastIntentInPackage("android", SYSTEM_UID, intent,
5809 null, null, 0, null, null, null, null, false, false, userIdF);
5810
5811 if (observer != null) {
5812 observer.onRemoveCompleted(packageName, succeeded);
5813 }
5814 }
5815 };
5816
5817 try {
5818 // Clear application user data
5819 pm.clearApplicationUserData(packageName, localObserver, userId);
5820
5821 synchronized(this) {
5822 // Remove all permissions granted from/to this package
5823 removeUriPermissionsForPackageLocked(packageName, userId, true);
5824 }
5825
5826 // Reset notification settings.
5827 INotificationManager inm = NotificationManager.getService();
5828 inm.clearData(packageName, pkgUidF, uid == pkgUidF);
5829 } catch (RemoteException e) {
5830 }
5831 } finally {
5832 Binder.restoreCallingIdentity(callingId);
5833 }
5834 return true;
5835 }
5836

后台杀掉app

 5837    @Override
5838 public void killBackgroundProcesses(final String packageName, int userId) {
5839 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
5840 != PackageManager.PERMISSION_GRANTED &&
5841 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
5842 != PackageManager.PERMISSION_GRANTED) {
5843 String msg = "Permission Denial: killBackgroundProcesses() from pid="
5844 + Binder.getCallingPid()
5845 + ", uid=" + Binder.getCallingUid()
5846 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
5847 Slog.w(TAG, msg);
5848 throw new SecurityException(msg);
5849 }
5850
5851 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
5852 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null);
5853 long callingId = Binder.clearCallingIdentity();
5854 try {
5855 IPackageManager pm = AppGlobals.getPackageManager();
5856 synchronized(this) {
5857 int appId = -1;
5858 try {
5859 appId = UserHandle.getAppId(
5860 pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId));
5861 } catch (RemoteException e) {
5862 }
5863 if (appId == -1) {
5864 Slog.w(TAG, "Invalid packageName: " + packageName);
5865 return;
5866 }
5867 killPackageProcessesLocked(packageName, appId, userId,
5868 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
5869 }
5870 } finally {
5871 Binder.restoreCallingIdentity(callingId);
5872 }
5873 }
5874
5875 @Override
5876 public void killAllBackgroundProcesses() {
5877 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
5878 != PackageManager.PERMISSION_GRANTED) {
5879 final String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
5880 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
5881 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
5882 Slog.w(TAG, msg);
5883 throw new SecurityException(msg);
5884 }
5885
5886 final long callingId = Binder.clearCallingIdentity();
5887 try {
5888 synchronized (this) {
5889 final ArrayList<ProcessRecord> procs = new ArrayList<>();
5890 final int NP = mProcessNames.getMap().size();
5891 for (int ip = 0; ip < NP; ip++) {
5892 final SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
5893 final int NA = apps.size();
5894 for (int ia = 0; ia < NA; ia++) {
5895 final ProcessRecord app = apps.valueAt(ia);
5896 if (app.persistent) {
5897 // We don't kill persistent processes.
5898 continue;
5899 }
5900 if (app.removed) {
5901 procs.add(app);
5902 } else if (app.setAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
5903 app.removed = true;
5904 procs.add(app);
5905 }
5906 }
5907 }
5908
5909 final int N = procs.size();
5910 for (int i = 0; i < N; i++) {
5911 removeProcessLocked(procs.get(i), false, true, "kill all background");
5912 }
5913
5914 mAllowLowerMemLevel = true;
5915
5916 updateOomAdjLocked();
5917 doLowMemReportIfNeededLocked(null);
5918 }
5919 } finally {
5920 Binder.restoreCallingIdentity(callingId);
5921 }
5922 }
5923
5924 /**
5925 * Kills all background processes, except those matching any of the
5926 * specified properties.
5927 *
5928 * @param minTargetSdk the target SDK version at or above which to preserve
5929 * processes, or {@code -1} to ignore the target SDK
5930 * @param maxProcState the process state at or below which to preserve
5931 * processes, or {@code -1} to ignore the process state
5932 */
5933 private void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) {
5934 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
5935 != PackageManager.PERMISSION_GRANTED) {
5936 final String msg = "Permission Denial: killAllBackgroundProcessesExcept() from pid="
5937 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
5938 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
5939 Slog.w(TAG, msg);
5940 throw new SecurityException(msg);
5941 }
5942
5943 final long callingId = Binder.clearCallingIdentity();
5944 try {
5945 synchronized (this) {
5946 final ArrayList<ProcessRecord> procs = new ArrayList<>();
5947 final int NP = mProcessNames.getMap().size();
5948 for (int ip = 0; ip < NP; ip++) {
5949 final SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
5950 final int NA = apps.size();
5951 for (int ia = 0; ia < NA; ia++) {
5952 final ProcessRecord app = apps.valueAt(ia);
5953 if (app.removed) {
5954 procs.add(app);
5955 } else if ((minTargetSdk < 0 || app.info.targetSdkVersion < minTargetSdk)
5956 && (maxProcState < 0 || app.setProcState > maxProcState)) {
5957 app.removed = true;
5958 procs.add(app);
5959 }
5960 }
5961 }
5962
5963 final int N = procs.size();
5964 for (int i = 0; i < N; i++) {
5965 removeProcessLocked(procs.get(i), false, true, "kill all background except");
5966 }
5967 }
5968 } finally {
5969 Binder.restoreCallingIdentity(callingId);
5970 }
5971 }

强制停止app

 5973    @Override
5974 public void forceStopPackage(final String packageName, int userId) {
5975 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
5976 != PackageManager.PERMISSION_GRANTED) {
5977 String msg = "Permission Denial: forceStopPackage() from pid="
5978 + Binder.getCallingPid()
5979 + ", uid=" + Binder.getCallingUid()
5980 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
5981 Slog.w(TAG, msg);
5982 throw new SecurityException(msg);
5983 }
5984 final int callingPid = Binder.getCallingPid();
5985 userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(),
5986 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null);
5987 long callingId = Binder.clearCallingIdentity();
5988 try {
5989 IPackageManager pm = AppGlobals.getPackageManager();
5990 synchronized(this) {
5991 int[] users = userId == UserHandle.USER_ALL
5992 ? mUserController.getUsers() : new int[] { userId };
5993 for (int user : users) {
5994 int pkgUid = -1;
5995 try {
5996 pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
5997 user);
5998 } catch (RemoteException e) {
5999 }
6000 if (pkgUid == -1) {
6001 Slog.w(TAG, "Invalid packageName: " + packageName);
6002 continue;
6003 }
6004 try {
6005 pm.setPackageStoppedState(packageName, true, user);
6006 } catch (RemoteException e) {
6007 } catch (IllegalArgumentException e) {
6008 Slog.w(TAG, "Failed trying to unstop package "
6009 + packageName + ": " + e);
6010 }
6011 if (mUserController.isUserRunningLocked(user, 0)) {
6012 forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid);
6013 finishForceStopPackageLocked(packageName, pkgUid);
6014 }
6015 }
6016 }
6017 } finally {
6018 Binder.restoreCallingIdentity(callingId);
6019 }
6020 }

添加package依赖

 6023    public void addPackageDependency(String packageName) {
6024 synchronized (this) {
6025 int callingPid = Binder.getCallingPid();
6026 if (callingPid == myPid()) {
6027 // Yeah, um, no.
6028 return;
6029 }
6030 ProcessRecord proc;
6031 synchronized (mPidsSelfLocked) {
6032 proc = mPidsSelfLocked.get(Binder.getCallingPid());
6033 }
6034 if (proc != null) {
6035 if (proc.pkgDeps == null) {
6036 proc.pkgDeps = new ArraySet<String>(1);
6037 }
6038 proc.pkgDeps.add(packageName);
6039 }
6040 }
6041 }

kill app

 6043    /*
6044 * The pkg name and app id have to be specified.
6045 */
6046 @Override
6047 public void killApplication(String pkg, int appId, int userId, String reason) {
6048 if (pkg == null) {
6049 return;
6050 }
6051 // Make sure the uid is valid.
6052 if (appId < 0) {
6053 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
6054 return;
6055 }
6056 int callerUid = Binder.getCallingUid();
6057 // Only the system server can kill an application
6058 if (UserHandle.getAppId(callerUid) == SYSTEM_UID) {
6059 // Post an aysnc message to kill the application
6060 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
6061 msg.arg1 = appId;
6062 msg.arg2 = userId;
6063 Bundle bundle = new Bundle();
6064 bundle.putString("pkg", pkg);
6065 bundle.putString("reason", reason);
6066 msg.obj = bundle;
6067 mHandler.sendMessage(msg);
6068 } else {
6069 throw new SecurityException(callerUid + " cannot kill pkg: " +
6070 pkg);
6071 }
6072 }

关闭系统对话框

 6074    @Override
6075 public void closeSystemDialogs(String reason) {
6076 enforceNotIsolatedCaller("closeSystemDialogs");
6077
6078 final int pid = Binder.getCallingPid();
6079 final int uid = Binder.getCallingUid();
6080 final long origId = Binder.clearCallingIdentity();
6081 try {
6082 synchronized (this) {
6083 // Only allow this from foreground processes, so that background
6084 // applications can't abuse it to prevent system UI from being shown.
6085 if (uid >= FIRST_APPLICATION_UID) {
6086 ProcessRecord proc;
6087 synchronized (mPidsSelfLocked) {
6088 proc = mPidsSelfLocked.get(pid);
6089 }
6090 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
6091 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6092 + " from background process " + proc);
6093 return;
6094 }
6095 }
6096 closeSystemDialogsLocked(reason);
6097 }
6098 } finally {
6099 Binder.restoreCallingIdentity(origId);
6100 }
6101 }
6102
6103 void closeSystemDialogsLocked(String reason) {
6104 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
6105 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
6106 | Intent.FLAG_RECEIVER_FOREGROUND);
6107 if (reason != null) {
6108 intent.putExtra("reason", reason);
6109 }
6110 mWindowManager.closeSystemDialogs(reason);
6111
6112 mStackSupervisor.closeSystemDialogsLocked();
6113
6114 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
6115 AppOpsManager.OP_NONE, null, false, false,
6116 -1, SYSTEM_UID, UserHandle.USER_ALL);
6117 }

获取进程内存信息,获取进程

 6119    @Override
6120 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
6121 enforceNotIsolatedCaller("getProcessMemoryInfo");
6122 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
6123 for (int i=pids.length-1; i>=0; i--) {
6124 ProcessRecord proc;
6125 int oomAdj;
6126 synchronized (this) {
6127 synchronized (mPidsSelfLocked) {
6128 proc = mPidsSelfLocked.get(pids[i]);
6129 oomAdj = proc != null ? proc.setAdj : 0;
6130 }
6131 }
6132 infos[i] = new Debug.MemoryInfo();
6133 Debug.getMemoryInfo(pids[i], infos[i]);
6134 if (proc != null) {
6135 synchronized (this) {
6136 if (proc.thread != null && proc.setAdj == oomAdj) {
6137 // Record this for posterity if the process has been stable.
6138 proc.baseProcessTracker.addPss(infos[i].getTotalPss(),
6139 infos[i].getTotalUss(), false, proc.pkgList);
6140 }
6141 }
6142 }
6143 }
6144 return infos;
6145 }
6146
6147 @Override
6148 public long[] getProcessPss(int[] pids) {
6149 enforceNotIsolatedCaller("getProcessPss");
6150 long[] pss = new long[pids.length];
6151 for (int i=pids.length-1; i>=0; i--) {
6152 ProcessRecord proc;
6153 int oomAdj;
6154 synchronized (this) {
6155 synchronized (mPidsSelfLocked) {
6156 proc = mPidsSelfLocked.get(pids[i]);
6157 oomAdj = proc != null ? proc.setAdj : 0;
6158 }
6159 }
6160 long[] tmpUss = new long[1];
6161 pss[i] = Debug.getPss(pids[i], tmpUss, null);
6162 if (proc != null) {
6163 synchronized (this) {
6164 if (proc.thread != null && proc.setAdj == oomAdj) {
6165 // Record this for posterity if the process has been stable.
6166 proc.baseProcessTracker.addPss(pss[i], tmpUss[0], false, proc.pkgList);
6167 }
6168 }
6169 }
6170 }
6171 return pss;
6172 }

kill程序进程

 6174    @Override
6175 public void killApplicationProcess(String processName, int uid) {
6176 if (processName == null) {
6177 return;
6178 }
6179
6180 int callerUid = Binder.getCallingUid();
6181 // Only the system server can kill an application
6182 if (callerUid == SYSTEM_UID) {
6183 synchronized (this) {
6184 ProcessRecord app = getProcessRecordLocked(processName, uid, true);
6185 if (app != null && app.thread != null) {
6186 try {
6187 app.thread.scheduleSuicide();
6188 } catch (RemoteException e) {
6189 // If the other end already died, then our work here is done.
6190 }
6191 } else {
6192 Slog.w(TAG, "Process/uid not found attempting kill of "
6193 + processName + " / " + uid);
6194 }
6195 }
6196 } else {
6197 throw new SecurityException(callerUid + " cannot kill app process: " +
6198 processName);
6199 }
6200 }

forece stop package

 6202    private void forceStopPackageLocked(final String packageName, int uid, String reason) {
6203 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
6204 false, true, false, false, UserHandle.getUserId(uid), reason);
6205 }

完成force stop

 6207    private void finishForceStopPackageLocked(final String packageName, int uid) {
6208 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
6209 Uri.fromParts("package", packageName, null));
6210 if (!mProcessesReady) {
6211 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
6212 | Intent.FLAG_RECEIVER_FOREGROUND);
6213 }
6214 intent.putExtra(Intent.EXTRA_UID, uid);
6215 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
6216 broadcastIntentLocked(null, null, intent,
6217 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
6218 null, false, false, MY_PID, SYSTEM_UID, UserHandle.getUserId(uid));
6219 }

杀掉package进程

 6222    private final boolean killPackageProcessesLocked(String packageName, int appId,
6223 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
6224 boolean doit, boolean evenPersistent, String reason) {
6225 ArrayList<ProcessRecord> procs = new ArrayList<>();
6226
6227 // Remove all processes this package may have touched: all with the
6228 // same UID (except for the system or root user), and all whose name
6229 // matches the package name.
6230 final int NP = mProcessNames.getMap().size();
6231 for (int ip=0; ip<NP; ip++) {
6232 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
6233 final int NA = apps.size();
6234 for (int ia=0; ia<NA; ia++) {
6235 ProcessRecord app = apps.valueAt(ia);
6236 if (app.persistent && !evenPersistent) {
6237 // we don't kill persistent processes
6238 continue;
6239 }
6240 if (app.removed) {
6241 if (doit) {
6242 procs.add(app);
6243 }
6244 continue;
6245 }
6246
6247 // Skip process if it doesn't meet our oom adj requirement.
6248 if (app.setAdj < minOomAdj) {
6249 continue;
6250 }
6251
6252 // If no package is specified, we call all processes under the
6253 // give user id.
6254 if (packageName == null) {
6255 if (userId != UserHandle.USER_ALL && app.userId != userId) {
6256 continue;
6257 }
6258 if (appId >= 0 && UserHandle.getAppId(app.uid) != appId) {
6259 continue;
6260 }
6261 // Package has been specified, we want to hit all processes
6262 // that match it. We need to qualify this by the processes
6263 // that are running under the specified app and user ID.
6264 } else {
6265 final boolean isDep = app.pkgDeps != null
6266 && app.pkgDeps.contains(packageName);
6267 if (!isDep && UserHandle.getAppId(app.uid) != appId) {
6268 continue;
6269 }
6270 if (userId != UserHandle.USER_ALL && app.userId != userId) {
6271 continue;
6272 }
6273 if (!app.pkgList.containsKey(packageName) && !isDep) {
6274 continue;
6275 }
6276 }
6277
6278 // Process has passed all conditions, kill it!
6279 if (!doit) {
6280 return true;
6281 }
6282 app.removed = true;
6283 procs.add(app);
6284 }
6285 }
6286
6287 int N = procs.size();
6288 for (int i=0; i<N; i++) {
6289 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
6290 }
6291 updateOomAdjLocked();
6292 return N > 0;
6293 }

清除disabled的包组件

 6295    private void cleanupDisabledPackageComponentsLocked(
6296 String packageName, int userId, boolean killProcess, String[] changedClasses) {
6297
6298 Set<String> disabledClasses = null;
6299 boolean packageDisabled = false;
6300 IPackageManager pm = AppGlobals.getPackageManager();
6301
6302 if (changedClasses == null) {
6303 // Nothing changed...
6304 return;
6305 }
6306
6307 // Determine enable/disable state of the package and its components.
6308 int enabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
6309 for (int i = changedClasses.length - 1; i >= 0; i--) {
6310 final String changedClass = changedClasses[i];
6311
6312 if (changedClass.equals(packageName)) {
6313 try {
6314 // Entire package setting changed
6315 enabled = pm.getApplicationEnabledSetting(packageName,
6316 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM);
6317 } catch (Exception e) {
6318 // No such package/component; probably racing with uninstall. In any
6319 // event it means we have nothing further to do here.
6320 return;
6321 }
6322 packageDisabled = enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED
6323 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
6324 if (packageDisabled) {
6325 // Entire package is disabled.
6326 // No need to continue to check component states.
6327 disabledClasses = null;
6328 break;
6329 }
6330 } else {
6331 try {
6332 enabled = pm.getComponentEnabledSetting(
6333 new ComponentName(packageName, changedClass),
6334 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM);
6335 } catch (Exception e) {
6336 // As above, probably racing with uninstall.
6337 return;
6338 }
6339 if (enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED
6340 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
6341 if (disabledClasses == null) {
6342 disabledClasses = new ArraySet<>(changedClasses.length);
6343 }
6344 disabledClasses.add(changedClass);
6345 }
6346 }
6347 }
6348
6349 if (!packageDisabled && disabledClasses == null) {
6350 // Nothing to do here...
6351 return;
6352 }
6353
6354 // Clean-up disabled activities.
6355 if (mStackSupervisor.finishDisabledPackageActivitiesLocked(
6356 packageName, disabledClasses, true, false, userId) && mBooted) {
6357 mStackSupervisor.resumeFocusedStackTopActivityLocked();
6358 mStackSupervisor.scheduleIdleLocked();
6359 }
6360
6361 // Clean-up disabled tasks
6362 cleanupDisabledPackageTasksLocked(packageName, disabledClasses, userId);
6363
6364 // Clean-up disabled services.
6365 mServices.bringDownDisabledPackageServicesLocked(
6366 packageName, disabledClasses, userId, false, killProcess, true);
6367
6368 // Clean-up disabled providers.
6369 ArrayList<ContentProviderRecord> providers = new ArrayList<>();
6370 mProviderMap.collectPackageProvidersLocked(
6371 packageName, disabledClasses, true, false, userId, providers);
6372 for (int i = providers.size() - 1; i >= 0; i--) {
6373 removeDyingProviderLocked(null, providers.get(i), true);
6374 }
6375
6376 // Clean-up disabled broadcast receivers.
6377 for (int i = mBroadcastQueues.length - 1; i >= 0; i--) {
6378 mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
6379 packageName, disabledClasses, userId, true);
6380 }
6381
6382 }

为用户清除广播队列

 6384    final boolean clearBroadcastQueueForUserLocked(int userId) {
6385 boolean didSomething = false;
6386 for (int i = mBroadcastQueues.length - 1; i >= 0; i--) {
6387 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
6388 null, null, userId, true);
6389 }
6390 return didSomething;
6391 }

forcestop package

 6393    final boolean forceStopPackageLocked(String packageName, int appId,
6394 boolean callerWillRestart, boolean purgeCache, boolean doit,
6395 boolean evenPersistent, boolean uninstalling, int userId, String reason) {
6396 int i;
6397
6398 if (userId == UserHandle.USER_ALL && packageName == null) {
6399 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
6400 }
6401
6402 if (appId < 0 && packageName != null) {
6403 try {
6404 appId = UserHandle.getAppId(AppGlobals.getPackageManager()
6405 .getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 0));
6406 } catch (RemoteException e) {
6407 }
6408 }
6409
6410 if (doit) {
6411 if (packageName != null) {
6412 Slog.i(TAG, "Force stopping " + packageName + " appid=" + appId
6413 + " user=" + userId + ": " + reason);
6414 } else {
6415 Slog.i(TAG, "Force stopping u" + userId + ": " + reason);
6416 }
6417
6418 mAppErrors.resetProcessCrashTimeLocked(packageName == null, appId, userId);
6419 }
6420
6421 boolean didSomething = killPackageProcessesLocked(packageName, appId, userId,
6422 ProcessList.INVALID_ADJ, callerWillRestart, true, doit, evenPersistent,
6423 packageName == null ? ("stop user " + userId) : ("stop " + packageName));
6424
6425 didSomething |= mActivityStarter.clearPendingActivityLaunchesLocked(packageName);
6426
6427 if (mStackSupervisor.finishDisabledPackageActivitiesLocked(
6428 packageName, null, doit, evenPersistent, userId)) {
6429 if (!doit) {
6430 return true;
6431 }
6432 didSomething = true;
6433 }
6434
6435 if (mServices.bringDownDisabledPackageServicesLocked(
6436 packageName, null, userId, evenPersistent, true, doit)) {
6437 if (!doit) {
6438 return true;
6439 }
6440 didSomething = true;
6441 }
6442
6443 if (packageName == null) {
6444 // Remove all sticky broadcasts from this user.
6445 mStickyBroadcasts.remove(userId);
6446 }
6447
6448 ArrayList<ContentProviderRecord> providers = new ArrayList<>();
6449 if (mProviderMap.collectPackageProvidersLocked(packageName, null, doit, evenPersistent,
6450 userId, providers)) {
6451 if (!doit) {
6452 return true;
6453 }
6454 didSomething = true;
6455 }
6456 for (i = providers.size() - 1; i >= 0; i--) {
6457 removeDyingProviderLocked(null, providers.get(i), true);
6458 }
6459
6460 // Remove transient permissions granted from/to this package/user
6461 removeUriPermissionsForPackageLocked(packageName, userId, false);
6462
6463 if (doit) {
6464 for (i = mBroadcastQueues.length - 1; i >= 0; i--) {
6465 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
6466 packageName, null, userId, doit);
6467 }
6468 }
6469
6470 if (packageName == null || uninstalling) {
6471 // Remove pending intents. For now we only do this when force
6472 // stopping users, because we have some problems when doing this
6473 // for packages -- app widgets are not currently cleaned up for
6474 // such packages, so they can be left with bad pending intents.
6475 if (mIntentSenderRecords.size() > 0) {
6476 Iterator<WeakReference<PendingIntentRecord>> it
6477 = mIntentSenderRecords.values().iterator();
6478 while (it.hasNext()) {
6479 WeakReference<PendingIntentRecord> wpir = it.next();
6480 if (wpir == null) {
6481 it.remove();
6482 continue;
6483 }
6484 PendingIntentRecord pir = wpir.get();
6485 if (pir == null) {
6486 it.remove();
6487 continue;
6488 }
6489 if (packageName == null) {
6490 // Stopping user, remove all objects for the user.
6491 if (pir.key.userId != userId) {
6492 // Not the same user, skip it.
6493 continue;
6494 }
6495 } else {
6496 if (UserHandle.getAppId(pir.uid) != appId) {
6497 // Different app id, skip it.
6498 continue;
6499 }
6500 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
6501 // Different user, skip it.
6502 continue;
6503 }
6504 if (!pir.key.packageName.equals(packageName)) {
6505 // Different package, skip it.
6506 continue;
6507 }
6508 }
6509 if (!doit) {
6510 return true;
6511 }
6512 didSomething = true;
6513 it.remove();
6514 makeIntentSenderCanceledLocked(pir);
6515 if (pir.key.activity != null && pir.key.activity.pendingResults != null) {
6516 pir.key.activity.pendingResults.remove(pir.ref);
6517 }
6518 }
6519 }
6520 }
6521
6522 if (doit) {
6523 if (purgeCache && packageName != null) {
6524 AttributeCache ac = AttributeCache.instance();
6525 if (ac != null) {
6526 ac.removePackage(packageName);
6527 }
6528 }
6529 if (mBooted) {
6530 mStackSupervisor.resumeFocusedStackTopActivityLocked();
6531 mStackSupervisor.scheduleIdleLocked();
6532 }
6533 }
6534
6535 return didSomething;
6536 }

移除进程name

 6538    private final ProcessRecord removeProcessNameLocked(final String name, final int uid) {
6539 return removeProcessNameLocked(name, uid, null);
6540 }
6541
6542 private final ProcessRecord removeProcessNameLocked(final String name, final int uid,
6543 final ProcessRecord expecting) {
6544 ProcessRecord old = mProcessNames.get(name, uid);
6545 // Only actually remove when the currently recorded value matches the
6546 // record that we expected; if it doesn't match then we raced with a
6547 // newly created process and we don't want to destroy the new one.
6548 if ((expecting == null) || (old == expecting)) {
6549 mProcessNames.remove(name, uid);
6550 }
6551 if (old != null && old.uidRecord != null) {
6552 old.uidRecord.numProcs--;
6553 if (old.uidRecord.numProcs == 0) {
6554 // No more processes using this uid, tell clients it is gone.
6555 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
6556 "No more processes in " + old.uidRecord);
6557 enqueueUidChangeLocked(old.uidRecord, -1, UidRecord.CHANGE_GONE);
6558 EventLogTags.writeAmUidStopped(uid);
6559 mActiveUids.remove(uid);
6560 noteUidProcessState(uid, ActivityManager.PROCESS_STATE_NONEXISTENT);
6561 }
6562 old.uidRecord = null;
6563 }
6564 mIsolatedProcesses.remove(uid);
6565 return old;
6566 }

添加进程name

 6568    private final void addProcessNameLocked(ProcessRecord proc) {
6569 // We shouldn't already have a process under this name, but just in case we
6570 // need to clean up whatever may be there now.
6571 ProcessRecord old = removeProcessNameLocked(proc.processName, proc.uid);
6572 if (old == proc && proc.persistent) {
6573 // We are re-adding a persistent process. Whatevs! Just leave it there.
6574 Slog.w(TAG, "Re-adding persistent process " + proc);
6575 } else if (old != null) {
6576 Slog.wtf(TAG, "Already have existing proc " + old + " when adding " + proc);
6577 }
6578 UidRecord uidRec = mActiveUids.get(proc.uid);
6579 if (uidRec == null) {
6580 uidRec = new UidRecord(proc.uid);
6581 // This is the first appearance of the uid, report it now!
6582 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
6583 "Creating new process uid: " + uidRec);
6584 if (Arrays.binarySearch(mDeviceIdleTempWhitelist, UserHandle.getAppId(proc.uid)) >= 0
6585 || mPendingTempWhitelist.indexOfKey(proc.uid) >= 0) {
6586 uidRec.setWhitelist = uidRec.curWhitelist = true;
6587 }
6588 uidRec.updateHasInternetPermission();
6589 mActiveUids.put(proc.uid, uidRec);
6590 EventLogTags.writeAmUidRunning(uidRec.uid);
6591 noteUidProcessState(uidRec.uid, uidRec.curProcState);
6592 enqueueUidChangeLocked(uidRec, -1, UidRecord.CHANGE_ACTIVE);
6593 }
6594 proc.uidRecord = uidRec;
6595
6596 // Reset render thread tid if it was already set, so new process can set it again.
6597 proc.renderThreadTid = 0;
6598 uidRec.numProcs++;
6599 mProcessNames.put(proc.processName, proc.uid, proc);
6600 if (proc.isolated) {
6601 mIsolatedProcesses.put(proc.uid, proc);
6602 }
6603 }
6604

移除进程

 6604
6605 boolean removeProcessLocked(ProcessRecord app,
6606 boolean callerWillRestart, boolean allowRestart, String reason) {
6607 final String name = app.processName;
6608 final int uid = app.uid;
6609 if (DEBUG_PROCESSES) Slog.d(TAG_PROCESSES,
6610 "Force removing proc " + app.toShortString() + " (" + name + "/" + uid + ")");
6611
6612 ProcessRecord old = mProcessNames.get(name, uid);
6613 if (old != app) {
6614 // This process is no longer active, so nothing to do.
6615 Slog.w(TAG, "Ignoring remove of inactive process: " + app);
6616 return false;
6617 }
6618 removeProcessNameLocked(name, uid);
6619 if (mHeavyWeightProcess == app) {
6620 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
6621 mHeavyWeightProcess.userId, 0));
6622 mHeavyWeightProcess = null;
6623 }
6624 boolean needRestart = false;
6625 if (app.pid > 0 && app.pid != MY_PID) {
6626 int pid = app.pid;
6627 synchronized (mPidsSelfLocked) {
6628 mPidsSelfLocked.remove(pid);
6629 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
6630 }
6631 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
6632 if (app.isolated) {
6633 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
6634 getPackageManagerInternalLocked().removeIsolatedUid(app.uid);
6635 }
6636 boolean willRestart = false;
6637 if (app.persistent && !app.isolated) {
6638 if (!callerWillRestart) {
6639 willRestart = true;
6640 } else {
6641 needRestart = true;
6642 }
6643 }
6644 app.kill(reason, true);
6645 handleAppDiedLocked(app, willRestart, allowRestart);
6646 if (willRestart) {
6647 removeLruProcessLocked(app);
6648 addAppLocked(app.info, null, false, null /* ABI override */);
6649 }
6650 } else {
6651 mRemovedProcesses.add(app);
6652 }
6653
6654 return needRestart;
6655 }

进程的content provider发布超时

 6657    private final void processContentProviderPublishTimedOutLocked(ProcessRecord app) {
6658 cleanupAppInLaunchingProvidersLocked(app, true);
6659 removeProcessLocked(app, false, true, "timeout publishing content providers");
6660 }

进程启动超时

 6657    private final void processContentProviderPublishTimedOutLocked(ProcessRecord app) {
6658 cleanupAppInLaunchingProvidersLocked(app, true);
6659 removeProcessLocked(app, false, true, "timeout publishing content providers");
6660 }
6661
6662 private final void processStartTimedOutLocked(ProcessRecord app) {
6663 final int pid = app.pid;
6664 boolean gone = false;
6665 synchronized (mPidsSelfLocked) {
6666 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
6667 if (knownApp != null && knownApp.thread == null) {
6668 mPidsSelfLocked.remove(pid);
6669 gone = true;
6670 }
6671 }
6672
6673 if (gone) {
6674 Slog.w(TAG, "Process " + app + " failed to attach");
6675 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
6676 pid, app.uid, app.processName);
6677 removeProcessNameLocked(app.processName, app.uid);
6678 if (mHeavyWeightProcess == app) {
6679 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
6680 mHeavyWeightProcess.userId, 0));
6681 mHeavyWeightProcess = null;
6682 }
6683 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
6684 if (app.isolated) {
6685 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
6686 }
6687 // Take care of any launching providers waiting for this process.
6688 cleanupAppInLaunchingProvidersLocked(app, true);
6689 // Take care of any services that are waiting for the process.
6690 mServices.processStartTimedOutLocked(app);
6691 app.kill("start timeout", true);
6692 removeLruProcessLocked(app);
6693 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
6694 Slog.w(TAG, "Unattached app died before backup, skipping");
6695 mHandler.post(new Runnable() {
6696 @Override
6697 public void run(){
6698 try {
6699 IBackupManager bm = IBackupManager.Stub.asInterface(
6700 ServiceManager.getService(Context.BACKUP_SERVICE));
6701 bm.agentDisconnected(app.info.packageName);
6702 } catch (RemoteException e) {
6703 // Can't happen; the backup manager is local
6704 }
6705 }
6706 });
6707 }
6708 if (isPendingBroadcastProcessLocked(pid)) {
6709 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
6710 skipPendingBroadcastLocked(pid);
6711 }
6712 } else {
6713 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
6714 }
6715 }

attach application

 6717    private final boolean attachApplicationLocked(IApplicationThread thread,
6718 int pid) {
6719
6720 // Find the application record that is being attached... either via
6721 // the pid if we are running in multiple processes, or just pull the
6722 // next app record if we are emulating process with anonymous threads.
6723 ProcessRecord app;
6724 long startTime = SystemClock.uptimeMillis();
6725 if (pid != MY_PID && pid >= 0) {
6726 synchronized (mPidsSelfLocked) {
6727 app = mPidsSelfLocked.get(pid);
6728 }
6729 } else {
6730 app = null;
6731 }
6732
6733 if (app == null) {
6734 Slog.w(TAG, "No pending application record for pid " + pid
6735 + " (IApplicationThread " + thread + "); dropping process");
6736 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
6737 if (pid > 0 && pid != MY_PID) {
6738 killProcessQuiet(pid);
6739 //TODO: killProcessGroup(app.info.uid, pid);
6740 } else {
6741 try {
6742 thread.scheduleExit();
6743 } catch (Exception e) {
6744 // Ignore exceptions.
6745 }
6746 }
6747 return false;
6748 }
6749
6750 // If this application record is still attached to a previous
6751 // process, clean it up now.
6752 if (app.thread != null) {
6753 handleAppDiedLocked(app, true, true);
6754 }
6755
6756 // Tell the process all about itself.
6757
6758 if (DEBUG_ALL) Slog.v(
6759 TAG, "Binding process pid " + pid + " to record " + app);
6760
6761 final String processName = app.processName;
6762 try {
6763 AppDeathRecipient adr = new AppDeathRecipient(
6764 app, pid, thread);
6765 thread.asBinder().linkToDeath(adr, 0);
6766 app.deathRecipient = adr;
6767 } catch (RemoteException e) {
6768 app.resetPackageList(mProcessStats);
6769 startProcessLocked(app, "link fail", processName);
6770 return false;
6771 }
6772
6773 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
6774
6775 app.makeActive(thread, mProcessStats);
6776 app.curAdj = app.setAdj = app.verifiedAdj = ProcessList.INVALID_ADJ;
6777 app.curSchedGroup = app.setSchedGroup = ProcessList.SCHED_GROUP_DEFAULT;
6778 app.forcingToImportant = null;
6779 updateProcessForegroundLocked(app, false, false);
6780 app.hasShownUi = false;
6781 app.debugging = false;
6782 app.cached = false;
6783 app.killedByAm = false;
6784 app.killed = false;
6785
6786
6787 // We carefully use the same state that PackageManager uses for
6788 // filtering, since we use this flag to decide if we need to install
6789 // providers when user is unlocked later
6790 app.unlocked = StorageManager.isUserKeyUnlocked(app.userId);
6791
6792 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
6793
6794 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
6795 List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null;
6796
6797 if (providers != null && checkAppInLaunchingProvidersLocked(app)) {
6798 Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG);
6799 msg.obj = app;
6800 mHandler.sendMessageDelayed(msg, CONTENT_PROVIDER_PUBLISH_TIMEOUT);
6801 }
6802
6803 checkTime(startTime, "attachApplicationLocked: before bindApplication");
6804
6805 if (!normalMode) {
6806 Slog.i(TAG, "Launching preboot mode app: " + app);
6807 }
6808
6809 if (DEBUG_ALL) Slog.v(
6810 TAG, "New app record " + app
6811 + " thread=" + thread.asBinder() + " pid=" + pid);
6812 try {
6813 int testMode = ApplicationThreadConstants.DEBUG_OFF;
6814 if (mDebugApp != null && mDebugApp.equals(processName)) {
6815 testMode = mWaitForDebugger
6816 ? ApplicationThreadConstants.DEBUG_WAIT
6817 : ApplicationThreadConstants.DEBUG_ON;
6818 app.debugging = true;
6819 if (mDebugTransient) {
6820 mDebugApp = mOrigDebugApp;
6821 mWaitForDebugger = mOrigWaitForDebugger;
6822 }
6823 }
6824 String profileFile = app.instr != null ? app.instr.mProfileFile : null;
6825 ParcelFileDescriptor profileFd = null;
6826 int samplingInterval = 0;
6827 boolean profileAutoStop = false;
6828 boolean profileStreamingOutput = false;
6829 if (mProfileApp != null && mProfileApp.equals(processName)) {
6830 mProfileProc = app;
6831 profileFile = mProfileFile;
6832 profileFd = mProfileFd;
6833 samplingInterval = mSamplingInterval;
6834 profileAutoStop = mAutoStopProfiler;
6835 profileStreamingOutput = mStreamingOutput;
6836 }
6837 boolean enableTrackAllocation = false;
6838 if (mTrackAllocationApp != null && mTrackAllocationApp.equals(processName)) {
6839 enableTrackAllocation = true;
6840 mTrackAllocationApp = null;
6841 }
6842
6843 // If the app is being launched for restore or full backup, set it up specially
6844 boolean isRestrictedBackupMode = false;
6845 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
6846 isRestrictedBackupMode = mBackupTarget.appInfo.uid >= FIRST_APPLICATION_UID
6847 && ((mBackupTarget.backupMode == BackupRecord.RESTORE)
6848 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
6849 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL));
6850 }
6851
6852 if (app.instr != null) {
6853 notifyPackageUse(app.instr.mClass.getPackageName(),
6854 PackageManager.NOTIFY_PACKAGE_USE_INSTRUMENTATION);
6855 }
6856 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Binding proc "
6857 + processName + " with config " + getGlobalConfiguration());
6858 ApplicationInfo appInfo = app.instr != null ? app.instr.mTargetInfo : app.info;
6859 app.compat = compatibilityInfoForPackageLocked(appInfo);
6860 if (profileFd != null) {
6861 profileFd = profileFd.dup();
6862 }
6863 ProfilerInfo profilerInfo = profileFile == null ? null
6864 : new ProfilerInfo(profileFile, profileFd, samplingInterval, profileAutoStop,
6865 profileStreamingOutput);
6866
6867 // We deprecated Build.SERIAL and it is not accessible to
6868 // apps that target the v2 security sandbox. Since access to
6869 // the serial is now behind a permission we push down the value.
6870 String buildSerial = Build.UNKNOWN;
6871 if (appInfo.targetSandboxVersion != 2) {
6872 buildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
6873 ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
6874 .getSerial();
6875 }
6876
6877 // Check if this is a secondary process that should be incorporated into some
6878 // currently active instrumentation. (Note we do this AFTER all of the profiling
6879 // stuff above because profiling can currently happen only in the primary
6880 // instrumentation process.)
6881 if (mActiveInstrumentation.size() > 0 && app.instr == null) {
6882 for (int i = mActiveInstrumentation.size() - 1; i >= 0 && app.instr == null; i--) {
6883 ActiveInstrumentation aInstr = mActiveInstrumentation.get(i);
6884 if (!aInstr.mFinished && aInstr.mTargetInfo.uid == app.uid) {
6885 if (aInstr.mTargetProcesses.length == 0) {
6886 // This is the wildcard mode, where every process brought up for
6887 // the target instrumentation should be included.
6888 if (aInstr.mTargetInfo.packageName.equals(app.info.packageName)) {
6889 app.instr = aInstr;
6890 aInstr.mRunningProcesses.add(app);
6891 }
6892 } else {
6893 for (String proc : aInstr.mTargetProcesses) {
6894 if (proc.equals(app.processName)) {
6895 app.instr = aInstr;
6896 aInstr.mRunningProcesses.add(app);
6897 break;
6898 }
6899 }
6900 }
6901 }
6902 }
6903 }
6904
6905 checkTime(startTime, "attachApplicationLocked: immediately before bindApplication");
6906 mStackSupervisor.mActivityMetricsLogger.notifyBindApplication(app);
6907 if (app.instr != null) {
6908 thread.bindApplication(processName, appInfo, providers,
6909 app.instr.mClass,
6910 profilerInfo, app.instr.mArguments,
6911 app.instr.mWatcher,
6912 app.instr.mUiAutomationConnection, testMode,
6913 mBinderTransactionTrackingEnabled, enableTrackAllocation,
6914 isRestrictedBackupMode || !normalMode, app.persistent,
6915 new Configuration(getGlobalConfiguration()), app.compat,
6916 getCommonServicesLocked(app.isolated),
6917 mCoreSettingsObserver.getCoreSettingsLocked(),
6918 buildSerial);
6919 } else {
6920 thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
6921 null, null, null, testMode,
6922 mBinderTransactionTrackingEnabled, enableTrackAllocation,
6923 isRestrictedBackupMode || !normalMode, app.persistent,
6924 new Configuration(getGlobalConfiguration()), app.compat,
6925 getCommonServicesLocked(app.isolated),
6926 mCoreSettingsObserver.getCoreSettingsLocked(),
6927 buildSerial);
6928 }
6929
6930 checkTime(startTime, "attachApplicationLocked: immediately after bindApplication");
6931 updateLruProcessLocked(app, false, null);
6932 checkTime(startTime, "attachApplicationLocked: after updateLruProcessLocked");
6933 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
6934 } catch (Exception e) {
6935 // todo: Yikes! What should we do? For now we will try to
6936 // start another process, but that could easily get us in
6937 // an infinite loop of restarting processes...
6938 Slog.wtf(TAG, "Exception thrown during bind of " + app, e);
6939
6940 app.resetPackageList(mProcessStats);
6941 app.unlinkDeathRecipient();
6942 startProcessLocked(app, "bind fail", processName);
6943 return false;
6944 }
6945
6946 // Remove this record from the list of starting applications.
6947 mPersistentStartingProcesses.remove(app);
6948 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES,
6949 "Attach application locked removing on hold: " + app);
6950 mProcessesOnHold.remove(app);
6951
6952 boolean badApp = false;
6953 boolean didSomething = false;
6954
6955 // See if the top visible activity is waiting to run in this process...
6956 if (normalMode) {
6957 try {
6958 if (mStackSupervisor.attachApplicationLocked(app)) {
6959 didSomething = true;
6960 }
6961 } catch (Exception e) {
6962 Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
6963 badApp = true;
6964 }
6965 }
6966
6967 // Find any services that should be running in this process...
6968 if (!badApp) {
6969 try {
6970 didSomething |= mServices.attachApplicationLocked(app, processName);
6971 checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked");
6972 } catch (Exception e) {
6973 Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
6974 badApp = true;
6975 }
6976 }
6977
6978 // Check if a next-broadcast receiver is in this process...
6979 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
6980 try {
6981 didSomething |= sendPendingBroadcastsLocked(app);
6982 checkTime(startTime, "attachApplicationLocked: after sendPendingBroadcastsLocked");
6983 } catch (Exception e) {
6984 // If the app died trying to launch the receiver we declare it 'bad'
6985 Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e);
6986 badApp = true;
6987 }
6988 }
6989
6990 // Check whether the next backup agent is in this process...
6991 if (!badApp && mBackupTarget != null && mBackupTarget.app == app) {
6992 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP,
6993 "New app is backup target, launching agent for " + app);
6994 notifyPackageUse(mBackupTarget.appInfo.packageName,
6995 PackageManager.NOTIFY_PACKAGE_USE_BACKUP);
6996 try {
6997 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
6998 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
6999 mBackupTarget.backupMode);
7000 } catch (Exception e) {
7001 Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e);
7002 badApp = true;
7003 }
7004 }
7005
7006 if (badApp) {
7007 app.kill("error during init", true);
7008 handleAppDiedLocked(app, false, true);
7009 return false;
7010 }
7011
7012 if (!didSomething) {
7013 updateOomAdjLocked();
7014 checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked");
7015 }
7016
7017 return true;
7018 }
7019
7020 @Override
7021 public final void attachApplication(IApplicationThread thread) {
7022 synchronized (this) {
7023 int callingPid = Binder.getCallingPid();
7024 final long origId = Binder.clearCallingIdentity();
7025 attachApplicationLocked(thread, callingPid);
7026 Binder.restoreCallingIdentity(origId);
7027 }
7028 }
7029

Activity idle

 7030    @Override
7031 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
7032 final long origId = Binder.clearCallingIdentity();
7033 synchronized (this) {
7034 ActivityStack stack = ActivityRecord.getStackLocked(token);
7035 if (stack != null) {
7036 ActivityRecord r =
7037 mStackSupervisor.activityIdleInternalLocked(token, false /* fromTimeout */,
7038 false /* processPausingActivities */, config);
7039 if (stopProfiling) {
7040 if ((mProfileProc == r.app) && (mProfileFd != null)) {
7041 try {
7042 mProfileFd.close();
7043 } catch (IOException e) {
7044 }
7045 clearProfilerLocked();
7046 }
7047 }
7048 }
7049 }
7050 Binder.restoreCallingIdentity(origId);
7051 }

发送结束boot消息

 7053    void postFinishBooting(boolean finishBooting, boolean enableScreen) {
7054 mHandler.sendMessage(mHandler.obtainMessage(FINISH_BOOTING_MSG,
7055 finishBooting ? 1 : 0, enableScreen ? 1 : 0));
7056 }

启动后使能screen

 7058    void enableScreenAfterBoot() {
7059 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
7060 SystemClock.uptimeMillis());
7061 mWindowManager.enableScreenAfterBoot();
7062
7063 synchronized (this) {
7064 updateEventDispatchingLocked();
7065 }
7066 }

显示启动信息

 7068    @Override
7069 public void showBootMessage(final CharSequence msg, final boolean always) {
7070 if (Binder.getCallingUid() != myUid()) {
7071 throw new SecurityException();
7072 }
7073 mWindowManager.showBootMessage(msg, always);
7074 }
7075

锁屏消失

 7076    @Override
7077 public void keyguardGoingAway(int flags) {
7078 enforceNotIsolatedCaller("keyguardGoingAway");
7079 final long token = Binder.clearCallingIdentity();
7080 try {
7081 synchronized (this) {
7082 mKeyguardController.keyguardGoingAway(flags);
7083 }
7084 } finally {
7085 Binder.restoreCallingIdentity(token);
7086 }
7087 }

是否有锁屏

 7089    /**
7090 * @return whther the keyguard is currently locked.
7091 */
7092 boolean isKeyguardLocked() {
7093 return mKeyguardController.isKeyguardLocked();
7094 }

结束boot

 7096    final void finishBooting() {
7097 synchronized (this) {
7098 if (!mBootAnimationComplete) {
7099 mCallFinishBooting = true;
7100 return;
7101 }
7102 mCallFinishBooting = false;
7103 }
7104
7105 ArraySet<String> completedIsas = new ArraySet<String>();
7106 for (String abi : Build.SUPPORTED_ABIS) {
7107 zygoteProcess.establishZygoteConnectionForAbi(abi);
7108 final String instructionSet = VMRuntime.getInstructionSet(abi);
7109 if (!completedIsas.contains(instructionSet)) {
7110 try {
7111 mInstaller.markBootComplete(VMRuntime.getInstructionSet(abi));
7112 } catch (InstallerException e) {
7113 Slog.w(TAG, "Unable to mark boot complete for abi: " + abi + " (" +
7114 e.getMessage() +")");
7115 }
7116 completedIsas.add(instructionSet);
7117 }
7118 }
7119
7120 IntentFilter pkgFilter = new IntentFilter();
7121 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
7122 pkgFilter.addDataScheme("package");
7123 mContext.registerReceiver(new BroadcastReceiver() {
7124 @Override
7125 public void onReceive(Context context, Intent intent) {
7126 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
7127 if (pkgs != null) {
7128 for (String pkg : pkgs) {
7129 synchronized (ActivityManagerService.this) {
7130 if (forceStopPackageLocked(pkg, -1, false, false, false, false, false,
7131 0, "query restart")) {
7132 setResultCode(Activity.RESULT_OK);
7133 return;
7134 }
7135 }
7136 }
7137 }
7138 }
7139 }, pkgFilter);
7140
7141 IntentFilter dumpheapFilter = new IntentFilter();
7142 dumpheapFilter.addAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP);
7143 mContext.registerReceiver(new BroadcastReceiver() {
7144 @Override
7145 public void onReceive(Context context, Intent intent) {
7146 if (intent.getBooleanExtra(DumpHeapActivity.EXTRA_DELAY_DELETE, false)) {
7147 mHandler.sendEmptyMessageDelayed(POST_DUMP_HEAP_NOTIFICATION_MSG, 5*60*1000);
7148 } else {
7149 mHandler.sendEmptyMessage(POST_DUMP_HEAP_NOTIFICATION_MSG);
7150 }
7151 }
7152 }, dumpheapFilter);
7153
7154 // Let system services know.
7155 mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED);
7156
7157 synchronized (this) {
7158 // Ensure that any processes we had put on hold are now started
7159 // up.
7160 final int NP = mProcessesOnHold.size();
7161 if (NP > 0) {
7162 ArrayList<ProcessRecord> procs =
7163 new ArrayList<ProcessRecord>(mProcessesOnHold);
7164 for (int ip=0; ip<NP; ip++) {
7165 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "Starting process on hold: "
7166 + procs.get(ip));
7167 startProcessLocked(procs.get(ip), "on-hold", null);
7168 }
7169 }
7170
7171 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
7172 // Start looking for apps that are abusing wake locks.
7173 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7174 mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_DELAY);
7175 // Tell anyone interested that we are done booting!
7176 SystemProperties.set("sys.boot_completed", "1");
7177
7178 // And trigger dev.bootcomplete if we are not showing encryption progress
7179 if (!"trigger_restart_min_framework".equals(SystemProperties.get("vold.decrypt"))
7180 || "".equals(SystemProperties.get("vold.encrypt_progress"))) {
7181 SystemProperties.set("dev.bootcomplete", "1");
7182 }
7183 mUserController.sendBootCompletedLocked(
7184 new IIntentReceiver.Stub() {
7185 @Override
7186 public void performReceive(Intent intent, int resultCode,
7187 String data, Bundle extras, boolean ordered,
7188 boolean sticky, int sendingUser) {
7189 synchronized (ActivityManagerService.this) {
7190 requestPssAllProcsLocked(SystemClock.uptimeMillis(),
7191 true, false);
7192 }
7193 }
7194 });
7195 scheduleStartProfilesLocked();
7196 }
7197 }
7198 }
7199

boot动画结束

 7200    @Override
7201 public void bootAnimationComplete() {
7202 final boolean callFinishBooting;
7203 synchronized (this) {
7204 callFinishBooting = mCallFinishBooting;
7205 mBootAnimationComplete = true;
7206 }
7207 if (callFinishBooting) {
7208 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "FinishBooting");
7209 finishBooting();
7210 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
7211 }
7212 }

确保boot完成

 7214    final void ensureBootCompleted() {
7215 boolean booting;
7216 boolean enableScreen;
7217 synchronized (this) {
7218 booting = mBooting;
7219 mBooting = false;
7220 enableScreen = !mBooted;
7221 mBooted = true;
7222 }
7223
7224 if (booting) {
7225 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "FinishBooting");
7226 finishBooting();
7227 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
7228 }
7229
7230 if (enableScreen) {
7231 enableScreenAfterBoot();
7232 }
7233 }

Activity resumed,paused,stopped,destroyed,relaunched

 7235    @Override
7236 public final void activityResumed(IBinder token) {
7237 final long origId = Binder.clearCallingIdentity();
7238 synchronized(this) {
7239 ActivityRecord.activityResumedLocked(token);
7240 mWindowManager.notifyAppResumedFinished(token);
7241 }
7242 Binder.restoreCallingIdentity(origId);
7243 }
7244
7245 @Override
7246 public final void activityPaused(IBinder token) {
7247 final long origId = Binder.clearCallingIdentity();
7248 synchronized(this) {
7249 ActivityStack stack = ActivityRecord.getStackLocked(token);
7250 if (stack != null) {
7251 stack.activityPausedLocked(token, false);
7252 }
7253 }
7254 Binder.restoreCallingIdentity(origId);
7255 }
7256
7257 @Override
7258 public final void activityStopped(IBinder token, Bundle icicle,
7259 PersistableBundle persistentState, CharSequence description) {
7260 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
7261
7262 // Refuse possible leaked file descriptors
7263 if (icicle != null && icicle.hasFileDescriptors()) {
7264 throw new IllegalArgumentException("File descriptors passed in Bundle");
7265 }
7266
7267 final long origId = Binder.clearCallingIdentity();
7268
7269 synchronized (this) {
7270 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
7271 if (r != null) {
7272 r.activityStoppedLocked(icicle, persistentState, description);
7273 }
7274 }
7275
7276 trimApplications();
7277
7278 Binder.restoreCallingIdentity(origId);
7279 }
7280
7281 @Override
7282 public final void activityDestroyed(IBinder token) {
7283 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
7284 synchronized (this) {
7285 ActivityStack stack = ActivityRecord.getStackLocked(token);
7286 if (stack != null) {
7287 stack.activityDestroyedLocked(token, "activityDestroyed");
7288 }
7289 }
7290 }
7291
7292 @Override
7293 public final void activityRelaunched(IBinder token) {
7294 final long origId = Binder.clearCallingIdentity();
7295 synchronized (this) {
7296 mStackSupervisor.activityRelaunchedLocked(token);
7297 }
7298 Binder.restoreCallingIdentity(origId);
7299 }

后台资源释放

 7317    @Override
7318 public final void backgroundResourcesReleased(IBinder token) {
7319 final long origId = Binder.clearCallingIdentity();
7320 try {
7321 synchronized (this) {
7322 ActivityStack stack = ActivityRecord.getStackLocked(token);
7323 if (stack != null) {
7324 stack.backgroundResourcesReleased();
7325 }
7326 }
7327 } finally {
7328 Binder.restoreCallingIdentity(origId);
7329 }
7330 }

通知启动task behind被进入动画完成

 7332    @Override
7333 public final void notifyLaunchTaskBehindComplete(IBinder token) {
7334 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
7335 }
7336
7337 @Override
7338 public final void notifyEnterAnimationComplete(IBinder token) {
7339 mHandler.sendMessage(mHandler.obtainMessage(ENTER_ANIMATION_COMPLETE_MSG, token));
7340 }

获取调用package,activity,record,token的Activity class,token的package

 7342    @Override
7343 public String getCallingPackage(IBinder token) {
7344 synchronized (this) {
7345 ActivityRecord r = getCallingRecordLocked(token);
7346 return r != null ? r.info.packageName : null;
7347 }
7348 }
7349
7350 @Override
7351 public ComponentName getCallingActivity(IBinder token) {
7352 synchronized (this) {
7353 ActivityRecord r = getCallingRecordLocked(token);
7354 return r != null ? r.intent.getComponent() : null;
7355 }
7356 }
7357
7358 private ActivityRecord getCallingRecordLocked(IBinder token) {
7359 ActivityRecord r = ActivityRecord.isInStackLocked(token);
7360 if (r == null) {
7361 return null;
7362 }
7363 return r.resultTo;
7364 }
7365
7366 @Override
7367 public ComponentName getActivityClassForToken(IBinder token) {
7368 synchronized(this) {
7369 ActivityRecord r = ActivityRecord.isInStackLocked(token);
7370 if (r == null) {
7371 return null;
7372 }
7373 return r.intent.getComponent();
7374 }
7375 }
7376
7377 @Override
7378 public String getPackageForToken(IBinder token) {
7379 synchronized(this) {
7380 ActivityRecord r = ActivityRecord.isInStackLocked(token);
7381 if (r == null) {
7382 return null;
7383 }
7384 return r.packageName;
7385 }
7386 }

是否是root语音交互

 7388    @Override
7389 public boolean isRootVoiceInteraction(IBinder token) {
7390 synchronized(this) {
7391 ActivityRecord r = ActivityRecord.isInStackLocked(token);
7392 if (r == null) {
7393 return false;
7394 }
7395 return r.rootVoiceInteraction;
7396 }
7397 }

获取Intent sender

 7399    @Override
7400 public IIntentSender getIntentSender(int type,
7401 String packageName, IBinder token, String resultWho,
7402 int requestCode, Intent[] intents, String[] resolvedTypes,
7403 int flags, Bundle bOptions, int userId) {
7404 enforceNotIsolatedCaller("getIntentSender");
7405 // Refuse possible leaked file descriptors
7406 if (intents != null) {
7407 if (intents.length < 1) {
7408 throw new IllegalArgumentException("Intents array length must be >= 1");
7409 }
7410 for (int i=0; i<intents.length; i++) {
7411 Intent intent = intents[i];
7412 if (intent != null) {
7413 if (intent.hasFileDescriptors()) {
7414 throw new IllegalArgumentException("File descriptors passed in Intent");
7415 }
7416 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
7417 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
7418 throw new IllegalArgumentException(
7419 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
7420 }
7421 intents[i] = new Intent(intent);
7422 }
7423 }
7424 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
7425 throw new IllegalArgumentException(
7426 "Intent array length does not match resolvedTypes length");
7427 }
7428 }
7429 if (bOptions != null) {
7430 if (bOptions.hasFileDescriptors()) {
7431 throw new IllegalArgumentException("File descriptors passed in options");
7432 }
7433 }
7434
7435 synchronized(this) {
7436 int callingUid = Binder.getCallingUid();
7437 int origUserId = userId;
7438 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
7439 type == ActivityManager.INTENT_SENDER_BROADCAST,
7440 ALLOW_NON_FULL, "getIntentSender", null);
7441 if (origUserId == UserHandle.USER_CURRENT) {
7442 // We don't want to evaluate this until the pending intent is
7443 // actually executed. However, we do want to always do the
7444 // security checking for it above.
7445 userId = UserHandle.USER_CURRENT;
7446 }
7447 try {
7448 if (callingUid != 0 && callingUid != SYSTEM_UID) {
7449 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
7450 MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(callingUid));
7451 if (!UserHandle.isSameApp(callingUid, uid)) {
7452 String msg = "Permission Denial: getIntentSender() from pid="
7453 + Binder.getCallingPid()
7454 + ", uid=" + Binder.getCallingUid()
7455 + ", (need uid=" + uid + ")"
7456 + " is not allowed to send as package " + packageName;
7457 Slog.w(TAG, msg);
7458 throw new SecurityException(msg);
7459 }
7460 }
7461
7462 return getIntentSenderLocked(type, packageName, callingUid, userId,
7463 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
7464
7465 } catch (RemoteException e) {
7466 throw new SecurityException(e);
7467 }
7468 }
7469 }
7470
7471 IIntentSender getIntentSenderLocked(int type, String packageName,
7472 int callingUid, int userId, IBinder token, String resultWho,
7473 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
7474 Bundle bOptions) {
7475 if (DEBUG_MU) Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
7476 ActivityRecord activity = null;
7477 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
7478 activity = ActivityRecord.isInStackLocked(token);
7479 if (activity == null) {
7480 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
7481 return null;
7482 }
7483 if (activity.finishing) {
7484 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
7485 return null;
7486 }
7487 }
7488
7489 // We're going to be splicing together extras before sending, so we're
7490 // okay poking into any contained extras.
7491 if (intents != null) {
7492 for (int i = 0; i < intents.length; i++) {
7493 intents[i].setDefusable(true);
7494 }
7495 }
7496 Bundle.setDefusable(bOptions, true);
7497
7498 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
7499 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
7500 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
7501 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
7502 |PendingIntent.FLAG_UPDATE_CURRENT);
7503
7504 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
7505 type, packageName, activity, resultWho,
7506 requestCode, intents, resolvedTypes, flags, bOptions, userId);
7507 WeakReference<PendingIntentRecord> ref;
7508 ref = mIntentSenderRecords.get(key);
7509 PendingIntentRecord rec = ref != null ? ref.get() : null;
7510 if (rec != null) {
7511 if (!cancelCurrent) {
7512 if (updateCurrent) {
7513 if (rec.key.requestIntent != null) {
7514 rec.key.requestIntent.replaceExtras(intents != null ?
7515 intents[intents.length - 1] : null);
7516 }
7517 if (intents != null) {
7518 intents[intents.length-1] = rec.key.requestIntent;
7519 rec.key.allIntents = intents;
7520 rec.key.allResolvedTypes = resolvedTypes;
7521 } else {
7522 rec.key.allIntents = null;
7523 rec.key.allResolvedTypes = null;
7524 }
7525 }
7526 return rec;
7527 }
7528 makeIntentSenderCanceledLocked(rec);
7529 mIntentSenderRecords.remove(key);
7530 }
7531 if (noCreate) {
7532 return rec;
7533 }
7534 rec = new PendingIntentRecord(this, key, callingUid);
7535 mIntentSenderRecords.put(key, rec.ref);
7536 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
7537 if (activity.pendingResults == null) {
7538 activity.pendingResults
7539 = new HashSet<WeakReference<PendingIntentRecord>>();
7540 }
7541 activity.pendingResults.add(rec.ref);
7542 }
7543 return rec;
7544 }

发送Intent Sender

 7546    @Override
7547 public int sendIntentSender(IIntentSender target, IBinder whitelistToken, int code,
7548 Intent intent, String resolvedType,
7549 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
7550 if (target instanceof PendingIntentRecord) {
7551 return ((PendingIntentRecord)target).sendWithResult(code, intent, resolvedType,
7552 whitelistToken, finishedReceiver, requiredPermission, options);
7553 } else {
7554 if (intent == null) {
7555 // Weird case: someone has given us their own custom IIntentSender, and now
7556 // they have someone else trying to send to it but of course this isn't
7557 // really a PendingIntent, so there is no base Intent, and the caller isn't
7558 // supplying an Intent... but we never want to dispatch a null Intent to
7559 // a receiver, so um... let's make something up.
7560 Slog.wtf(TAG, "Can't use null intent with direct IIntentSender call");
7561 intent = new Intent(Intent.ACTION_MAIN);
7562 }
7563 try {
7564 target.send(code, intent, resolvedType, whitelistToken, null,
7565 requiredPermission, options);
7566 } catch (RemoteException e) {
7567 }
7568 // Platform code can rely on getting a result back when the send is done, but if
7569 // this intent sender is from outside of the system we can't rely on it doing that.
7570 // So instead we don't give it the result receiver, and instead just directly
7571 // report the finish immediately.
7572 if (finishedReceiver != null) {
7573 try {
7574 finishedReceiver.performReceive(intent, 0,
7575 null, null, false, false, UserHandle.getCallingUserId());
7576 } catch (RemoteException e) {
7577 }
7578 }
7579 return 0;
7580 }
7581 }

取消Intent Sender

 7583    @Override
7584 public void cancelIntentSender(IIntentSender sender) {
7585 if (!(sender instanceof PendingIntentRecord)) {
7586 return;
7587 }
7588 synchronized(this) {
7589 PendingIntentRecord rec = (PendingIntentRecord)sender;
7590 try {
7591 final int uid = AppGlobals.getPackageManager().getPackageUid(rec.key.packageName,
7592 MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getCallingUserId());
7593 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
7594 String msg = "Permission Denial: cancelIntentSender() from pid="
7595 + Binder.getCallingPid()
7596 + ", uid=" + Binder.getCallingUid()
7597 + " is not allowed to cancel package "
7598 + rec.key.packageName;
7599 Slog.w(TAG, msg);
7600 throw new SecurityException(msg);
7601 }
7602 } catch (RemoteException e) {
7603 throw new SecurityException(e);
7604 }
7605 cancelIntentSenderLocked(rec, true);
7606 }
7607 }
7608
7609 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
7610 makeIntentSenderCanceledLocked(rec);
7611 mIntentSenderRecords.remove(rec.key);
7612 if (cleanActivity && rec.key.activity != null) {
7613 rec.key.activity.pendingResults.remove(rec.ref);
7614 }
7615 }

制作Intent Sender cancel

 7617    void makeIntentSenderCanceledLocked(PendingIntentRecord rec) {
7618 rec.canceled = true;
7619 RemoteCallbackList<IResultReceiver> callbacks = rec.detachCancelListenersLocked();
7620 if (callbacks != null) {
7621 mHandler.obtainMessage(DISPATCH_PENDING_INTENT_CANCEL_MSG, callbacks).sendToTarget();
7622 }
7623 }
7624

为Intent Sender获取package

 7625    @Override
7626 public String getPackageForIntentSender(IIntentSender pendingResult) {
7627 if (!(pendingResult instanceof PendingIntentRecord)) {
7628 return null;
7629 }
7630 try {
7631 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
7632 return res.key.packageName;
7633 } catch (ClassCastException e) {
7634 }
7635 return null;
7636 }

注册、取消Intent Sender取消监听器

7638    @Override
7639 public void registerIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver) {
7640 if (!(sender instanceof PendingIntentRecord)) {
7641 return;
7642 }
7643 synchronized(this) {
7644 ((PendingIntentRecord)sender).registerCancelListenerLocked(receiver);
7645 }
7646 }
7647
7648 @Override
7649 public void unregisterIntentSenderCancelListener(IIntentSender sender,
7650 IResultReceiver receiver) {
7651 if (!(sender instanceof PendingIntentRecord)) {
7652 return;
7653 }
7654 synchronized(this) {
7655 ((PendingIntentRecord)sender).unregisterCancelListenerLocked(receiver);
7656 }
7657 }

为Intent Sender获取Uid

 7659    @Override
7660 public int getUidForIntentSender(IIntentSender sender) {
7661 if (sender instanceof PendingIntentRecord) {
7662 try {
7663 PendingIntentRecord res = (PendingIntentRecord)sender;
7664 return res.uid;
7665 } catch (ClassCastException e) {
7666 }
7667 }
7668 return -1;
7669 }
7670

是否Intent Sender目标的目标是相应package

 7671    @Override
7672 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
7673 if (!(pendingResult instanceof PendingIntentRecord)) {
7674 return false;
7675 }
7676 try {
7677 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
7678 if (res.key.allIntents == null) {
7679 return false;
7680 }
7681 for (int i=0; i<res.key.allIntents.length; i++) {
7682 Intent intent = res.key.allIntents[i];
7683 if (intent.getPackage() != null && intent.getComponent() != null) {
7684 return false;
7685 }
7686 }
7687 return true;
7688 } catch (ClassCastException e) {
7689 }
7690 return false;
7691 }
7692

是否Intent Sender是个Activity

 7693    @Override
7694 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
7695 if (!(pendingResult instanceof PendingIntentRecord)) {
7696 return false;
7697 }
7698 try {
7699 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
7700 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
7701 return true;
7702 }
7703 return false;
7704 } catch (ClassCastException e) {
7705 }
7706 return false;
7707 }

为Intent Sender获取Intent,tag

7709    @Override
7710 public Intent getIntentForIntentSender(IIntentSender pendingResult) {
7711 enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT,
7712 "getIntentForIntentSender()");
7713 if (!(pendingResult instanceof PendingIntentRecord)) {
7714 return null;
7715 }
7716 try {
7717 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
7718 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
7719 } catch (ClassCastException e) {
7720 }
7721 return null;
7722 }
7723
7724 @Override
7725 public String getTagForIntentSender(IIntentSender pendingResult, String prefix) {
7726 if (!(pendingResult instanceof PendingIntentRecord)) {
7727 return null;
7728 }
7729 try {
7730 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
7731 synchronized (this) {
7732 return getTagForIntentSenderLocked(res, prefix);
7733 }
7734 } catch (ClassCastException e) {
7735 }
7736 return null;
7737 }
7738
7739 String getTagForIntentSenderLocked(PendingIntentRecord res, String prefix) {
7740 final Intent intent = res.key.requestIntent;
7741 if (intent != null) {
7742 if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null
7743 || res.lastTagPrefix.equals(prefix))) {
7744 return res.lastTag;
7745 }
7746 res.lastTagPrefix = prefix;
7747 final StringBuilder sb = new StringBuilder(128);
7748 if (prefix != null) {
7749 sb.append(prefix);
7750 }
7751 if (intent.getAction() != null) {
7752 sb.append(intent.getAction());
7753 } else if (intent.getComponent() != null) {
7754 intent.getComponent().appendShortString(sb);
7755 } else {
7756 sb.append("?");
7757 }
7758 return res.lastTag = sb.toString();
7759 }
7760 return null;
7761 }
7762

设置、获取进程limit

 7763    @Override
7764 public void setProcessLimit(int max) {
7765 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
7766 "setProcessLimit()");
7767 synchronized (this) {
7768 mConstants.setOverrideMaxCachedProcesses(max);
7769 }
7770 trimApplications();
7771 }
7772
7773 @Override
7774 public int getProcessLimit() {
7775 synchronized (this) {
7776 return mConstants.getOverrideMaxCachedProcesses();
7777 }
7778 }

重要进程死亡

 7780    void importanceTokenDied(ImportanceToken token) {
7781 synchronized (ActivityManagerService.this) {
7782 synchronized (mPidsSelfLocked) {
7783 ImportanceToken cur
7784 = mImportantProcesses.get(token.pid);
7785 if (cur != token) {
7786 return;
7787 }
7788 mImportantProcesses.remove(token.pid);
7789 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
7790 if (pr == null) {
7791 return;
7792 }
7793 pr.forcingToImportant = null;
7794 updateProcessForegroundLocked(pr, false, false);
7795 }
7796 updateOomAdjLocked();
7797 }
7798 }

设置进程important

 7800    @Override
7801 public void setProcessImportant(IBinder token, int pid, boolean isForeground, String reason) {
7802 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
7803 "setProcessImportant()");
7804 synchronized(this) {
7805 boolean changed = false;
7806
7807 synchronized (mPidsSelfLocked) {
7808 ProcessRecord pr = mPidsSelfLocked.get(pid);
7809 if (pr == null && isForeground) {
7810 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
7811 return;
7812 }
7813 ImportanceToken oldToken = mImportantProcesses.get(pid);
7814 if (oldToken != null) {
7815 oldToken.token.unlinkToDeath(oldToken, 0);
7816 mImportantProcesses.remove(pid);
7817 if (pr != null) {
7818 pr.forcingToImportant = null;
7819 }
7820 changed = true;
7821 }
7822 if (isForeground && token != null) {
7823 ImportanceToken newToken = new ImportanceToken(pid, token, reason) {
7824 @Override
7825 public void binderDied() {
7826 importanceTokenDied(this);
7827 }
7828 };
7829 try {
7830 token.linkToDeath(newToken, 0);
7831 mImportantProcesses.put(pid, newToken);
7832 pr.forcingToImportant = newToken;
7833 changed = true;
7834 } catch (RemoteException e) {
7835 // If the process died while doing this, we will later
7836 // do the cleanup with the process death link.
7837 }
7838 }
7839 }
7840
7841 if (changed) {
7842 updateOomAdjLocked();
7843 }
7844 }
7845 }
7846

判断app是否在前台

 7847    @Override
7848 public boolean isAppForeground(int uid) throws RemoteException {
7849 synchronized (this) {
7850 UidRecord uidRec = mActiveUids.get(uid);
7851 if (uidRec == null || uidRec.idle) {
7852 return false;
7853 }
7854 return uidRec.curProcState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
7855 }
7856 }

获取uid状态

 7858    // NOTE: this is an internal method used by the OnShellCommand implementation only and should
7859 // be guarded by permission checking.
7860 int getUidState(int uid) {
7861 synchronized (this) {
7862 return getUidStateLocked(uid);
7863 }
7864 }

获取uid state

 7866    int getUidStateLocked(int uid) {
7867 UidRecord uidRec = mActiveUids.get(uid);
7868 return uidRec == null ? ActivityManager.PROCESS_STATE_NONEXISTENT : uidRec.curProcState;
7869 }

是否在多窗口模式

 7871    @Override
7872 public boolean isInMultiWindowMode(IBinder token) {
7873 final long origId = Binder.clearCallingIdentity();
7874 try {
7875 synchronized(this) {
7876 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
7877 if (r == null) {
7878 return false;
7879 }
7880 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
7881 return !r.getTask().mFullscreen;
7882 }
7883 } finally {
7884 Binder.restoreCallingIdentity(origId);
7885 }
7886 }

pip模式相关

 7888    @Override
7889 public boolean isInPictureInPictureMode(IBinder token) {
7890 final long origId = Binder.clearCallingIdentity();
7891 try {
7892 synchronized(this) {
7893 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
7894 }
7895 } finally {
7896 Binder.restoreCallingIdentity(origId);
7897 }
7898 }
7899
7900 private boolean isInPictureInPictureMode(ActivityRecord r) {
7901 if (r == null || r.getStack() == null || !r.getStack().isPinnedStack() ||
7902 r.getStack().isInStackLocked(r) == null) {
7903 return false;
7904 }
7905
7906 // If we are animating to fullscreen then we have already dispatched the PIP mode
7907 // changed, so we should reflect that check here as well.
7908 final PinnedActivityStack stack = r.getStack();
7909 final PinnedStackWindowController windowController = stack.getWindowContainerController();
7910 return !windowController.isAnimatingBoundsToFullscreen();
7911 }
7912
7913 @Override
7914 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
7915 final long origId = Binder.clearCallingIdentity();
7916 try {
7917 synchronized(this) {
7918 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
7919 "enterPictureInPictureMode", token, params);
7920
7921 // If the activity is already in picture in picture mode, then just return early
7922 if (isInPictureInPictureMode(r)) {
7923 return true;
7924 }
7925
7926 // Activity supports picture-in-picture, now check that we can enter PiP at this
7927 // point, if it is
7928 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
7929 false /* noThrow */, false /* beforeStopping */)) {
7930 return false;
7931 }
7932
7933 final Runnable enterPipRunnable = () -> {
7934 // Only update the saved args from the args that are set
7935 r.pictureInPictureArgs.copyOnlySet(params);
7936 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
7937 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
7938 // Adjust the source bounds by the insets for the transition down
7939 final Rect sourceBounds = new Rect(r.pictureInPictureArgs.getSourceRectHint());
7940 mStackSupervisor.moveActivityToPinnedStackLocked(r, sourceBounds, aspectRatio,
7941 true /* moveHomeStackToFront */, "enterPictureInPictureMode");
7942 final PinnedActivityStack stack = mStackSupervisor.getStack(PINNED_STACK_ID);
7943 stack.setPictureInPictureAspectRatio(aspectRatio);
7944 stack.setPictureInPictureActions(actions);
7945
7946 MetricsLogger.action(mContext, MetricsEvent.ACTION_PICTURE_IN_PICTURE_ENTERED,
7947 r.supportsPictureInPictureWhilePausing);
7948 logPictureInPictureArgs(params);
7949 };
7950
7951 if (isKeyguardLocked()) {
7952 // If the keyguard is showing or occluded, then try and dismiss it before
7953 // entering picture-in-picture (this will prompt the user to authenticate if the
7954 // device is currently locked).
7955 try {
7956 dismissKeyguard(token, new IKeyguardDismissCallback.Stub() {
7957 @Override
7958 public void onDismissError() throws RemoteException {
7959 // Do nothing
7960 }
7961
7962 @Override
7963 public void onDismissSucceeded() throws RemoteException {
7964 mHandler.post(enterPipRunnable);
7965 }
7966
7967 @Override
7968 public void onDismissCancelled() throws RemoteException {
7969 // Do nothing
7970 }
7971 });
7972 } catch (RemoteException e) {
7973 // Local call
7974 }
7975 } else {
7976 // Enter picture in picture immediately otherwise
7977 enterPipRunnable.run();
7978 }
7979 return true;
7980 }
7981 } finally {
7982 Binder.restoreCallingIdentity(origId);
7983 }
7984 }
7985
7986 @Override
7987 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
7988 final long origId = Binder.clearCallingIdentity();
7989 try {
7990 synchronized(this) {
7991 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
7992 "setPictureInPictureParams", token, params);
7993
7994 // Only update the saved args from the args that are set
7995 r.pictureInPictureArgs.copyOnlySet(params);
7996 if (r.getStack().getStackId() == PINNED_STACK_ID) {
7997 // If the activity is already in picture-in-picture, update the pinned stack now
7998 // if it is not already expanding to fullscreen. Otherwise, the arguments will
7999 // be used the next time the activity enters PiP
8000 final PinnedActivityStack stack = r.getStack();
8001 if (!stack.isAnimatingBoundsToFullscreen()) {
8002 stack.setPictureInPictureAspectRatio(
8003 r.pictureInPictureArgs.getAspectRatio());
8004 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
8005 }
8006 }
8007 logPictureInPictureArgs(params);
8008 }
8009 } finally {
8010 Binder.restoreCallingIdentity(origId);
8011 }
8012 }
8013
8014 @Override
8015 public int getMaxNumPictureInPictureActions(IBinder token) {
8016 // Currently, this is a static constant, but later, we may change this to be dependent on
8017 // the context of the activity
8018 return 3;
8019 }
8020
8021 private void logPictureInPictureArgs(PictureInPictureParams params) {
8022 if (params.hasSetActions()) {
8023 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
8024 params.getActions().size());
8025 }
8026 if (params.hasSetAspectRatio()) {
8027 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
8028 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
8029 MetricsLogger.action(lm);
8030 }
8031 }
8032
8033 /**
8034 * Checks the state of the system and the activity associated with the given {@param token} to
8035 * verify that picture-in-picture is supported for that activity.
8036 *
8037 * @return the activity record for the given {@param token} if all the checks pass.
8038 */
8039 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
8040 IBinder token, PictureInPictureParams params) {
8041 if (!mSupportsPictureInPicture) {
8042 throw new IllegalStateException(caller
8043 + ": Device doesn't support picture-in-picture mode.");
8044 }
8045
8046 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
8047 if (r == null) {
8048 throw new IllegalStateException(caller
8049 + ": Can't find activity for token=" + token);
8050 }
8051
8052 if (!r.supportsPictureInPicture()) {
8053 throw new IllegalStateException(caller
8054 + ": Current activity does not support picture-in-picture.");
8055 }
8056
8057 if (!StackId.isAllowedToEnterPictureInPicture(r.getStack().getStackId())) {
8058 throw new IllegalStateException(caller
8059 + ": Activities on the home, assistant, or recents stack not supported");
8060 }
8061
8062 if (params.hasSetAspectRatio()
8063 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId,
8064 params.getAspectRatio())) {
8065 final float minAspectRatio = mContext.getResources().getFloat(
8066 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
8067 final float maxAspectRatio = mContext.getResources().getFloat(
8068 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
8069 throw new IllegalArgumentException(String.format(caller
8070 + ": Aspect ratio is too extreme (must be between %f and %f).",
8071 minAspectRatio, maxAspectRatio));
8072 }
8073
8074 // Truncate the number of actions if necessary
8075 params.truncateActions(getMaxNumPictureInPictureActions(token));
8076
8077 return r;
8078 }

process info相关

 8079
8080 // =========================================================
8081 // PROCESS INFO
8082 // =========================================================
8083
8084 static class ProcessInfoService extends IProcessInfoService.Stub {
8085 final ActivityManagerService mActivityManagerService;
8086 ProcessInfoService(ActivityManagerService activityManagerService) {
8087 mActivityManagerService = activityManagerService;
8088 }
8089
8090 @Override
8091 public void getProcessStatesFromPids(/*in*/ int[] pids, /*out*/ int[] states) {
8092 mActivityManagerService.getProcessStatesAndOomScoresForPIDs(
8093 /*in*/ pids, /*out*/ states, null);
8094 }
8095
8096 @Override
8097 public void getProcessStatesAndOomScoresFromPids(
8098 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) {
8099 mActivityManagerService.getProcessStatesAndOomScoresForPIDs(
8100 /*in*/ pids, /*out*/ states, /*out*/ scores);
8101 }
8102 }
8103
8104 /**
8105 * For each PID in the given input array, write the current process state
8106 * for that process into the states array, or -1 to indicate that no
8107 * process with the given PID exists. If scores array is provided, write
8108 * the oom score for the process into the scores array, with INVALID_ADJ
8109 * indicating the PID doesn't exist.
8110 */
8111 public void getProcessStatesAndOomScoresForPIDs(
8112 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) {
8113 if (scores != null) {
8114 enforceCallingPermission(android.Manifest.permission.GET_PROCESS_STATE_AND_OOM_SCORE,
8115 "getProcessStatesAndOomScoresForPIDs()");
8116 }
8117
8118 if (pids == null) {
8119 throw new NullPointerException("pids");
8120 } else if (states == null) {
8121 throw new NullPointerException("states");
8122 } else if (pids.length != states.length) {
8123 throw new IllegalArgumentException("pids and states arrays have different lengths!");
8124 } else if (scores != null && pids.length != scores.length) {
8125 throw new IllegalArgumentException("pids and scores arrays have different lengths!");
8126 }
8127
8128 synchronized (mPidsSelfLocked) {
8129 for (int i = 0; i < pids.length; i++) {
8130 ProcessRecord pr = mPidsSelfLocked.get(pids[i]);
8131 states[i] = (pr == null) ? ActivityManager.PROCESS_STATE_NONEXISTENT :
8132 pr.curProcState;
8133 if (scores != null) {
8134 scores[i] = (pr == null) ? ProcessList.INVALID_ADJ : pr.curAdj;
8135 }
8136 }
8137 }
8138 }
8139

permission相关

 8140    // =========================================================
8141 // PERMISSIONS
8142 // =========================================================
8143
8144 static class PermissionController extends IPermissionController.Stub {
8145 ActivityManagerService mActivityManagerService;
8146 PermissionController(ActivityManagerService activityManagerService) {
8147 mActivityManagerService = activityManagerService;
8148 }
8149
8150 @Override
8151 public boolean checkPermission(String permission, int pid, int uid) {
8152 return mActivityManagerService.checkPermission(permission, pid,
8153 uid) == PackageManager.PERMISSION_GRANTED;
8154 }
8155
8156 @Override
8157 public String[] getPackagesForUid(int uid) {
8158 return mActivityManagerService.mContext.getPackageManager()
8159 .getPackagesForUid(uid);
8160 }
8161
8162 @Override
8163 public boolean isRuntimePermission(String permission) {
8164 try {
8165 PermissionInfo info = mActivityManagerService.mContext.getPackageManager()
8166 .getPermissionInfo(permission, 0);
8167 return (info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
8168 == PermissionInfo.PROTECTION_DANGEROUS;
8169 } catch (NameNotFoundException nnfe) {
8170 Slog.e(TAG, "No such permission: "+ permission, nnfe);
8171 }
8172 return false;
8173 }
8174 }
8175
8176 class IntentFirewallInterface implements IntentFirewall.AMSInterface {
8177 @Override
8178 public int checkComponentPermission(String permission, int pid, int uid,
8179 int owningUid, boolean exported) {
8180 return ActivityManagerService.this.checkComponentPermission(permission, pid, uid,
8181 owningUid, exported);
8182 }
8183
8184 @Override
8185 public Object getAMSLock() {
8186 return ActivityManagerService.this;
8187 }
8188 }
8189
8190 /**
8191 * This can be called with or without the global lock held.
8192 */
8193 int checkComponentPermission(String permission, int pid, int uid,
8194 int owningUid, boolean exported) {
8195 if (pid == MY_PID) {
8196 return PackageManager.PERMISSION_GRANTED;
8197 }
8198 return ActivityManager.checkComponentPermission(permission, uid,
8199 owningUid, exported);
8200 }
8201
8202 /**
8203 * As the only public entry point for permissions checking, this method
8204 * can enforce the semantic that requesting a check on a null global
8205 * permission is automatically denied. (Internally a null permission
8206 * string is used when calling {@link #checkComponentPermission} in cases
8207 * when only uid-based security is needed.)
8208 *
8209 * This can be called with or without the global lock held.
8210 */
8211 @Override
8212 public int checkPermission(String permission, int pid, int uid) {
8213 if (permission == null) {
8214 return PackageManager.PERMISSION_DENIED;
8215 }
8216 return checkComponentPermission(permission, pid, uid, -1, true);
8217 }
8218
8219 @Override
8220 public int checkPermissionWithToken(String permission, int pid, int uid, IBinder callerToken) {
8221 if (permission == null) {
8222 return PackageManager.PERMISSION_DENIED;
8223 }
8224
8225 // We might be performing an operation on behalf of an indirect binder
8226 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
8227 // client identity accordingly before proceeding.
8228 Identity tlsIdentity = sCallerIdentity.get();
8229 if (tlsIdentity != null && tlsIdentity.token == callerToken) {
8230 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
8231 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
8232 uid = tlsIdentity.uid;
8233 pid = tlsIdentity.pid;
8234 }
8235
8236 return checkComponentPermission(permission, pid, uid, -1, true);
8237 }
8238
8239 /**
8240 * Binder IPC calls go through the public entry point.
8241 * This can be called with or without the global lock held.
8242 */
8243 int checkCallingPermission(String permission) {
8244 return checkPermission(permission,
8245 Binder.getCallingPid(),
8246 UserHandle.getAppId(Binder.getCallingUid()));
8247 }
8248
8249 /**
8250 * This can be called with or without the global lock held.
8251 */
8252 void enforceCallingPermission(String permission, String func) {
8253 if (checkCallingPermission(permission)
8254 == PackageManager.PERMISSION_GRANTED) {
8255 return;
8256 }
8257
8258 String msg = "Permission Denial: " + func + " from pid="
8259 + Binder.getCallingPid()
8260 + ", uid=" + Binder.getCallingUid()
8261 + " requires " + permission;
8262 Slog.w(TAG, msg);
8263 throw new SecurityException(msg);
8264 }
8265
8266 /**
8267 * Determine if UID is holding permissions required to access {@link Uri} in
8268 * the given {@link ProviderInfo}. Final permission checking is always done
8269 * in {@link ContentProvider}.
8270 */
8271 private final boolean checkHoldingPermissionsLocked(
8272 IPackageManager pm, ProviderInfo pi, GrantUri grantUri, int uid, final int modeFlags) {
8273 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION,
8274 "checkHoldingPermissionsLocked: uri=" + grantUri + " uid=" + uid);
8275 if (UserHandle.getUserId(uid) != grantUri.sourceUserId) {
8276 if (ActivityManager.checkComponentPermission(INTERACT_ACROSS_USERS, uid, -1, true)
8277 != PERMISSION_GRANTED) {
8278 return false;
8279 }
8280 }
8281 return checkHoldingPermissionsInternalLocked(pm, pi, grantUri, uid, modeFlags, true);
8282 }
8283
8284 private final boolean checkHoldingPermissionsInternalLocked(IPackageManager pm, ProviderInfo pi,
8285 GrantUri grantUri, int uid, final int modeFlags, boolean considerUidPermissions) {
8286 if (pi.applicationInfo.uid == uid) {
8287 return true;
8288 } else if (!pi.exported) {
8289 return false;
8290 }
8291
8292 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
8293 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
8294 try {
8295 // check if target holds top-level <provider> permissions
8296 if (!readMet && pi.readPermission != null && considerUidPermissions
8297 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
8298 readMet = true;
8299 }
8300 if (!writeMet && pi.writePermission != null && considerUidPermissions
8301 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
8302 writeMet = true;
8303 }
8304
8305 // track if unprotected read/write is allowed; any denied
8306 // <path-permission> below removes this ability
8307 boolean allowDefaultRead = pi.readPermission == null;
8308 boolean allowDefaultWrite = pi.writePermission == null;
8309
8310 // check if target holds any <path-permission> that match uri
8311 final PathPermission[] pps = pi.pathPermissions;
8312 if (pps != null) {
8313 final String path = grantUri.uri.getPath();
8314 int i = pps.length;
8315 while (i > 0 && (!readMet || !writeMet)) {
8316 i--;
8317 PathPermission pp = pps[i];
8318 if (pp.match(path)) {
8319 if (!readMet) {
8320 final String pprperm = pp.getReadPermission();
8321 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION,
8322 "Checking read perm for " + pprperm + " for " + pp.getPath()
8323 + ": match=" + pp.match(path)
8324 + " check=" + pm.checkUidPermission(pprperm, uid));
8325 if (pprperm != null) {
8326 if (considerUidPermissions && pm.checkUidPermission(pprperm, uid)
8327 == PERMISSION_GRANTED) {
8328 readMet = true;
8329 } else {
8330 allowDefaultRead = false;
8331 }
8332 }
8333 }
8334 if (!writeMet) {
8335 final String ppwperm = pp.getWritePermission();
8336 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION,
8337 "Checking write perm " + ppwperm + " for " + pp.getPath()
8338 + ": match=" + pp.match(path)
8339 + " check=" + pm.checkUidPermission(ppwperm, uid));
8340 if (ppwperm != null) {
8341 if (considerUidPermissions && pm.checkUidPermission(ppwperm, uid)
8342 == PERMISSION_GRANTED) {
8343 writeMet = true;
8344 } else {
8345 allowDefaultWrite = false;
8346 }
8347 }
8348 }
8349 }
8350 }
8351 }
8352
8353 // grant unprotected <provider> read/write, if not blocked by
8354 // <path-permission> above
8355 if (allowDefaultRead) readMet = true;
8356 if (allowDefaultWrite) writeMet = true;
8357
8358 } catch (RemoteException e) {
8359 return false;
8360 }
8361
8362 return readMet && writeMet;
8363 }

是否app start mode被禁止

 8365    public boolean isAppStartModeDisabled(int uid, String packageName) {
8366 synchronized (this) {
8367 return getAppStartModeLocked(uid, packageName, 0, -1, false, true)
8368 == ActivityManager.APP_START_MODE_DISABLED;
8369 }
8370 }

app被限制在后台

 8372    // Unified app-op and target sdk check
8373 int appRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk) {
8374 // Apps that target O+ are always subject to background check
8375 if (packageTargetSdk >= Build.VERSION_CODES.O) {
8376 if (DEBUG_BACKGROUND_CHECK) {
8377 Slog.i(TAG, "App " + uid + "/" + packageName + " targets O+, restricted");
8378 }
8379 return ActivityManager.APP_START_MODE_DELAYED_RIGID;
8380 }
8381 // ...and legacy apps get an AppOp check
8382 int appop = mAppOpsService.noteOperation(AppOpsManager.OP_RUN_IN_BACKGROUND,
8383 uid, packageName);
8384 if (DEBUG_BACKGROUND_CHECK) {
8385 Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " bg appop " + appop);
8386 }
8387 switch (appop) {
8388 case AppOpsManager.MODE_ALLOWED:
8389 return ActivityManager.APP_START_MODE_NORMAL;
8390 case AppOpsManager.MODE_IGNORED:
8391 return ActivityManager.APP_START_MODE_DELAYED;
8392 default:
8393 return ActivityManager.APP_START_MODE_DELAYED_RIGID;
8394 }
8395 }
8396
8397 // Service launch is available to apps with run-in-background exemptions but
8398 // some other background operations are not. If we're doing a check
8399 // of service-launch policy, allow those callers to proceed unrestricted.
8400 int appServicesRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk) {
8401 // Persistent app?
8402 if (mPackageManagerInt.isPackagePersistent(packageName)) {
8403 if (DEBUG_BACKGROUND_CHECK) {
8404 Slog.i(TAG, "App " + uid + "/" + packageName
8405 + " is persistent; not restricted in background");
8406 }
8407 return ActivityManager.APP_START_MODE_NORMAL;
8408 }
8409
8410 // Non-persistent but background whitelisted?
8411 if (uidOnBackgroundWhitelist(uid)) {
8412 if (DEBUG_BACKGROUND_CHECK) {
8413 Slog.i(TAG, "App " + uid + "/" + packageName
8414 + " on background whitelist; not restricted in background");
8415 }
8416 return ActivityManager.APP_START_MODE_NORMAL;
8417 }
8418
8419 // Is this app on the battery whitelist?
8420 if (isOnDeviceIdleWhitelistLocked(uid)) {
8421 if (DEBUG_BACKGROUND_CHECK) {
8422 Slog.i(TAG, "App " + uid + "/" + packageName
8423 + " on idle whitelist; not restricted in background");
8424 }
8425 return ActivityManager.APP_START_MODE_NORMAL;
8426 }
8427
8428 // None of the service-policy criteria apply, so we apply the common criteria
8429 return appRestrictedInBackgroundLocked(uid, packageName, packageTargetSdk);
8430 }

获取app启动模式

 8432    int getAppStartModeLocked(int uid, String packageName, int packageTargetSdk,
8433 int callingPid, boolean alwaysRestrict, boolean disabledOnly) {
8434 UidRecord uidRec = mActiveUids.get(uid);
8435 if (DEBUG_BACKGROUND_CHECK) Slog.d(TAG, "checkAllowBackground: uid=" + uid + " pkg="
8436 + packageName + " rec=" + uidRec + " always=" + alwaysRestrict + " idle="
8437 + (uidRec != null ? uidRec.idle : false));
8438 if (uidRec == null || alwaysRestrict || uidRec.idle) {
8439 boolean ephemeral;
8440 if (uidRec == null) {
8441 ephemeral = getPackageManagerInternalLocked().isPackageEphemeral(
8442 UserHandle.getUserId(uid), packageName);
8443 } else {
8444 ephemeral = uidRec.ephemeral;
8445 }
8446
8447 if (ephemeral) {
8448 // We are hard-core about ephemeral apps not running in the background.
8449 return ActivityManager.APP_START_MODE_DISABLED;
8450 } else {
8451 if (disabledOnly) {
8452 // The caller is only interested in whether app starts are completely
8453 // disabled for the given package (that is, it is an instant app). So
8454 // we don't need to go further, which is all just seeing if we should
8455 // apply a "delayed" mode for a regular app.
8456 return ActivityManager.APP_START_MODE_NORMAL;
8457 }
8458 final int startMode = (alwaysRestrict)
8459 ? appRestrictedInBackgroundLocked(uid, packageName, packageTargetSdk)
8460 : appServicesRestrictedInBackgroundLocked(uid, packageName,
8461 packageTargetSdk);
8462 if (DEBUG_BACKGROUND_CHECK) Slog.d(TAG, "checkAllowBackground: uid=" + uid
8463 + " pkg=" + packageName + " startMode=" + startMode
8464 + " onwhitelist=" + isOnDeviceIdleWhitelistLocked(uid));
8465 if (startMode == ActivityManager.APP_START_MODE_DELAYED) {
8466 // This is an old app that has been forced into a "compatible as possible"
8467 // mode of background check. To increase compatibility, we will allow other
8468 // foreground apps to cause its services to start.
8469 if (callingPid >= 0) {
8470 ProcessRecord proc;
8471 synchronized (mPidsSelfLocked) {
8472 proc = mPidsSelfLocked.get(callingPid);
8473 }
8474 if (proc != null &&
8475 !ActivityManager.isProcStateBackground(proc.curProcState)) {
8476 // Whoever is instigating this is in the foreground, so we will allow it
8477 // to go through.
8478 return ActivityManager.APP_START_MODE_NORMAL;
8479 }
8480 }
8481 }
8482 return startMode;
8483 }
8484 }
8485 return ActivityManager.APP_START_MODE_NORMAL;
8486 }

是否在设备空闲白名单上

 8488    boolean isOnDeviceIdleWhitelistLocked(int uid) {
8489 final int appId = UserHandle.getAppId(uid);
8490 return Arrays.binarySearch(mDeviceIdleWhitelist, appId) >= 0
8491 || Arrays.binarySearch(mDeviceIdleTempWhitelist, appId) >= 0
8492 || mPendingTempWhitelist.indexOfKey(uid) >= 0;
8493 }

获取provider info

 8495    private ProviderInfo getProviderInfoLocked(String authority, int userHandle, int pmFlags) {
8496 ProviderInfo pi = null;
8497 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userHandle);
8498 if (cpr != null) {
8499 pi = cpr.info;
8500 } else {
8501 try {
8502 pi = AppGlobals.getPackageManager().resolveContentProvider(
8503 authority, PackageManager.GET_URI_PERMISSION_PATTERNS | pmFlags,
8504 userHandle);
8505 } catch (RemoteException ex) {
8506 }
8507 }
8508 return pi;
8509 }
8510

授权访问ephemeral

 8511    void grantEphemeralAccessLocked(int userId, Intent intent,
8512 int targetAppId, int ephemeralAppId) {
8513 getPackageManagerInternalLocked().
8514 grantEphemeralAccess(userId, intent, targetAppId, ephemeralAppId);
8515 }

uri permission相关

 8517    private UriPermission findUriPermissionLocked(int targetUid, GrantUri grantUri) {
8518 final ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid);
8519 if (targetUris != null) {
8520 return targetUris.get(grantUri);
8521 }
8522 return null;
8523 }
8524
8525 private UriPermission findOrCreateUriPermissionLocked(String sourcePkg,
8526 String targetPkg, int targetUid, GrantUri grantUri) {
8527 ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid);
8528 if (targetUris == null) {
8529 targetUris = Maps.newArrayMap();
8530 mGrantedUriPermissions.put(targetUid, targetUris);
8531 }
8532
8533 UriPermission perm = targetUris.get(grantUri);
8534 if (perm == null) {
8535 perm = new UriPermission(sourcePkg, targetPkg, targetUid, grantUri);
8536 targetUris.put(grantUri, perm);
8537 }
8538
8539 return perm;
8540 }
8541
8542 private final boolean checkUriPermissionLocked(GrantUri grantUri, int uid,
8543 final int modeFlags) {
8544 final boolean persistable = (modeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0;
8545 final int minStrength = persistable ? UriPermission.STRENGTH_PERSISTABLE
8546 : UriPermission.STRENGTH_OWNED;
8547
8548 // Root gets to do everything.
8549 if (uid == 0) {
8550 return true;
8551 }
8552
8553 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid);
8554 if (perms == null) return false;
8555
8556 // First look for exact match
8557 final UriPermission exactPerm = perms.get(grantUri);
8558 if (exactPerm != null && exactPerm.getStrength(modeFlags) >= minStrength) {
8559 return true;
8560 }
8561
8562 // No exact match, look for prefixes
8563 final int N = perms.size();
8564 for (int i = 0; i < N; i++) {
8565 final UriPermission perm = perms.valueAt(i);
8566 if (perm.uri.prefix && grantUri.uri.isPathPrefixMatch(perm.uri.uri)
8567 && perm.getStrength(modeFlags) >= minStrength) {
8568 return true;
8569 }
8570 }
8571
8572 return false;
8573 }
8574
8575 /**
8576 * @param uri This uri must NOT contain an embedded userId.
8577 * @param userId The userId in which the uri is to be resolved.
8578 */
8579 @Override
8580 public int checkUriPermission(Uri uri, int pid, int uid,
8581 final int modeFlags, int userId, IBinder callerToken) {
8582 enforceNotIsolatedCaller("checkUriPermission");
8583
8584 // Another redirected-binder-call permissions check as in
8585 // {@link checkPermissionWithToken}.
8586 Identity tlsIdentity = sCallerIdentity.get();
8587 if (tlsIdentity != null && tlsIdentity.token == callerToken) {
8588 uid = tlsIdentity.uid;
8589 pid = tlsIdentity.pid;
8590 }
8591
8592 // Our own process gets to do everything.
8593 if (pid == MY_PID) {
8594 return PackageManager.PERMISSION_GRANTED;
8595 }
8596 synchronized (this) {
8597 return checkUriPermissionLocked(new GrantUri(userId, uri, false), uid, modeFlags)
8598 ? PackageManager.PERMISSION_GRANTED
8599 : PackageManager.PERMISSION_DENIED;
8600 }
8601 }
8602
8603 /**
8604 * Check if the targetPkg can be granted permission to access uri by
8605 * the callingUid using the given modeFlags. Throws a security exception
8606 * if callingUid is not allowed to do this. Returns the uid of the target
8607 * if the URI permission grant should be performed; returns -1 if it is not
8608 * needed (for example targetPkg already has permission to access the URI).
8609 * If you already know the uid of the target, you can supply it in
8610 * lastTargetUid else set that to -1.
8611 */
8612 int checkGrantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri,
8613 final int modeFlags, int lastTargetUid) {
8614 if (!Intent.isAccessUriMode(modeFlags)) {
8615 return -1;
8616 }
8617
8618 if (targetPkg != null) {
8619 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION,
8620 "Checking grant " + targetPkg + " permission to " + grantUri);
8621 }
8622
8623 final IPackageManager pm = AppGlobals.getPackageManager();
8624
8625 // If this is not a content: uri, we can't do anything with it.
8626 if (!ContentResolver.SCHEME_CONTENT.equals(grantUri.uri.getScheme())) {
8627 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION,
8628 "Can't grant URI permission for non-content URI: " + grantUri);
8629 return -1;
8630 }
8631
8632 final String authority = grantUri.uri.getAuthority();
8633 final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId,
8634 MATCH_DEBUG_TRIAGED_MISSING);
8635 if (pi == null) {
8636 Slog.w(TAG, "No content provider found for permission check: " +
8637 grantUri.uri.toSafeString());
8638 return -1;
8639 }
8640
8641 int targetUid = lastTargetUid;
8642 if (targetUid < 0 && targetPkg != null) {
8643 try {
8644 targetUid = pm.getPackageUid(targetPkg, MATCH_DEBUG_TRIAGED_MISSING,
8645 UserHandle.getUserId(callingUid));
8646 if (targetUid < 0) {
8647 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION,
8648 "Can't grant URI permission no uid for: " + targetPkg);
8649 return -1;
8650 }
8651 } catch (RemoteException ex) {
8652 return -1;
8653 }
8654 }
8655
8656 // If we're extending a persistable grant, then we always need to create
8657 // the grant data structure so that take/release APIs work
8658 if ((modeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0) {
8659 return targetUid;
8660 }
8661
8662 if (targetUid >= 0) {
8663 // First... does the target actually need this permission?
8664 if (checkHoldingPermissionsLocked(pm, pi, grantUri, targetUid, modeFlags)) {
8665 // No need to grant the target this permission.
8666 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION,
8667 "Target " + targetPkg + " already has full permission to " + grantUri);
8668 return -1;
8669 }
8670 } else {
8671 // First... there is no target package, so can anyone access it?
8672 boolean allowed = pi.exported;
8673 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
8674 if (pi.readPermission != null) {
8675 allowed = false;
8676 }
8677 }
8678 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
8679 if (pi.writePermission != null) {
8680 allowed = false;
8681 }
8682 }
8683 if (allowed) {
8684 return -1;
8685 }
8686 }
8687
8688 /* There is a special cross user grant if:
8689 * - The target is on another user.
8690 * - Apps on the current user can access the uri without any uid permissions.
8691 * In this case, we grant a uri permission, even if the ContentProvider does not normally
8692 * grant uri permissions.
8693 */
8694 boolean specialCrossUserGrant = UserHandle.getUserId(targetUid) != grantUri.sourceUserId
8695 && checkHoldingPermissionsInternalLocked(pm, pi, grantUri, callingUid,
8696 modeFlags, false /*without considering the uid permissions*/);
8697
8698 // Second... is the provider allowing granting of URI permissions?
8699 if (!specialCrossUserGrant) {
8700 if (!pi.grantUriPermissions) {
8701 throw new SecurityException("Provider " + pi.packageName
8702 + "/" + pi.name
8703 + " does not allow granting of Uri permissions (uri "
8704 + grantUri + ")");
8705 }
8706 if (pi.uriPermissionPatterns != null) {
8707 final int N = pi.uriPermissionPatterns.length;
8708 boolean allowed = false;
8709 for (int i=0; i<N; i++) {
8710 if (pi.uriPermissionPatterns[i] != null
8711 && pi.uriPermissionPatterns[i].match(grantUri.uri.getPath())) {
8712 allowed = true;
8713 break;
8714 }
8715 }
8716 if (!allowed) {
8717 throw new SecurityException("Provider " + pi.packageName
8718 + "/" + pi.name
8719 + " does not allow granting of permission to path of Uri "
8720 + grantUri);
8721 }
8722 }
8723 }
8724
8725 // Third... does the caller itself have permission to access
8726 // this uri?
8727 final int callingAppId = UserHandle.getAppId(callingUid);
8728 if ((callingAppId == SYSTEM_UID) || (callingAppId == ROOT_UID)) {
8729 if ("com.android.settings.files".equals(grantUri.uri.getAuthority())) {
8730 // Exempted authority for cropping user photos in Settings app
8731 } else {
8732 Slog.w(TAG, "For security reasons, the system cannot issue a Uri permission"
8733 + " grant to " + grantUri + "; use startActivityAsCaller() instead");
8734 return -1;
8735 }
8736 }
8737 if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) {
8738 // Require they hold a strong enough Uri permission
8739 if (!checkUriPermissionLocked(grantUri, callingUid, modeFlags)) {
8740 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(pi.readPermission)) {
8741 throw new SecurityException(
8742 "UID " + callingUid + " does not have permission to " + grantUri
8743 + "; you could obtain access using ACTION_OPEN_DOCUMENT "
8744 + "or related APIs");
8745 } else {
8746 throw new SecurityException(
8747 "UID " + callingUid + " does not have permission to " + grantUri);
8748 }
8749 }
8750 }
8751 return targetUid;
8752 }
8753
8754 /**
8755 * @param uri This uri must NOT contain an embedded userId.
8756 * @param userId The userId in which the uri is to be resolved.
8757 */
8758 @Override
8759 public int checkGrantUriPermission(int callingUid, String targetPkg, Uri uri,
8760 final int modeFlags, int userId) {
8761 enforceNotIsolatedCaller("checkGrantUriPermission");
8762 synchronized(this) {
8763 return checkGrantUriPermissionLocked(callingUid, targetPkg,
8764 new GrantUri(userId, uri, false), modeFlags, -1);
8765 }
8766 }
8767
8768 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg, GrantUri grantUri,
8769 final int modeFlags, UriPermissionOwner owner) {
8770 if (!Intent.isAccessUriMode(modeFlags)) {
8771 return;
8772 }
8773
8774 // So here we are: the caller has the assumed permission
8775 // to the uri, and the target doesn't. Let's now give this to
8776 // the target.
8777
8778 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION,
8779 "Granting " + targetPkg + "/" + targetUid + " permission to " + grantUri);
8780
8781 final String authority = grantUri.uri.getAuthority();
8782 final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId,
8783 MATCH_DEBUG_TRIAGED_MISSING);
8784 if (pi == null) {
8785 Slog.w(TAG, "No content provider found for grant: " + grantUri.toSafeString());
8786 return;
8787 }
8788
8789 if ((modeFlags & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0) {
8790 grantUri.prefix = true;
8791 }
8792 final UriPermission perm = findOrCreateUriPermissionLocked(
8793 pi.packageName, targetPkg, targetUid, grantUri);
8794 perm.grantModes(modeFlags, owner);
8795 }
8796
8797 void grantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri,
8798 final int modeFlags, UriPermissionOwner owner, int targetUserId) {
8799 if (targetPkg == null) {
8800 throw new NullPointerException("targetPkg");
8801 }
8802 int targetUid;
8803 final IPackageManager pm = AppGlobals.getPackageManager();
8804 try {
8805 targetUid = pm.getPackageUid(targetPkg, MATCH_DEBUG_TRIAGED_MISSING, targetUserId);
8806 } catch (RemoteException ex) {
8807 return;
8808 }
8809
8810 targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, modeFlags,
8811 targetUid);
8812 if (targetUid < 0) {
8813 return;
8814 }
8815
8816 grantUriPermissionUncheckedLocked(targetUid, targetPkg, grantUri, modeFlags,
8817 owner);
8818 }
8819
8820 static class NeededUriGrants extends ArrayList<GrantUri> {
8821 final String targetPkg;
8822 final int targetUid;
8823 final int flags;
8824
8825 NeededUriGrants(String targetPkg, int targetUid, int flags) {
8826 this.targetPkg = targetPkg;
8827 this.targetUid = targetUid;
8828 this.flags = flags;
8829 }
8830 }
8831
8832 /**
8833 * Like checkGrantUriPermissionLocked, but takes an Intent.
8834 */
8835 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
8836 String targetPkg, Intent intent, int mode, NeededUriGrants needed, int targetUserId) {
8837 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION,
8838 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
8839 + " clip=" + (intent != null ? intent.getClipData() : null)
8840 + " from " + intent + "; flags=0x"
8841 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
8842
8843 if (targetPkg == null) {
8844 throw new NullPointerException("targetPkg");
8845 }
8846
8847 if (intent == null) {
8848 return null;
8849 }
8850 Uri data = intent.getData();
8851 ClipData clip = intent.getClipData();
8852 if (data == null && clip == null) {
8853 return null;
8854 }
8855 // Default userId for uris in the intent (if they don't specify it themselves)
8856 int contentUserHint = intent.getContentUserHint();
8857 if (contentUserHint == UserHandle.USER_CURRENT) {
8858 contentUserHint = UserHandle.getUserId(callingUid);
8859 }
8860 final IPackageManager pm = AppGlobals.getPackageManager();
8861 int targetUid;
8862 if (needed != null) {
8863 targetUid = needed.targetUid;
8864 } else {
8865 try {
8866 targetUid = pm.getPackageUid(targetPkg, MATCH_DEBUG_TRIAGED_MISSING,
8867 targetUserId);
8868 } catch (RemoteException ex) {
8869 return null;
8870 }
8871 if (targetUid < 0) {
8872 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION,
8873 "Can't grant URI permission no uid for: " + targetPkg
8874 + " on user " + targetUserId);
8875 return null;
8876 }
8877 }
8878 if (data != null) {
8879 GrantUri grantUri = GrantUri.resolve(contentUserHint, data);
8880 targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode,
8881 targetUid);
8882 if (targetUid > 0) {
8883 if (needed == null) {
8884 needed = new NeededUriGrants(targetPkg, targetUid, mode);
8885 }
8886 needed.add(grantUri);
8887 }
8888 }
8889 if (clip != null) {
8890 for (int i=0; i<clip.getItemCount(); i++) {
8891 Uri uri = clip.getItemAt(i).getUri();
8892 if (uri != null) {
8893 GrantUri grantUri = GrantUri.resolve(contentUserHint, uri);
8894 targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode,
8895 targetUid);
8896 if (targetUid > 0) {
8897 if (needed == null) {
8898 needed = new NeededUriGrants(targetPkg, targetUid, mode);
8899 }
8900 needed.add(grantUri);
8901 }
8902 } else {
8903 Intent clipIntent = clip.getItemAt(i).getIntent();
8904 if (clipIntent != null) {
8905 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
8906 callingUid, targetPkg, clipIntent, mode, needed, targetUserId);
8907 if (newNeeded != null) {
8908 needed = newNeeded;
8909 }
8910 }
8911 }
8912 }
8913 }
8914
8915 return needed;
8916 }
8917
8918 /**
8919 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
8920 */
8921 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
8922 UriPermissionOwner owner) {
8923 if (needed != null) {
8924 for (int i=0; i<needed.size(); i++) {
8925 GrantUri grantUri = needed.get(i);
8926 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
8927 grantUri, needed.flags, owner);
8928 }
8929 }
8930 }
8931
8932 void grantUriPermissionFromIntentLocked(int callingUid,
8933 String targetPkg, Intent intent, UriPermissionOwner owner, int targetUserId) {
8934 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
8935 intent, intent != null ? intent.getFlags() : 0, null, targetUserId);
8936 if (needed == null) {
8937 return;
8938 }
8939
8940 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
8941 }
8942
8943 /**
8944 * @param uri This uri must NOT contain an embedded userId.
8945 * @param userId The userId in which the uri is to be resolved.
8946 */
8947 @Override
8948 public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri,
8949 final int modeFlags, int userId) {
8950 enforceNotIsolatedCaller("grantUriPermission");
8951 GrantUri grantUri = new GrantUri(userId, uri, false);
8952 synchronized(this) {
8953 final ProcessRecord r = getRecordForAppLocked(caller);
8954 if (r == null) {
8955 throw new SecurityException("Unable to find app for caller "
8956 + caller
8957 + " when granting permission to uri " + grantUri);
8958 }
8959 if (targetPkg == null) {
8960 throw new IllegalArgumentException("null target");
8961 }
8962 if (grantUri == null) {
8963 throw new IllegalArgumentException("null uri");
8964 }
8965
8966 Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION
8967 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
8968 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
8969 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
8970
8971 grantUriPermissionLocked(r.uid, targetPkg, grantUri, modeFlags, null,
8972 UserHandle.getUserId(r.uid));
8973 }
8974 }
8975
8976 void removeUriPermissionIfNeededLocked(UriPermission perm) {
8977 if (perm.modeFlags == 0) {
8978 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(
8979 perm.targetUid);
8980 if (perms != null) {
8981 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION,
8982 "Removing " + perm.targetUid + " permission to " + perm.uri);
8983
8984 perms.remove(perm.uri);
8985 if (perms.isEmpty()) {
8986 mGrantedUriPermissions.remove(perm.targetUid);
8987 }
8988 }
8989 }
8990 }
8991
8992 private void revokeUriPermissionLocked(String targetPackage, int callingUid, GrantUri grantUri,
8993 final int modeFlags) {
8994 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION,
8995 "Revoking all granted permissions to " + grantUri);
8996
8997 final IPackageManager pm = AppGlobals.getPackageManager();
8998 final String authority = grantUri.uri.getAuthority();
8999 final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId,
9000 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE);
9001 if (pi == null) {
9002 Slog.w(TAG, "No content provider found for permission revoke: "
9003 + grantUri.toSafeString());
9004 return;
9005 }
9006
9007 // Does the caller have this permission on the URI?
9008 if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) {
9009 // If they don't have direct access to the URI, then revoke any
9010 // ownerless URI permissions that have been granted to them.
9011 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
9012 if (perms != null) {
9013 boolean persistChanged = false;
9014 for (int i = perms.size()-1; i >= 0; i--) {
9015 final UriPermission perm = perms.valueAt(i);
9016 if (targetPackage != null && !targetPackage.equals(perm.targetPkg)) {
9017 continue;
9018 }
9019 if (perm.uri.sourceUserId == grantUri.sourceUserId
9020 && perm.uri.uri.isPathPrefixMatch(grantUri.uri)) {
9021 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION,
9022 "Revoking non-owned " + perm.targetUid
9023 + " permission to " + perm.uri);
9024 persistChanged |= perm.revokeModes(
9025 modeFlags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION, false);
9026 if (perm.modeFlags == 0) {
9027 perms.removeAt(i);
9028 }
9029 }
9030 }
9031 if (perms.isEmpty()) {
9032 mGrantedUriPermissions.remove(callingUid);
9033 }
9034 if (persistChanged) {
9035 schedulePersistUriGrants();
9036 }
9037 }
9038 return;
9039 }
9040
9041 boolean persistChanged = false;
9042
9043 // Go through all of the permissions and remove any that match.
9044 for (int i = mGrantedUriPermissions.size()-1; i >= 0; i--) {
9045 final int targetUid = mGrantedUriPermissions.keyAt(i);
9046 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
9047
9048 for (int j = perms.size()-1; j >= 0; j--) {
9049 final UriPermission perm = perms.valueAt(j);
9050 if (targetPackage != null && !targetPackage.equals(perm.targetPkg)) {
9051 continue;
9052 }
9053 if (perm.uri.sourceUserId == grantUri.sourceUserId
9054 && perm.uri.uri.isPathPrefixMatch(grantUri.uri)) {
9055 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION,
9056 "Revoking " + perm.targetUid + " permission to " + perm.uri);
9057 persistChanged |= perm.revokeModes(
9058 modeFlags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION,
9059 targetPackage == null);
9060 if (perm.modeFlags == 0) {
9061 perms.removeAt(j);
9062 }
9063 }
9064 }
9065
9066 if (perms.isEmpty()) {
9067 mGrantedUriPermissions.removeAt(i);
9068 }
9069 }
9070
9071 if (persistChanged) {
9072 schedulePersistUriGrants();
9073 }
9074 }
9075
9076 /**
9077 * @param uri This uri must NOT contain an embedded userId.
9078 * @param userId The userId in which the uri is to be resolved.
9079 */
9080 @Override
9081 public void revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri,
9082 final int modeFlags, int userId) {
9083 enforceNotIsolatedCaller("revokeUriPermission");
9084 synchronized(this) {
9085 final ProcessRecord r = getRecordForAppLocked(caller);
9086 if (r == null) {
9087 throw new SecurityException("Unable to find app for caller "
9088 + caller
9089 + " when revoking permission to uri " + uri);
9090 }
9091 if (uri == null) {
9092 Slog.w(TAG, "revokeUriPermission: null uri");
9093 return;
9094 }
9095
9096 if (!Intent.isAccessUriMode(modeFlags)) {
9097 return;
9098 }
9099
9100 final String authority = uri.getAuthority();
9101 final ProviderInfo pi = getProviderInfoLocked(authority, userId,
9102 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE);
9103 if (pi == null) {
9104 Slog.w(TAG, "No content provider found for permission revoke: "
9105 + uri.toSafeString());
9106 return;
9107 }
9108
9109 revokeUriPermissionLocked(targetPackage, r.uid, new GrantUri(userId, uri, false),
9110 modeFlags);
9111 }
9112 }
9113
9114 /**
9115 * Remove any {@link UriPermission} granted <em>from</em> or <em>to</em> the
9116 * given package.
9117 *
9118 * @param packageName Package name to match, or {@code null} to apply to all
9119 * packages.
9120 * @param userHandle User to match, or {@link UserHandle#USER_ALL} to apply
9121 * to all users.
9122 * @param persistable If persistable grants should be removed.
9123 */
9124 private void removeUriPermissionsForPackageLocked(
9125 String packageName, int userHandle, boolean persistable) {
9126 if (userHandle == UserHandle.USER_ALL && packageName == null) {
9127 throw new IllegalArgumentException("Must narrow by either package or user");
9128 }
9129
9130 boolean persistChanged = false;
9131
9132 int N = mGrantedUriPermissions.size();
9133 for (int i = 0; i < N; i++) {
9134 final int targetUid = mGrantedUriPermissions.keyAt(i);
9135 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
9136
9137 // Only inspect grants matching user
9138 if (userHandle == UserHandle.USER_ALL
9139 || userHandle == UserHandle.getUserId(targetUid)) {
9140 for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) {
9141 final UriPermission perm = it.next();
9142
9143 // Only inspect grants matching package
9144 if (packageName == null || perm.sourcePkg.equals(packageName)
9145 || perm.targetPkg.equals(packageName)) {
9146 // Hacky solution as part of fixing a security bug; ignore
9147 // grants associated with DownloadManager so we don't have
9148 // to immediately launch it to regrant the permissions
9149 if (Downloads.Impl.AUTHORITY.equals(perm.uri.uri.getAuthority())
9150 && !persistable) continue;
9151
9152 persistChanged |= perm.revokeModes(persistable
9153 ? ~0 : ~Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION, true);
9154
9155 // Only remove when no modes remain; any persisted grants
9156 // will keep this alive.
9157 if (perm.modeFlags == 0) {
9158 it.remove();
9159 }
9160 }
9161 }
9162
9163 if (perms.isEmpty()) {
9164 mGrantedUriPermissions.remove(targetUid);
9165 N--;
9166 i--;
9167 }
9168 }
9169 }
9170
9171 if (persistChanged) {
9172 schedulePersistUriGrants();
9173 }
9174 }
9175
9176 @Override
9177 public IBinder newUriPermissionOwner(String name) {
9178 enforceNotIsolatedCaller("newUriPermissionOwner");
9179 synchronized(this) {
9180 UriPermissionOwner owner = new UriPermissionOwner(this, name);
9181 return owner.getExternalTokenLocked();
9182 }
9183 }
9184
9185 @Override
9186 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
9187 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
9188 synchronized(this) {
9189 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
9190 if (r == null) {
9191 throw new IllegalArgumentException("Activity does not exist; token="
9192 + activityToken);
9193 }
9194 return r.getUriPermissionsLocked().getExternalTokenLocked();
9195 }
9196 }
9197 /**
9198 * @param uri This uri must NOT contain an embedded userId.
9199 * @param sourceUserId The userId in which the uri is to be resolved.
9200 * @param targetUserId The userId of the app that receives the grant.
9201 */
9202 @Override
9203 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg, Uri uri,
9204 final int modeFlags, int sourceUserId, int targetUserId) {
9205 targetUserId = mUserController.handleIncomingUser(Binder.getCallingPid(),
9206 Binder.getCallingUid(), targetUserId, false, ALLOW_FULL_ONLY,
9207 "grantUriPermissionFromOwner", null);
9208 synchronized(this) {
9209 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
9210 if (owner == null) {
9211 throw new IllegalArgumentException("Unknown owner: " + token);
9212 }
9213 if (fromUid != Binder.getCallingUid()) {
9214 if (Binder.getCallingUid() != myUid()) {
9215 // Only system code can grant URI permissions on behalf
9216 // of other users.
9217 throw new SecurityException("nice try");
9218 }
9219 }
9220 if (targetPkg == null) {
9221 throw new IllegalArgumentException("null target");
9222 }
9223 if (uri == null) {
9224 throw new IllegalArgumentException("null uri");
9225 }
9226
9227 grantUriPermissionLocked(fromUid, targetPkg, new GrantUri(sourceUserId, uri, false),
9228 modeFlags, owner, targetUserId);
9229 }
9230 }
9231
9232 /**
9233 * @param uri This uri must NOT contain an embedded userId.
9234 * @param userId The userId in which the uri is to be resolved.
9235 */
9236 @Override
9237 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode, int userId) {
9238 synchronized(this) {
9239 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
9240 if (owner == null) {
9241 throw new IllegalArgumentException("Unknown owner: " + token);
9242 }
9243
9244 if (uri == null) {
9245 owner.removeUriPermissionsLocked(mode);
9246 } else {
9247 final boolean prefix = (mode & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0;
9248 owner.removeUriPermissionLocked(new GrantUri(userId, uri, prefix), mode);
9249 }
9250 }
9251 }
9252
9253 private void schedulePersistUriGrants() {
9254 if (!mHandler.hasMessages(PERSIST_URI_GRANTS_MSG)) {
9255 mHandler.sendMessageDelayed(mHandler.obtainMessage(PERSIST_URI_GRANTS_MSG),
9256 10 * DateUtils.SECOND_IN_MILLIS);
9257 }
9258 }
9259
9260 private void writeGrantedUriPermissions() {
9261 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, "writeGrantedUriPermissions()");
9262
9263 // Snapshot permissions so we can persist without lock
9264 ArrayList<UriPermission.Snapshot> persist = Lists.newArrayList();
9265 synchronized (this) {
9266 final int size = mGrantedUriPermissions.size();
9267 for (int i = 0; i < size; i++) {
9268 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
9269 for (UriPermission perm : perms.values()) {
9270 if (perm.persistedModeFlags != 0) {
9271 persist.add(perm.snapshot());
9272 }
9273 }
9274 }
9275 }
9276
9277 FileOutputStream fos = null;
9278 try {
9279 fos = mGrantFile.startWrite();
9280
9281 XmlSerializer out = new FastXmlSerializer();
9282 out.setOutput(fos, StandardCharsets.UTF_8.name());
9283 out.startDocument(null, true);
9284 out.startTag(null, TAG_URI_GRANTS);
9285 for (UriPermission.Snapshot perm : persist) {
9286 out.startTag(null, TAG_URI_GRANT);
9287 writeIntAttribute(out, ATTR_SOURCE_USER_ID, perm.uri.sourceUserId);
9288 writeIntAttribute(out, ATTR_TARGET_USER_ID, perm.targetUserId);
9289 out.attribute(null, ATTR_SOURCE_PKG, perm.sourcePkg);
9290 out.attribute(null, ATTR_TARGET_PKG, perm.targetPkg);
9291 out.attribute(null, ATTR_URI, String.valueOf(perm.uri.uri));
9292 writeBooleanAttribute(out, ATTR_PREFIX, perm.uri.prefix);
9293 writeIntAttribute(out, ATTR_MODE_FLAGS, perm.persistedModeFlags);
9294 writeLongAttribute(out, ATTR_CREATED_TIME, perm.persistedCreateTime);
9295 out.endTag(null, TAG_URI_GRANT);
9296 }
9297 out.endTag(null, TAG_URI_GRANTS);
9298 out.endDocument();
9299
9300 mGrantFile.finishWrite(fos);
9301 } catch (IOException e) {
9302 if (fos != null) {
9303 mGrantFile.failWrite(fos);
9304 }
9305 }
9306 }
9307
9308 private void readGrantedUriPermissionsLocked() {
9309 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, "readGrantedUriPermissions()");
9310
9311 final long now = System.currentTimeMillis();
9312
9313 FileInputStream fis = null;
9314 try {
9315 fis = mGrantFile.openRead();
9316 final XmlPullParser in = Xml.newPullParser();
9317 in.setInput(fis, StandardCharsets.UTF_8.name());
9318
9319 int type;
9320 while ((type = in.next()) != END_DOCUMENT) {
9321 final String tag = in.getName();
9322 if (type == START_TAG) {
9323 if (TAG_URI_GRANT.equals(tag)) {
9324 final int sourceUserId;
9325 final int targetUserId;
9326 final int userHandle = readIntAttribute(in,
9327 ATTR_USER_HANDLE, UserHandle.USER_NULL);
9328 if (userHandle != UserHandle.USER_NULL) {
9329 // For backwards compatibility.
9330 sourceUserId = userHandle;
9331 targetUserId = userHandle;
9332 } else {
9333 sourceUserId = readIntAttribute(in, ATTR_SOURCE_USER_ID);
9334 targetUserId = readIntAttribute(in, ATTR_TARGET_USER_ID);
9335 }
9336 final String sourcePkg = in.getAttributeValue(null, ATTR_SOURCE_PKG);
9337 final String targetPkg = in.getAttributeValue(null, ATTR_TARGET_PKG);
9338 final Uri uri = Uri.parse(in.getAttributeValue(null, ATTR_URI));
9339 final boolean prefix = readBooleanAttribute(in, ATTR_PREFIX);
9340 final int modeFlags = readIntAttribute(in, ATTR_MODE_FLAGS);
9341 final long createdTime = readLongAttribute(in, ATTR_CREATED_TIME, now);
9342
9343 // Sanity check that provider still belongs to source package
9344 // Both direct boot aware and unaware packages are fine as we
9345 // will do filtering at query time to avoid multiple parsing.
9346 final ProviderInfo pi = getProviderInfoLocked(
9347 uri.getAuthority(), sourceUserId, MATCH_DIRECT_BOOT_AWARE
9348 | MATCH_DIRECT_BOOT_UNAWARE);
9349 if (pi != null && sourcePkg.equals(pi.packageName)) {
9350 int targetUid = -1;
9351 try {
9352 targetUid = AppGlobals.getPackageManager().getPackageUid(
9353 targetPkg, MATCH_UNINSTALLED_PACKAGES, targetUserId);
9354 } catch (RemoteException e) {
9355 }
9356 if (targetUid != -1) {
9357 final UriPermission perm = findOrCreateUriPermissionLocked(
9358 sourcePkg, targetPkg, targetUid,
9359 new GrantUri(sourceUserId, uri, prefix));
9360 perm.initPersistedModes(modeFlags, createdTime);
9361 }
9362 } else {
9363 Slog.w(TAG, "Persisted grant for " + uri + " had source " + sourcePkg
9364 + " but instead found " + pi);
9365 }
9366 }
9367 }
9368 }
9369 } catch (FileNotFoundException e) {
9370 // Missing grants is okay
9371 } catch (IOException e) {
9372 Slog.wtf(TAG, "Failed reading Uri grants", e);
9373 } catch (XmlPullParserException e) {
9374 Slog.wtf(TAG, "Failed reading Uri grants", e);
9375 } finally {
9376 IoUtils.closeQuietly(fis);
9377 }
9378 }
9379
9380 /**
9381 * @param uri This uri must NOT contain an embedded userId.
9382 * @param userId The userId in which the uri is to be resolved.
9383 */
9384 @Override
9385 public void takePersistableUriPermission(Uri uri, final int modeFlags, int userId) {
9386 enforceNotIsolatedCaller("takePersistableUriPermission");
9387
9388 Preconditions.checkFlagsArgument(modeFlags,
9389 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
9390
9391 synchronized (this) {
9392 final int callingUid = Binder.getCallingUid();
9393 boolean persistChanged = false;
9394 GrantUri grantUri = new GrantUri(userId, uri, false);
9395
9396 UriPermission exactPerm = findUriPermissionLocked(callingUid,
9397 new GrantUri(userId, uri, false));
9398 UriPermission prefixPerm = findUriPermissionLocked(callingUid,
9399 new GrantUri(userId, uri, true));
9400
9401 final boolean exactValid = (exactPerm != null)
9402 && ((modeFlags & exactPerm.persistableModeFlags) == modeFlags);
9403 final boolean prefixValid = (prefixPerm != null)
9404 && ((modeFlags & prefixPerm.persistableModeFlags) == modeFlags);
9405
9406 if (!(exactValid || prefixValid)) {
9407 throw new SecurityException("No persistable permission grants found for UID "
9408 + callingUid + " and Uri " + grantUri.toSafeString());
9409 }
9410
9411 if (exactValid) {
9412 persistChanged |= exactPerm.takePersistableModes(modeFlags);
9413 }
9414 if (prefixValid) {
9415 persistChanged |= prefixPerm.takePersistableModes(modeFlags);
9416 }
9417
9418 persistChanged |= maybePrunePersistedUriGrantsLocked(callingUid);
9419
9420 if (persistChanged) {
9421 schedulePersistUriGrants();
9422 }
9423 }
9424 }
9425
9426 /**
9427 * @param uri This uri must NOT contain an embedded userId.
9428 * @param userId The userId in which the uri is to be resolved.
9429 */
9430 @Override
9431 public void releasePersistableUriPermission(Uri uri, final int modeFlags, int userId) {
9432 enforceNotIsolatedCaller("releasePersistableUriPermission");
9433
9434 Preconditions.checkFlagsArgument(modeFlags,
9435 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
9436
9437 synchronized (this) {
9438 final int callingUid = Binder.getCallingUid();
9439 boolean persistChanged = false;
9440
9441 UriPermission exactPerm = findUriPermissionLocked(callingUid,
9442 new GrantUri(userId, uri, false));
9443 UriPermission prefixPerm = findUriPermissionLocked(callingUid,
9444 new GrantUri(userId, uri, true));
9445 if (exactPerm == null && prefixPerm == null) {
9446 throw new SecurityException("No permission grants found for UID " + callingUid
9447 + " and Uri " + uri.toSafeString());
9448 }
9449
9450 if (exactPerm != null) {
9451 persistChanged |= exactPerm.releasePersistableModes(modeFlags);
9452 removeUriPermissionIfNeededLocked(exactPerm);
9453 }
9454 if (prefixPerm != null) {
9455 persistChanged |= prefixPerm.releasePersistableModes(modeFlags);
9456 removeUriPermissionIfNeededLocked(prefixPerm);
9457 }
9458
9459 if (persistChanged) {
9460 schedulePersistUriGrants();
9461 }
9462 }
9463 }
9464
9465 /**
9466 * Prune any older {@link UriPermission} for the given UID until outstanding
9467 * persisted grants are below {@link #MAX_PERSISTED_URI_GRANTS}.
9468 *
9469 * @return if any mutations occured that require persisting.
9470 */
9471 private boolean maybePrunePersistedUriGrantsLocked(int uid) {
9472 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid);
9473 if (perms == null) return false;
9474 if (perms.size() < MAX_PERSISTED_URI_GRANTS) return false;
9475
9476 final ArrayList<UriPermission> persisted = Lists.newArrayList();
9477 for (UriPermission perm : perms.values()) {
9478 if (perm.persistedModeFlags != 0) {
9479 persisted.add(perm);
9480 }
9481 }
9482
9483 final int trimCount = persisted.size() - MAX_PERSISTED_URI_GRANTS;
9484 if (trimCount <= 0) return false;
9485
9486 Collections.sort(persisted, new UriPermission.PersistedTimeComparator());
9487 for (int i = 0; i < trimCount; i++) {
9488 final UriPermission perm = persisted.get(i);
9489
9490 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION,
9491 "Trimming grant created at " + perm.persistedCreateTime);
9492
9493 perm.releasePersistableModes(~0);
9494 removeUriPermissionIfNeededLocked(perm);
9495 }
9496
9497 return true;
9498 }
9499
9500 @Override
9501 public ParceledListSlice<android.content.UriPermission> getPersistedUriPermissions(
9502 String packageName, boolean incoming) {
9503 enforceNotIsolatedCaller("getPersistedUriPermissions");
9504 Preconditions.checkNotNull(packageName, "packageName");
9505
9506 final int callingUid = Binder.getCallingUid();
9507 final int callingUserId = UserHandle.getUserId(callingUid);
9508 final IPackageManager pm = AppGlobals.getPackageManager();
9509 try {
9510 final int packageUid = pm.getPackageUid(packageName,
9511 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, callingUserId);
9512 if (packageUid != callingUid) {
9513 throw new SecurityException(
9514 "Package " + packageName + " does not belong to calling UID " + callingUid);
9515 }
9516 } catch (RemoteException e) {
9517 throw new SecurityException("Failed to verify package name ownership");
9518 }
9519
9520 final ArrayList<android.content.UriPermission> result = Lists.newArrayList();
9521 synchronized (this) {
9522 if (incoming) {
9523 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(
9524 callingUid);
9525 if (perms == null) {
9526 Slog.w(TAG, "No permission grants found for " + packageName);
9527 } else {
9528 for (UriPermission perm : perms.values()) {
9529 if (packageName.equals(perm.targetPkg) && perm.persistedModeFlags != 0) {
9530 result.add(perm.buildPersistedPublicApiObject());
9531 }
9532 }
9533 }
9534 } else {
9535 final int size = mGrantedUriPermissions.size();
9536 for (int i = 0; i < size; i++) {
9537 final ArrayMap<GrantUri, UriPermission> perms =
9538 mGrantedUriPermissions.valueAt(i);
9539 for (UriPermission perm : perms.values()) {
9540 if (packageName.equals(perm.sourcePkg) && perm.persistedModeFlags != 0) {
9541 result.add(perm.buildPersistedPublicApiObject());
9542 }
9543 }
9544 }
9545 }
9546 }
9547 return new ParceledListSlice<android.content.UriPermission>(result);
9548 }
9549
9550 @Override
9551 public ParceledListSlice<android.content.UriPermission> getGrantedUriPermissions(
9552 String packageName, int userId) {
9553 enforceCallingPermission(android.Manifest.permission.GET_APP_GRANTED_URI_PERMISSIONS,
9554 "getGrantedUriPermissions");
9555
9556 final ArrayList<android.content.UriPermission> result = Lists.newArrayList();
9557 synchronized (this) {
9558 final int size = mGrantedUriPermissions.size();
9559 for (int i = 0; i < size; i++) {
9560 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
9561 for (UriPermission perm : perms.values()) {
9562 if (packageName.equals(perm.targetPkg) && perm.targetUserId == userId
9563 && perm.persistedModeFlags != 0) {
9564 result.add(perm.buildPersistedPublicApiObject());
9565 }
9566 }
9567 }
9568 }
9569 return new ParceledListSlice<android.content.UriPermission>(result);
9570 }
9571
9572 @Override
9573 public void clearGrantedUriPermissions(String packageName, int userId) {
9574 enforceCallingPermission(android.Manifest.permission.CLEAR_APP_GRANTED_URI_PERMISSIONS,
9575 "clearGrantedUriPermissions");
9576 removeUriPermissionsForPackageLocked(packageName, userId, true);
9577 }
9578

显示等待debug

 9579    @Override
9580 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
9581 synchronized (this) {
9582 ProcessRecord app =
9583 who != null ? getRecordForAppLocked(who) : null;
9584 if (app == null) return;
9585
9586 Message msg = Message.obtain();
9587 msg.what = WAIT_FOR_DEBUGGER_UI_MSG;
9588 msg.obj = app;
9589 msg.arg1 = waiting ? 1 : 0;
9590 mUiHandler.sendMessage(msg);
9591 }
9592 }

获取mem info

 9594    @Override
9595 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
9596 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
9597 final long cachedAppMem = mProcessList.getMemLevel(ProcessList.CACHED_APP_MIN_ADJ);
9598 outInfo.availMem = getFreeMemory();
9599 outInfo.totalMem = getTotalMemory();
9600 outInfo.threshold = homeAppMem;
9601 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((cachedAppMem-homeAppMem)/2));
9602 outInfo.hiddenAppThreshold = cachedAppMem;
9603 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
9604 ProcessList.SERVICE_ADJ);
9605 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
9606 ProcessList.VISIBLE_APP_ADJ);
9607 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
9608 ProcessList.FOREGROUND_APP_ADJ);
9609 }

app task stack相关

 9611    // =========================================================
9612 // TASK MANAGEMENT
9613 // =========================================================
9614
9615 @Override
9616 public List<IBinder> getAppTasks(String callingPackage) {
9617 int callingUid = Binder.getCallingUid();
9618 long ident = Binder.clearCallingIdentity();
9619
9620 synchronized(this) {
9621 ArrayList<IBinder> list = new ArrayList<IBinder>();
9622 try {
9623 if (DEBUG_ALL) Slog.v(TAG, "getAppTasks");
9624
9625 final int N = mRecentTasks.size();
9626 for (int i = 0; i < N; i++) {
9627 TaskRecord tr = mRecentTasks.get(i);
9628 // Skip tasks that do not match the caller. We don't need to verify
9629 // callingPackage, because we are also limiting to callingUid and know
9630 // that will limit to the correct security sandbox.
9631 if (tr.effectiveUid != callingUid) {
9632 continue;
9633 }
9634 Intent intent = tr.getBaseIntent();
9635 if (intent == null ||
9636 !callingPackage.equals(intent.getComponent().getPackageName())) {
9637 continue;
9638 }
9639 ActivityManager.RecentTaskInfo taskInfo =
9640 createRecentTaskInfoFromTaskRecord(tr);
9641 AppTaskImpl taskImpl = new AppTaskImpl(taskInfo.persistentId, callingUid);
9642 list.add(taskImpl.asBinder());
9643 }
9644 } finally {
9645 Binder.restoreCallingIdentity(ident);
9646 }
9647 return list;
9648 }
9649 }
9650
9651 @Override
9652 public List<RunningTaskInfo> getTasks(int maxNum, int flags) {
9653 final int callingUid = Binder.getCallingUid();
9654 ArrayList<RunningTaskInfo> list = new ArrayList<RunningTaskInfo>();
9655
9656 synchronized(this) {
9657 if (DEBUG_ALL) Slog.v(
9658 TAG, "getTasks: max=" + maxNum + ", flags=" + flags);
9659
9660 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
9661 callingUid);
9662
9663 // TODO: Improve with MRU list from all ActivityStacks.
9664 mStackSupervisor.getTasksLocked(maxNum, list, callingUid, allowed);
9665 }
9666
9667 return list;
9668 }
9669
9670 /**
9671 * Creates a new RecentTaskInfo from a TaskRecord.
9672 */
9673 private ActivityManager.RecentTaskInfo createRecentTaskInfoFromTaskRecord(TaskRecord tr) {
9674 // Update the task description to reflect any changes in the task stack
9675 tr.updateTaskDescription();
9676
9677 // Compose the recent task info
9678 ActivityManager.RecentTaskInfo rti = new ActivityManager.RecentTaskInfo();
9679 rti.id = tr.getTopActivity() == null ? INVALID_TASK_ID : tr.taskId;
9680 rti.persistentId = tr.taskId;
9681 rti.baseIntent = new Intent(tr.getBaseIntent());
9682 rti.origActivity = tr.origActivity;
9683 rti.realActivity = tr.realActivity;
9684 rti.description = tr.lastDescription;
9685 rti.stackId = tr.getStackId();
9686 rti.userId = tr.userId;
9687 rti.taskDescription = new ActivityManager.TaskDescription(tr.lastTaskDescription);
9688 rti.firstActiveTime = tr.firstActiveTime;
9689 rti.lastActiveTime = tr.lastActiveTime;
9690 rti.affiliatedTaskId = tr.mAffiliatedTaskId;
9691 rti.affiliatedTaskColor = tr.mAffiliatedTaskColor;
9692 rti.numActivities = 0;
9693 if (tr.mBounds != null) {
9694 rti.bounds = new Rect(tr.mBounds);
9695 }
9696 rti.supportsSplitScreenMultiWindow = tr.supportsSplitScreen();
9697 rti.resizeMode = tr.mResizeMode;
9698
9699 ActivityRecord base = null;
9700 ActivityRecord top = null;
9701 ActivityRecord tmp;
9702
9703 for (int i = tr.mActivities.size() - 1; i >= 0; --i) {
9704 tmp = tr.mActivities.get(i);
9705 if (tmp.finishing) {
9706 continue;
9707 }
9708 base = tmp;
9709 if (top == null || (top.state == ActivityState.INITIALIZING)) {
9710 top = base;
9711 }
9712 rti.numActivities++;
9713 }
9714
9715 rti.baseActivity = (base != null) ? base.intent.getComponent() : null;
9716 rti.topActivity = (top != null) ? top.intent.getComponent() : null;
9717
9718 return rti;
9719 }
9720
9721 private boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
9722 boolean allowed = checkPermission(android.Manifest.permission.REAL_GET_TASKS,
9723 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
9724 if (!allowed) {
9725 if (checkPermission(android.Manifest.permission.GET_TASKS,
9726 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
9727 // Temporary compatibility: some existing apps on the system image may
9728 // still be requesting the old permission and not switched to the new
9729 // one; if so, we'll still allow them full access. This means we need
9730 // to see if they are holding the old permission and are a system app.
9731 try {
9732 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
9733 allowed = true;
9734 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
9735 + " is using old GET_TASKS but privileged; allowing");
9736 }
9737 } catch (RemoteException e) {
9738 }
9739 }
9740 }
9741 if (!allowed) {
9742 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
9743 + " does not hold REAL_GET_TASKS; limiting output");
9744 }
9745 return allowed;
9746 }
9747
9748 @Override
9749 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
9750 int userId) {
9751 final int callingUid = Binder.getCallingUid();
9752 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
9753 false, ALLOW_FULL_ONLY, "getRecentTasks", null);
9754
9755 final boolean includeProfiles = (flags & ActivityManager.RECENT_INCLUDE_PROFILES) != 0;
9756 final boolean withExcluded = (flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0;
9757 synchronized (this) {
9758 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
9759 callingUid);
9760 final boolean detailed = checkCallingPermission(
9761 android.Manifest.permission.GET_DETAILED_TASKS)
9762 == PackageManager.PERMISSION_GRANTED;
9763
9764 if (!isUserRunning(userId, ActivityManager.FLAG_AND_UNLOCKED)) {
9765 Slog.i(TAG, "user " + userId + " is still locked. Cannot load recents");
9766 return ParceledListSlice.emptyList();
9767 }
9768 mRecentTasks.loadUserRecentsLocked(userId);
9769
9770 final int recentsCount = mRecentTasks.size();
9771 ArrayList<ActivityManager.RecentTaskInfo> res =
9772 new ArrayList<>(maxNum < recentsCount ? maxNum : recentsCount);
9773
9774 final Set<Integer> includedUsers;
9775 if (includeProfiles) {
9776 includedUsers = mUserController.getProfileIds(userId);
9777 } else {
9778 includedUsers = new HashSet<>();
9779 }
9780 includedUsers.add(Integer.valueOf(userId));
9781
9782 for (int i = 0; i < recentsCount && maxNum > 0; i++) {
9783 TaskRecord tr = mRecentTasks.get(i);
9784 // Only add calling user or related users recent tasks
9785 if (!includedUsers.contains(Integer.valueOf(tr.userId))) {
9786 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not user: " + tr);
9787 continue;
9788 }
9789
9790 if (tr.realActivitySuspended) {
9791 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, activity suspended: " + tr);
9792 continue;
9793 }
9794
9795 // Return the entry if desired by the caller. We always return
9796 // the first entry, because callers always expect this to be the
9797 // foreground app. We may filter others if the caller has
9798 // not supplied RECENT_WITH_EXCLUDED and there is some reason
9799 // we should exclude the entry.
9800
9801 if (i == 0
9802 || withExcluded
9803 || (tr.intent == null)
9804 || ((tr.intent.getFlags() & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
9805 == 0)) {
9806 if (!allowed) {
9807 // If the caller doesn't have the GET_TASKS permission, then only
9808 // allow them to see a small subset of tasks -- their own and home.
9809 if (!tr.isHomeTask() && tr.effectiveUid != callingUid) {
9810 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not allowed: " + tr);
9811 continue;
9812 }
9813 }
9814 final ActivityStack stack = tr.getStack();
9815 if ((flags & ActivityManager.RECENT_IGNORE_HOME_AND_RECENTS_STACK_TASKS) != 0) {
9816 if (stack != null && stack.isHomeOrRecentsStack()) {
9817 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
9818 "Skipping, home or recents stack task: " + tr);
9819 continue;
9820 }
9821 }
9822 if ((flags & ActivityManager.RECENT_INGORE_DOCKED_STACK_TOP_TASK) != 0) {
9823 if (stack != null && stack.isDockedStack() && stack.topTask() == tr) {
9824 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
9825 "Skipping, top task in docked stack: " + tr);
9826 continue;
9827 }
9828 }
9829 if ((flags & ActivityManager.RECENT_INGORE_PINNED_STACK_TASKS) != 0) {
9830 if (stack != null && stack.isPinnedStack()) {
9831 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
9832 "Skipping, pinned stack task: " + tr);
9833 continue;
9834 }
9835 }
9836 if (tr.autoRemoveRecents && tr.getTopActivity() == null) {
9837 // Don't include auto remove tasks that are finished or finishing.
9838 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
9839 "Skipping, auto-remove without activity: " + tr);
9840 continue;
9841 }
9842 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0
9843 && !tr.isAvailable) {
9844 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
9845 "Skipping, unavail real act: " + tr);
9846 continue;
9847 }
9848
9849 if (!tr.mUserSetupComplete) {
9850 // Don't include task launched while user is not done setting-up.
9851 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
9852 "Skipping, user setup not complete: " + tr);
9853 continue;
9854 }
9855
9856 ActivityManager.RecentTaskInfo rti = createRecentTaskInfoFromTaskRecord(tr);
9857 if (!detailed) {
9858 rti.baseIntent.replaceExtras((Bundle)null);
9859 }
9860
9861 res.add(rti);
9862 maxNum--;
9863 }
9864 }
9865 return new ParceledListSlice<>(res);
9866 }
9867 }
9868
9869 @Override
9870 public ActivityManager.TaskThumbnail getTaskThumbnail(int id) {
9871 synchronized (this) {
9872 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
9873 "getTaskThumbnail()");
9874 final TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(
9875 id, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS, INVALID_STACK_ID);
9876 if (tr != null) {
9877 return tr.getTaskThumbnailLocked();
9878 }
9879 }
9880 return null;
9881 }
9882
9883 @Override
9884 public ActivityManager.TaskDescription getTaskDescription(int id) {
9885 synchronized (this) {
9886 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
9887 "getTaskDescription()");
9888 final TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(id,
9889 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS, INVALID_STACK_ID);
9890 if (tr != null) {
9891 return tr.lastTaskDescription;
9892 }
9893 }
9894 return null;
9895 }
9896
9897 @Override
9898 public int addAppTask(IBinder activityToken, Intent intent,
9899 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
9900 final int callingUid = Binder.getCallingUid();
9901 final long callingIdent = Binder.clearCallingIdentity();
9902
9903 try {
9904 synchronized (this) {
9905 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
9906 if (r == null) {
9907 throw new IllegalArgumentException("Activity does not exist; token="
9908 + activityToken);
9909 }
9910 ComponentName comp = intent.getComponent();
9911 if (comp == null) {
9912 throw new IllegalArgumentException("Intent " + intent
9913 + " must specify explicit component");
9914 }
9915 if (thumbnail.getWidth() != mThumbnailWidth
9916 || thumbnail.getHeight() != mThumbnailHeight) {
9917 throw new IllegalArgumentException("Bad thumbnail size: got "
9918 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
9919 + mThumbnailWidth + "x" + mThumbnailHeight);
9920 }
9921 if (intent.getSelector() != null) {
9922 intent.setSelector(null);
9923 }
9924 if (intent.getSourceBounds() != null) {
9925 intent.setSourceBounds(null);
9926 }
9927 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
9928 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
9929 // The caller has added this as an auto-remove task... that makes no
9930 // sense, so turn off auto-remove.
9931 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
9932 }
9933 }
9934 if (!comp.equals(mLastAddedTaskComponent) || callingUid != mLastAddedTaskUid) {
9935 mLastAddedTaskActivity = null;
9936 }
9937 ActivityInfo ainfo = mLastAddedTaskActivity;
9938 if (ainfo == null) {
9939 ainfo = mLastAddedTaskActivity = AppGlobals.getPackageManager().getActivityInfo(
9940 comp, 0, UserHandle.getUserId(callingUid));
9941 if (ainfo.applicationInfo.uid != callingUid) {
9942 throw new SecurityException(
9943 "Can't add task for another application: target uid="
9944 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
9945 }
9946 }
9947
9948 TaskRecord task = new TaskRecord(this,
9949 mStackSupervisor.getNextTaskIdForUserLocked(r.userId),
9950 ainfo, intent, description, new TaskThumbnailInfo());
9951
9952 int trimIdx = mRecentTasks.trimForTaskLocked(task, false);
9953 if (trimIdx >= 0) {
9954 // If this would have caused a trim, then we'll abort because that
9955 // means it would be added at the end of the list but then just removed.
9956 return INVALID_TASK_ID;
9957 }
9958
9959 final int N = mRecentTasks.size();
9960 if (N >= (ActivityManager.getMaxRecentTasksStatic()-1)) {
9961 final TaskRecord tr = mRecentTasks.remove(N - 1);
9962 tr.removedFromRecents();
9963 }
9964
9965 task.inRecents = true;
9966 mRecentTasks.add(task);
9967 r.getStack().addTask(task, false, "addAppTask");
9968
9969 task.setLastThumbnailLocked(thumbnail);
9970 task.freeLastThumbnail();
9971 return task.taskId;
9972 }
9973 } finally {
9974 Binder.restoreCallingIdentity(callingIdent);
9975 }
9976 }
9977
9978 @Override
9979 public Point getAppTaskThumbnailSize() {
9980 synchronized (this) {
9981 return new Point(mThumbnailWidth, mThumbnailHeight);
9982 }
9983 }
9984
9985 @Override
9986 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
9987 synchronized (this) {
9988 ActivityRecord r = ActivityRecord.isInStackLocked(token);
9989 if (r != null) {
9990 r.setTaskDescription(td);
9991 final TaskRecord task = r.getTask();
9992 task.updateTaskDescription();
9993 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
9994 }
9995 }
9996 }
9997
9998 @Override
9999 public void setTaskResizeable(int taskId, int resizeableMode) {
10000 synchronized (this) {
10001 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(
10002 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS, INVALID_STACK_ID);
10003 if (task == null) {
10004 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
10005 return;
10006 }
10007 task.setResizeMode(resizeableMode);
10008 }
10009 }
10010
10011 @Override
10012 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
10013 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
10014 long ident = Binder.clearCallingIdentity();
10015 try {
10016 synchronized (this) {
10017 TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
10018 if (task == null) {
10019 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
10020 return;
10021 }
10022 // Place the task in the right stack if it isn't there already based on
10023 // the requested bounds.
10024 // The stack transition logic is:
10025 // - a null bounds on a freeform task moves that task to fullscreen
10026 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
10027 // that task to freeform
10028 // - otherwise the task is not moved
10029 int stackId = task.getStackId();
10030 if (!StackId.isTaskResizeAllowed(stackId)) {
10031 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
10032 }
10033 if (bounds == null && stackId == FREEFORM_WORKSPACE_STACK_ID) {
10034 stackId = FULLSCREEN_WORKSPACE_STACK_ID;
10035 } else if (bounds != null && stackId != FREEFORM_WORKSPACE_STACK_ID ) {
10036 stackId = FREEFORM_WORKSPACE_STACK_ID;
10037 }
10038
10039 // Reparent the task to the right stack if necessary
10040 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
10041 if (stackId != task.getStackId()) {
10042 // Defer resume until the task is resized below
10043 task.reparent(stackId, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
10044 DEFER_RESUME, "resizeTask");
10045 preserveWindow = false;
10046 }
10047
10048 // After reparenting (which only resizes the task to the stack bounds), resize the
10049 // task to the actual bounds provided
10050 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
10051 }
10052 } finally {
10053 Binder.restoreCallingIdentity(ident);
10054 }
10055 }
10056
10057 @Override
10058 public Rect getTaskBounds(int taskId) {
10059 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
10060 long ident = Binder.clearCallingIdentity();
10061 Rect rect = new Rect();
10062 try {
10063 synchronized (this) {
10064 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
10065 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS, INVALID_STACK_ID);
10066 if (task == null) {
10067 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
10068 return rect;
10069 }
10070 if (task.getStack() != null) {
10071 // Return the bounds from window manager since it will be adjusted for various
10072 // things like the presense of a docked stack for tasks that aren't resizeable.
10073 task.getWindowContainerBounds(rect);
10074 } else {
10075 // Task isn't in window manager yet since it isn't associated with a stack.
10076 // Return the persist value from activity manager
10077 if (task.mBounds != null) {
10078 rect.set(task.mBounds);
10079 } else if (task.mLastNonFullscreenBounds != null) {
10080 rect.set(task.mLastNonFullscreenBounds);
10081 }
10082 }
10083 }
10084 } finally {
10085 Binder.restoreCallingIdentity(ident);
10086 }
10087 return rect;
10088 }
10089
10090 @Override
10091 public void cancelTaskWindowTransition(int taskId) {
10092 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "cancelTaskWindowTransition()");
10093 final long ident = Binder.clearCallingIdentity();
10094 try {
10095 synchronized (this) {
10096 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
10097 MATCH_TASK_IN_STACKS_ONLY, INVALID_STACK_ID);
10098 if (task == null) {
10099 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
10100 return;
10101 }
10102 task.cancelWindowTransition();
10103 }
10104 } finally {
10105 Binder.restoreCallingIdentity(ident);
10106 }
10107 }
10108
10109 @Override
10110 public void cancelTaskThumbnailTransition(int taskId) {
10111 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "cancelTaskThumbnailTransition()");
10112 final long ident = Binder.clearCallingIdentity();
10113 try {
10114 synchronized (this) {
10115 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
10116 MATCH_TASK_IN_STACKS_ONLY, INVALID_STACK_ID);
10117 if (task == null) {
10118 Slog.w(TAG, "cancelTaskThumbnailTransition: taskId=" + taskId + " not found");
10119 return;
10120 }
10121 task.cancelThumbnailTransition();
10122 }
10123 } finally {
10124 Binder.restoreCallingIdentity(ident);
10125 }
10126 }
10127
10128 @Override
10129 public TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
10130 enforceCallingPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
10131 final long ident = Binder.clearCallingIdentity();
10132 try {
10133 final TaskRecord task;
10134 synchronized (this) {
10135 task = mStackSupervisor.anyTaskForIdLocked(taskId,
10136 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS, INVALID_STACK_ID);
10137 if (task == null) {
10138 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
10139 return null;
10140 }
10141 }
10142 // Don't call this while holding the lock as this operation might hit the disk.
10143 return task.getSnapshot(reducedResolution);
10144 } finally {
10145 Binder.restoreCallingIdentity(ident);
10146 }
10147 }
10148
10149 @Override
10150 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
10151 if (userId != UserHandle.getCallingUserId()) {
10152 enforceCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10153 "getTaskDescriptionIcon");
10154 }
10155 final File passedIconFile = new File(filePath);
10156 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
10157 passedIconFile.getName());
10158 if (!legitIconFile.getPath().equals(filePath)
10159 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
10160 throw new IllegalArgumentException("Bad file path: " + filePath
10161 + " passed for userId " + userId);
10162 }
10163 return mRecentTasks.getTaskDescriptionIcon(filePath);
10164 }
10165
10166 @Override
10167 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts)
10168 throws RemoteException {
10169 final ActivityOptions activityOptions = ActivityOptions.fromBundle(opts);
10170 if (activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE ||
10171 activityOptions.getCustomInPlaceResId() == 0) {
10172 throw new IllegalArgumentException("Expected in-place ActivityOption " +
10173 "with valid animation");
10174 }
10175 mWindowManager.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
10176 mWindowManager.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
10177 activityOptions.getCustomInPlaceResId());
10178 mWindowManager.executeAppTransition();
10179 }
10180
10181 private void removeTasksByPackageNameLocked(String packageName, int userId) {
10182 // Remove all tasks with activities in the specified package from the list of recent tasks
10183 for (int i = mRecentTasks.size() - 1; i >= 0; i--) {
10184 TaskRecord tr = mRecentTasks.get(i);
10185 if (tr.userId != userId) continue;
10186
10187 ComponentName cn = tr.intent.getComponent();
10188 if (cn != null && cn.getPackageName().equals(packageName)) {
10189 // If the package name matches, remove the task.
10190 mStackSupervisor.removeTaskByIdLocked(tr.taskId, true, REMOVE_FROM_RECENTS);
10191 }
10192 }
10193 }
10194
10195 private void cleanupDisabledPackageTasksLocked(String packageName, Set<String> filterByClasses,
10196 int userId) {
10197
10198 for (int i = mRecentTasks.size() - 1; i >= 0; i--) {
10199 TaskRecord tr = mRecentTasks.get(i);
10200 if (userId != UserHandle.USER_ALL && tr.userId != userId) {
10201 continue;
10202 }
10203
10204 ComponentName cn = tr.intent.getComponent();
10205 final boolean sameComponent = cn != null && cn.getPackageName().equals(packageName)
10206 && (filterByClasses == null || filterByClasses.contains(cn.getClassName()));
10207 if (sameComponent) {
10208 mStackSupervisor.removeTaskByIdLocked(tr.taskId, false, REMOVE_FROM_RECENTS);
10209 }
10210 }
10211 }
10212
10213 @Override
10214 public void removeStack(int stackId) {
10215 enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS, "removeStack()");
10216 if (StackId.isHomeOrRecentsStack(stackId)) {
10217 throw new IllegalArgumentException("Removing home or recents stack is not allowed.");
10218 }
10219
10220 synchronized (this) {
10221 final long ident = Binder.clearCallingIdentity();
10222 try {
10223 mStackSupervisor.removeStackLocked(stackId);
10224 } finally {
10225 Binder.restoreCallingIdentity(ident);
10226 }
10227 }
10228 }
10229
10230 @Override
10231 public void moveStackToDisplay(int stackId, int displayId) {
10232 enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
10233
10234 synchronized (this) {
10235 final long ident = Binder.clearCallingIdentity();
10236 try {
10237 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
10238 + " to displayId=" + displayId);
10239 mStackSupervisor.moveStackToDisplayLocked(stackId, displayId, ON_TOP);
10240 } finally {
10241 Binder.restoreCallingIdentity(ident);
10242 }
10243 }
10244 }
10245
10246 @Override
10247 public boolean removeTask(int taskId) {
10248 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS, "removeTask()");
10249 synchronized (this) {
10250 final long ident = Binder.clearCallingIdentity();
10251 try {
10252 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS);
10253 } finally {
10254 Binder.restoreCallingIdentity(ident);
10255 }
10256 }
10257 }
10258
10259 /**
10260 * TODO: Add mController hook
10261 */
10262 @Override
10263 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
10264 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
10265
10266 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
10267 synchronized(this) {
10268 moveTaskToFrontLocked(taskId, flags, bOptions, false /* fromRecents */);
10269 }
10270 }
10271
10272 void moveTaskToFrontLocked(int taskId, int flags, Bundle bOptions, boolean fromRecents) {
10273 ActivityOptions options = ActivityOptions.fromBundle(bOptions);
10274
10275 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
10276 Binder.getCallingUid(), -1, -1, "Task to front")) {
10277 ActivityOptions.abort(options);
10278 return;
10279 }
10280 final long origId = Binder.clearCallingIdentity();
10281 try {
10282 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
10283 if (task == null) {
10284 Slog.d(TAG, "Could not find task for id: "+ taskId);
10285 return;
10286 }
10287 if (mStackSupervisor.isLockTaskModeViolation(task)) {
10288 mStackSupervisor.showLockTaskToast();
10289 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
10290 return;
10291 }
10292 final ActivityRecord prev = mStackSupervisor.topRunningActivityLocked();
10293 if (prev != null) {
10294 task.setTaskToReturnTo(prev);
10295 }
10296 mStackSupervisor.findTaskToMoveToFrontLocked(task, flags, options, "moveTaskToFront",
10297 false /* forceNonResizable */);
10298
10299 final ActivityRecord topActivity = task.getTopActivity();
10300 if (topActivity != null) {
10301
10302 // We are reshowing a task, use a starting window to hide the initial draw delay
10303 // so the transition can start earlier.
10304 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
10305 true /* taskSwitch */, fromRecents);
10306 }
10307 } finally {
10308 Binder.restoreCallingIdentity(origId);
10309 }
10310 ActivityOptions.abort(options);
10311 }
10312
10313 /**
10314 * Attempts to move a task backwards in z-order (the order of activities within the task is
10315 * unchanged).
10316 *
10317 * There are several possible results of this call:
10318 * - if the task is locked, then we will show the lock toast
10319 * - if there is a task behind the provided task, then that task is made visible and resumed as
10320 * this task is moved to the back
10321 * - otherwise, if there are no other tasks in the stack:
10322 * - if this task is in the pinned stack, then we remove the stack completely, which will
10323 * have the effect of moving the task to the top or bottom of the fullscreen stack
10324 * (depending on whether it is visible)
10325 * - otherwise, we simply return home and hide this task
10326 *
10327 * @param token A reference to the activity we wish to move
10328 * @param nonRoot If false then this only works if the activity is the root
10329 * of a task; if true it will work for any activity in a task.
10330 * @return Returns true if the move completed, false if not.
10331 */
10332 @Override
10333 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
10334 enforceNotIsolatedCaller("moveActivityTaskToBack");
10335 synchronized(this) {
10336 final long origId = Binder.clearCallingIdentity();
10337 try {
10338 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
10339 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
10340 if (task != null) {
10341 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
10342 }
10343 } finally {
10344 Binder.restoreCallingIdentity(origId);
10345 }
10346 }
10347 return false;
10348 }
10349
10350 @Override
10351 public void moveTaskBackwards(int task) {
10352 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
10353 "moveTaskBackwards()");
10354
10355 synchronized(this) {
10356 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
10357 Binder.getCallingUid(), -1, -1, "Task backwards")) {
10358 return;
10359 }
10360 final long origId = Binder.clearCallingIdentity();
10361 moveTaskBackwardsLocked(task);
10362 Binder.restoreCallingIdentity(origId);
10363 }
10364 }
10365
10366 private final void moveTaskBackwardsLocked(int task) {
10367 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
10368 }
10369
10370 @Override
10371 public IActivityContainer createVirtualActivityContainer(IBinder parentActivityToken,
10372 IActivityContainerCallback callback) throws RemoteException {
10373 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "createActivityContainer()");
10374 synchronized (this) {
10375 if (parentActivityToken == null) {
10376 throw new IllegalArgumentException("parent token must not be null");
10377 }
10378 ActivityRecord r = ActivityRecord.forTokenLocked(parentActivityToken);
10379 if (r == null) {
10380 return null;
10381 }
10382 if (callback == null) {
10383 throw new IllegalArgumentException("callback must not be null");
10384 }
10385 return mStackSupervisor.createVirtualActivityContainer(r, callback);
10386 }
10387 }
10388
10389 @Override
10390 public IActivityContainer createStackOnDisplay(int displayId) throws RemoteException {
10391 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "createStackOnDisplay()");
10392 synchronized (this) {
10393 final int stackId = mStackSupervisor.getNextStackId();
10394 final ActivityStack stack =
10395 mStackSupervisor.createStackOnDisplay(stackId, displayId, true /*onTop*/);
10396 if (stack == null) {
10397 return null;
10398 }
10399 return stack.mActivityContainer;
10400 }
10401 }
10402
10403 @Override
10404 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
10405 synchronized (this) {
10406 ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
10407 if (stack != null && stack.mActivityContainer.isAttachedLocked()) {
10408 return stack.mActivityContainer.getDisplayId();
10409 }
10410 return DEFAULT_DISPLAY;
10411 }
10412 }
10413
10414 @Override
10415 public int getActivityStackId(IBinder token) throws RemoteException {
10416 synchronized (this) {
10417 ActivityStack stack = ActivityRecord.getStackLocked(token);
10418 if (stack == null) {
10419 return INVALID_STACK_ID;
10420 }
10421 return stack.mStackId;
10422 }
10423 }
10424
10425 @Override
10426 public void exitFreeformMode(IBinder token) throws RemoteException {
10427 synchronized (this) {
10428 long ident = Binder.clearCallingIdentity();
10429 try {
10430 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
10431 if (r == null) {
10432 throw new IllegalArgumentException(
10433 "exitFreeformMode: No activity record matching token=" + token);
10434 }
10435
10436 final ActivityStack stack = r.getStack();
10437 if (stack == null || stack.mStackId != FREEFORM_WORKSPACE_STACK_ID) {
10438 throw new IllegalStateException(
10439 "exitFreeformMode: You can only go fullscreen from freeform.");
10440 }
10441
10442 if (DEBUG_STACK) Slog.d(TAG_STACK, "exitFreeformMode: " + r);
10443 r.getTask().reparent(FULLSCREEN_WORKSPACE_STACK_ID, ON_TOP,
10444 REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME, "exitFreeformMode");
10445 } finally {
10446 Binder.restoreCallingIdentity(ident);
10447 }
10448 }
10449 }
10450
10451 @Override
10452 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
10453 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
10454 if (StackId.isHomeOrRecentsStack(stackId)) {
10455 throw new IllegalArgumentException(
10456 "moveTaskToStack: Attempt to move task " + taskId + " to stack " + stackId);
10457 }
10458 synchronized (this) {
10459 long ident = Binder.clearCallingIdentity();
10460 try {
10461 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
10462 if (task == null) {
10463 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
10464 return;
10465 }
10466
10467 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
10468 + " to stackId=" + stackId + " toTop=" + toTop);
10469 if (stackId == DOCKED_STACK_ID) {
10470 mWindowManager.setDockedStackCreateState(DOCKED_STACK_CREATE_MODE_TOP_OR_LEFT,
10471 null /* initialBounds */);
10472 }
10473 task.reparent(stackId, toTop,
10474 REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME, "moveTaskToStack");
10475 } finally {
10476 Binder.restoreCallingIdentity(ident);
10477 }
10478 }
10479 }
10480
10481 @Override
10482 public void swapDockedAndFullscreenStack() throws RemoteException {
10483 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "swapDockedAndFullscreenStack()");
10484 synchronized (this) {
10485 long ident = Binder.clearCallingIdentity();
10486 try {
10487 final ActivityStack fullscreenStack = mStackSupervisor.getStack(
10488 FULLSCREEN_WORKSPACE_STACK_ID);
10489 final TaskRecord topTask = fullscreenStack != null ? fullscreenStack.topTask()
10490 : null;
10491 final ActivityStack dockedStack = mStackSupervisor.getStack(DOCKED_STACK_ID);
10492 final ArrayList<TaskRecord> tasks = dockedStack != null ? dockedStack.getAllTasks()
10493 : null;
10494 if (topTask == null || tasks == null || tasks.size() == 0) {
10495 Slog.w(TAG,
10496 "Unable to swap tasks, either docked or fullscreen stack is empty.");
10497 return;
10498 }
10499
10500 // TODO: App transition
10501 mWindowManager.prepareAppTransition(TRANSIT_ACTIVITY_RELAUNCH, false);
10502
10503 // Defer the resume until we move all the docked tasks to the fullscreen stack below
10504 topTask.reparent(DOCKED_STACK_ID, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
10505 DEFER_RESUME, "swapDockedAndFullscreenStack - DOCKED_STACK");
10506 final int size = tasks.size();
10507 for (int i = 0; i < size; i++) {
10508 final int id = tasks.get(i).taskId;
10509 if (id == topTask.taskId) {
10510 continue;
10511 }
10512
10513 // Defer the resume until after all the tasks have been moved
10514 tasks.get(i).reparent(FULLSCREEN_WORKSPACE_STACK_ID, ON_TOP,
10515 REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, DEFER_RESUME,
10516 "swapDockedAndFullscreenStack - FULLSCREEN_STACK");
10517 }
10518
10519 // Because we deferred the resume to avoid conflicts with stack switches while
10520 // resuming, we need to do it after all the tasks are moved.
10521 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
10522 mStackSupervisor.resumeFocusedStackTopActivityLocked();
10523
10524 mWindowManager.executeAppTransition();
10525 } finally {
10526 Binder.restoreCallingIdentity(ident);
10527 }
10528 }
10529 }
10530
10531 /**
10532 * Moves the input task to the docked stack.
10533 *
10534 * @param taskId Id of task to move.
10535 * @param createMode The mode the docked stack should be created in if it doesn't exist
10536 * already. See
10537 * {@link android.app.ActivityManager#DOCKED_STACK_CREATE_MODE_TOP_OR_LEFT}
10538 * and
10539 * {@link android.app.ActivityManager#DOCKED_STACK_CREATE_MODE_BOTTOM_OR_RIGHT}
10540 * @param toTop If the task and stack should be moved to the top.
10541 * @param animate Whether we should play an animation for the moving the task
10542 * @param initialBounds If the docked stack gets created, it will use these bounds for the
10543 * docked stack. Pass {@code null} to use default bounds.
10544 */
10545 @Override
10546 public boolean moveTaskToDockedStack(int taskId, int createMode, boolean toTop, boolean animate,
10547 Rect initialBounds) {
10548 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToDockedStack()");
10549 synchronized (this) {
10550 long ident = Binder.clearCallingIdentity();
10551 try {
10552 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
10553 if (task == null) {
10554 Slog.w(TAG, "moveTaskToDockedStack: No task for id=" + taskId);
10555 return false;
10556 }
10557
10558 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToDockedStack: moving task=" + taskId
10559 + " to createMode=" + createMode + " toTop=" + toTop);
10560 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
10561
10562 // Defer resuming until we move the home stack to the front below
10563 final boolean moved = task.reparent(DOCKED_STACK_ID, toTop,
10564 REPARENT_KEEP_STACK_AT_FRONT, animate, !DEFER_RESUME,
10565 "moveTaskToDockedStack");
10566 if (moved) {
10567 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
10568 }
10569 return moved;
10570 } finally {
10571 Binder.restoreCallingIdentity(ident);
10572 }
10573 }
10574 }
10575
10576 /**
10577 * Moves the top activity in the input stackId to the pinned stack.
10578 *
10579 * @param stackId Id of stack to move the top activity to pinned stack.
10580 * @param bounds Bounds to use for pinned stack.
10581 *
10582 * @return True if the top activity of the input stack was successfully moved to the pinned
10583 * stack.
10584 */
10585 @Override
10586 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
10587 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "moveTopActivityToPinnedStack()");
10588 synchronized (this) {
10589 if (!mSupportsPictureInPicture) {
10590 throw new IllegalStateException("moveTopActivityToPinnedStack:"
10591 + "Device doesn't support picture-in-picture mode");
10592 }
10593
10594 long ident = Binder.clearCallingIdentity();
10595 try {
10596 return mStackSupervisor.moveTopStackActivityToPinnedStackLocked(stackId, bounds);
10597 } finally {
10598 Binder.restoreCallingIdentity(ident);
10599 }
10600 }
10601 }
10602
10603 @Override
10604 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
10605 boolean preserveWindows, boolean animate, int animationDuration) {
10606 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
10607 long ident = Binder.clearCallingIdentity();
10608 try {
10609 synchronized (this) {
10610 if (animate) {
10611 if (stackId == PINNED_STACK_ID) {
10612 final PinnedActivityStack pinnedStack =
10613 mStackSupervisor.getStack(PINNED_STACK_ID);
10614 if (pinnedStack != null) {
10615 pinnedStack.animateResizePinnedStack(null /* sourceHintBounds */,
10616 destBounds, animationDuration, false /* fromFullscreen */);
10617 }
10618 } else {
10619 throw new IllegalArgumentException("Stack: " + stackId
10620 + " doesn't support animated resize.");
10621 }
10622 } else {
10623 mStackSupervisor.resizeStackLocked(stackId, destBounds, null /* tempTaskBounds */,
10624 null /* tempTaskInsetBounds */, preserveWindows,
10625 allowResizeInDockedMode, !DEFER_RESUME);
10626 }
10627 }
10628 } finally {
10629 Binder.restoreCallingIdentity(ident);
10630 }
10631 }
10632
10633 @Override
10634 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
10635 Rect tempDockedTaskInsetBounds,
10636 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
10637 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
10638 "resizeDockedStack()");
10639 long ident = Binder.clearCallingIdentity();
10640 try {
10641 synchronized (this) {
10642 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
10643 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
10644 PRESERVE_WINDOWS);
10645 }
10646 } finally {
10647 Binder.restoreCallingIdentity(ident);
10648 }
10649 }
10650
10651 @Override
10652 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
10653 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
10654 "resizePinnedStack()");
10655 final long ident = Binder.clearCallingIdentity();
10656 try {
10657 synchronized (this) {
10658 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
10659 }
10660 } finally {
10661 Binder.restoreCallingIdentity(ident);
10662 }
10663 }
10664
10665 /**
10666 * Try to place task to provided position. The final position might be different depending on
10667 * current user and stacks state. The task will be moved to target stack if it's currently in
10668 * different stack.
10669 */
10670 @Override
10671 public void positionTaskInStack(int taskId, int stackId, int position) {
10672 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
10673 if (StackId.isHomeOrRecentsStack(stackId)) {
10674 throw new IllegalArgumentException(
10675 "positionTaskInStack: Attempt to change the position of task "
10676 + taskId + " in/to home/recents stack");
10677 }
10678 synchronized (this) {
10679 long ident = Binder.clearCallingIdentity();
10680 try {
10681 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
10682 + taskId + " in stackId=" + stackId + " at position=" + position);
10683 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
10684 if (task == null) {
10685 throw new IllegalArgumentException("positionTaskInStack: no task for id="
10686 + taskId);
10687 }
10688
10689 final ActivityStack stack = mStackSupervisor.getStack(stackId, CREATE_IF_NEEDED,
10690 !ON_TOP);
10691
10692 // TODO: Have the callers of this API call a separate reparent method if that is
10693 // what they intended to do vs. having this method also do reparenting.
10694 if (task.getStack() == stack) {
10695 // Change position in current stack.
10696 stack.positionChildAt(task, position);
10697 } else {
10698 // Reparent to new stack.
10699 task.reparent(stackId, position, REPARENT_LEAVE_STACK_IN_PLACE,
10700 !ANIMATE, !DEFER_RESUME, "positionTaskInStack");
10701 }
10702 } finally {
10703 Binder.restoreCallingIdentity(ident);
10704 }
10705 }
10706 }
10707
10708 @Override
10709 public List<StackInfo> getAllStackInfos() {
10710 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
10711 long ident = Binder.clearCallingIdentity();
10712 try {
10713 synchronized (this) {
10714 return mStackSupervisor.getAllStackInfosLocked();
10715 }
10716 } finally {
10717 Binder.restoreCallingIdentity(ident);
10718 }
10719 }
10720
10721 @Override
10722 public StackInfo getStackInfo(int stackId) {
10723 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
10724 long ident = Binder.clearCallingIdentity();
10725 try {
10726 synchronized (this) {
10727 return mStackSupervisor.getStackInfoLocked(stackId);
10728 }
10729 } finally {
10730 Binder.restoreCallingIdentity(ident);
10731 }
10732 }
10733
10734 @Override
10735 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
10736 synchronized(this) {
10737 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
10738 }
10739 }
10740
10741 @Override
10742 public void updateDeviceOwner(String packageName) {
10743 final int callingUid = Binder.getCallingUid();
10744 if (callingUid != 0 && callingUid != SYSTEM_UID) {
10745 throw new SecurityException("updateDeviceOwner called from non-system process");
10746 }
10747 synchronized (this) {
10748 mDeviceOwnerName = packageName;
10749 }
10750 }
10751
10752 @Override
10753 public void updateLockTaskPackages(int userId, String[] packages) {
10754 final int callingUid = Binder.getCallingUid();
10755 if (callingUid != 0 && callingUid != SYSTEM_UID) {
10756 enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
10757 "updateLockTaskPackages()");
10758 }
10759 synchronized (this) {
10760 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":" +
10761 Arrays.toString(packages));
10762 mLockTaskPackages.put(userId, packages);
10763 mStackSupervisor.onLockTaskPackagesUpdatedLocked();
10764 }
10765 }
10766
10767
10768 void startLockTaskModeLocked(TaskRecord task) {
10769 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
10770 if (task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
10771 return;
10772 }
10773
10774 // When a task is locked, dismiss the pinned stack if it exists
10775 final PinnedActivityStack pinnedStack = mStackSupervisor.getStack(
10776 PINNED_STACK_ID);
10777 if (pinnedStack != null) {
10778 mStackSupervisor.removeStackLocked(PINNED_STACK_ID);
10779 }
10780
10781 // isSystemInitiated is used to distinguish between locked and pinned mode, as pinned mode
10782 // is initiated by system after the pinning request was shown and locked mode is initiated
10783 // by an authorized app directly
10784 final int callingUid = Binder.getCallingUid();
10785 boolean isSystemInitiated = callingUid == SYSTEM_UID;
10786 long ident = Binder.clearCallingIdentity();
10787 try {
10788 if (!isSystemInitiated) {
10789 task.mLockTaskUid = callingUid;
10790 if (task.mLockTaskAuth == LOCK_TASK_AUTH_PINNABLE) {
10791 // startLockTask() called by app and task mode is lockTaskModeDefault.
10792 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Mode default, asking user");
10793 StatusBarManagerInternal statusBarManager =
10794 LocalServices.getService(StatusBarManagerInternal.class);
10795 if (statusBarManager != null) {
10796 statusBarManager.showScreenPinningRequest(task.taskId);
10797 }
10798 return;
10799 }
10800
10801 final ActivityStack stack = mStackSupervisor.getFocusedStack();
10802 if (stack == null || task != stack.topTask()) {
10803 throw new IllegalArgumentException("Invalid task, not in foreground");
10804 }
10805 }
10806 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, isSystemInitiated ? "Locking pinned" :
10807 "Locking fully");
10808 mStackSupervisor.setLockTaskModeLocked(task, isSystemInitiated ?
10809 ActivityManager.LOCK_TASK_MODE_PINNED :
10810 ActivityManager.LOCK_TASK_MODE_LOCKED,
10811 "startLockTask", true);
10812 } finally {
10813 Binder.restoreCallingIdentity(ident);
10814 }
10815 }
10816
10817 @Override
10818 public void startLockTaskModeById(int taskId) {
10819 synchronized (this) {
10820 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
10821 if (task != null) {
10822 startLockTaskModeLocked(task);
10823 }
10824 }
10825 }
10826
10827 @Override
10828 public void startLockTaskModeByToken(IBinder token) {
10829 synchronized (this) {
10830 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
10831 if (r == null) {
10832 return;
10833 }
10834 final TaskRecord task = r.getTask();
10835 if (task != null) {
10836 startLockTaskModeLocked(task);
10837 }
10838 }
10839 }
10840
10841 @Override
10842 public void startSystemLockTaskMode(int taskId) throws RemoteException {
10843 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
10844 // This makes inner call to look as if it was initiated by system.
10845 long ident = Binder.clearCallingIdentity();
10846 try {
10847 synchronized (this) {
10848 startLockTaskModeById(taskId);
10849 }
10850 } finally {
10851 Binder.restoreCallingIdentity(ident);
10852 }
10853 }
10854
10855 @Override
10856 public void stopLockTaskMode() {
10857 final TaskRecord lockTask = mStackSupervisor.getLockedTaskLocked();
10858 if (lockTask == null) {
10859 // Our work here is done.
10860 return;
10861 }
10862
10863 final int callingUid = Binder.getCallingUid();
10864 final int lockTaskUid = lockTask.mLockTaskUid;
10865 final int lockTaskModeState = mStackSupervisor.getLockTaskModeState();
10866 if (lockTaskModeState == ActivityManager.LOCK_TASK_MODE_NONE) {
10867 // Done.
10868 return;
10869 } else {
10870 // Ensure the same caller for startLockTaskMode and stopLockTaskMode.
10871 // It is possible lockTaskMode was started by the system process because
10872 // android:lockTaskMode is set to a locking value in the application manifest
10873 // instead of the app calling startLockTaskMode. In this case
10874 // {@link TaskRecord.mLockTaskUid} will be 0, so we compare the callingUid to the
10875 // {@link TaskRecord.effectiveUid} instead. Also caller with
10876 // {@link MANAGE_ACTIVITY_STACKS} can stop any lock task.
10877 if (checkCallingPermission(MANAGE_ACTIVITY_STACKS) != PERMISSION_GRANTED
10878 && callingUid != lockTaskUid
10879 && (lockTaskUid != 0 || callingUid != lockTask.effectiveUid)) {
10880 throw new SecurityException("Invalid uid, expected " + lockTaskUid
10881 + " callingUid=" + callingUid + " effectiveUid=" + lockTask.effectiveUid);
10882 }
10883 }
10884 long ident = Binder.clearCallingIdentity();
10885 try {
10886 Log.d(TAG, "stopLockTaskMode");
10887 // Stop lock task
10888 synchronized (this) {
10889 mStackSupervisor.setLockTaskModeLocked(null, ActivityManager.LOCK_TASK_MODE_NONE,
10890 "stopLockTask", true);
10891 }
10892 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
10893 if (tm != null) {
10894 tm.showInCallScreen(false);
10895 }
10896 } finally {
10897 Binder.restoreCallingIdentity(ident);
10898 }
10899 }
10900
10901 /**
10902 * This API should be called by SystemUI only when user perform certain action to dismiss
10903 * lock task mode. We should only dismiss pinned lock task mode in this case.
10904 */
10905 @Override
10906 public void stopSystemLockTaskMode() throws RemoteException {
10907 if (mStackSupervisor.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_PINNED) {
10908 stopLockTaskMode();
10909 } else {
10910 mStackSupervisor.showLockTaskToast();
10911 }
10912 }
10913
10914 @Override
10915 public boolean isInLockTaskMode() {
10916 return getLockTaskModeState() != ActivityManager.LOCK_TASK_MODE_NONE;
10917 }
10918
10919 @Override
10920 public int getLockTaskModeState() {
10921 synchronized (this) {
10922 return mStackSupervisor.getLockTaskModeState();
10923 }
10924 }
10925
10926 @Override
10927 public void showLockTaskEscapeMessage(IBinder token) {
10928 synchronized (this) {
10929 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
10930 if (r == null) {
10931 return;
10932 }
10933 mStackSupervisor.showLockTaskEscapeMessageLocked(r.getTask());
10934 }
10935 }
10936
10937 @Override
10938 public void setDisablePreviewScreenshots(IBinder token, boolean disable)
10939 throws RemoteException {
10940 synchronized (this) {
10941 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
10942 if (r == null) {
10943 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
10944 + token);
10945 return;
10946 }
10947 final long origId = Binder.clearCallingIdentity();
10948 try {
10949 r.setDisablePreviewScreenshots(disable);
10950 } finally {
10951 Binder.restoreCallingIdentity(origId);
10952 }
10953 }
10954 }

content provider相关

 10956    // =========================================================
10957 // CONTENT PROVIDERS
10958 // =========================================================
10959
10960 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
10961 List<ProviderInfo> providers = null;
10962 try {
10963 providers = AppGlobals.getPackageManager()
10964 .queryContentProviders(app.processName, app.uid,
10965 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS
10966 | MATCH_DEBUG_TRIAGED_MISSING, /*metadastaKey=*/ null)
10967 .getList();
10968 } catch (RemoteException ex) {
10969 }
10970 if (DEBUG_MU) Slog.v(TAG_MU,
10971 "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
10972 int userId = app.userId;
10973 if (providers != null) {
10974 int N = providers.size();
10975 app.pubProviders.ensureCapacity(N + app.pubProviders.size());
10976 for (int i=0; i<N; i++) {
10977 // TODO: keep logic in sync with installEncryptionUnawareProviders
10978 ProviderInfo cpi =
10979 (ProviderInfo)providers.get(i);
10980 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
10981 cpi.name, cpi.flags);
10982 if (singleton && UserHandle.getUserId(app.uid) != UserHandle.USER_SYSTEM) {
10983 // This is a singleton provider, but a user besides the
10984 // default user is asking to initialize a process it runs
10985 // in... well, no, it doesn't actually run in this process,
10986 // it runs in the process of the default user. Get rid of it.
10987 providers.remove(i);
10988 N--;
10989 i--;
10990 continue;
10991 }
10992
10993 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
10994 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
10995 if (cpr == null) {
10996 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
10997 mProviderMap.putProviderByClass(comp, cpr);
10998 }
10999 if (DEBUG_MU) Slog.v(TAG_MU,
11000 "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
11001 app.pubProviders.put(cpi.name, cpr);
11002 if (!cpi.multiprocess || !"android".equals(cpi.packageName)) {
11003 // Don't add this if it is a platform component that is marked
11004 // to run in multiple processes, because this is actually
11005 // part of the framework so doesn't make sense to track as a
11006 // separate apk in the process.
11007 app.addPackage(cpi.applicationInfo.packageName, cpi.applicationInfo.versionCode,
11008 mProcessStats);
11009 }
11010 notifyPackageUse(cpi.applicationInfo.packageName,
11011 PackageManager.NOTIFY_PACKAGE_USE_CONTENT_PROVIDER);
11012 }
11013 }
11014 return providers;
11015 }
11016
11017 /**
11018 * Check if the calling UID has a possible chance at accessing the provider
11019 * at the given authority and user.
11020 */
11021 public String checkContentProviderAccess(String authority, int userId) {
11022 if (userId == UserHandle.USER_ALL) {
11023 mContext.enforceCallingOrSelfPermission(
11024 Manifest.permission.INTERACT_ACROSS_USERS_FULL, TAG);
11025 userId = UserHandle.getCallingUserId();
11026 }
11027
11028 ProviderInfo cpi = null;
11029 try {
11030 cpi = AppGlobals.getPackageManager().resolveContentProvider(authority,
11031 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS
11032 | PackageManager.MATCH_DISABLED_COMPONENTS
11033 | PackageManager.MATCH_DIRECT_BOOT_AWARE
11034 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
11035 userId);
11036 } catch (RemoteException ignored) {
11037 }
11038 if (cpi == null) {
11039 return "Failed to find provider " + authority + " for user " + userId
11040 + "; expected to find a valid ContentProvider for this authority";
11041 }
11042
11043 ProcessRecord r = null;
11044 synchronized (mPidsSelfLocked) {
11045 r = mPidsSelfLocked.get(Binder.getCallingPid());
11046 }
11047 if (r == null) {
11048 return "Failed to find PID " + Binder.getCallingPid();
11049 }
11050
11051 synchronized (this) {
11052 return checkContentProviderPermissionLocked(cpi, r, userId, true);
11053 }
11054 }
11055
11056 /**
11057 * Check if {@link ProcessRecord} has a possible chance at accessing the
11058 * given {@link ProviderInfo}. Final permission checking is always done
11059 * in {@link ContentProvider}.
11060 */
11061 private final String checkContentProviderPermissionLocked(
11062 ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser) {
11063 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
11064 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
11065 boolean checkedGrants = false;
11066 if (checkUser) {
11067 // Looking for cross-user grants before enforcing the typical cross-users permissions
11068 int tmpTargetUserId = mUserController.unsafeConvertIncomingUserLocked(userId);
11069 if (tmpTargetUserId != UserHandle.getUserId(callingUid)) {
11070 if (checkAuthorityGrants(callingUid, cpi, tmpTargetUserId, checkUser)) {
11071 return null;
11072 }
11073 checkedGrants = true;
11074 }
11075 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
11076 ALLOW_NON_FULL, "checkContentProviderPermissionLocked " + cpi.authority, null);
11077 if (userId != tmpTargetUserId) {
11078 // When we actually went to determine the final targer user ID, this ended
11079 // up different than our initial check for the authority. This is because
11080 // they had asked for USER_CURRENT_OR_SELF and we ended up switching to
11081 // SELF. So we need to re-check the grants again.
11082 checkedGrants = false;
11083 }
11084 }
11085 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
11086 cpi.applicationInfo.uid, cpi.exported)
11087 == PackageManager.PERMISSION_GRANTED) {
11088 return null;
11089 }
11090 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
11091 cpi.applicationInfo.uid, cpi.exported)
11092 == PackageManager.PERMISSION_GRANTED) {
11093 return null;
11094 }
11095
11096 PathPermission[] pps = cpi.pathPermissions;
11097 if (pps != null) {
11098 int i = pps.length;
11099 while (i > 0) {
11100 i--;
11101 PathPermission pp = pps[i];
11102 String pprperm = pp.getReadPermission();
11103 if (pprperm != null && checkComponentPermission(pprperm, callingPid, callingUid,
11104 cpi.applicationInfo.uid, cpi.exported)
11105 == PackageManager.PERMISSION_GRANTED) {
11106 return null;
11107 }
11108 String ppwperm = pp.getWritePermission();
11109 if (ppwperm != null && checkComponentPermission(ppwperm, callingPid, callingUid,
11110 cpi.applicationInfo.uid, cpi.exported)
11111 == PackageManager.PERMISSION_GRANTED) {
11112 return null;
11113 }
11114 }
11115 }
11116 if (!checkedGrants && checkAuthorityGrants(callingUid, cpi, userId, checkUser)) {
11117 return null;
11118 }
11119
11120 final String suffix;
11121 if (!cpi.exported) {
11122 suffix = " that is not exported from UID " + cpi.applicationInfo.uid;
11123 } else if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(cpi.readPermission)) {
11124 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
11125 } else {
11126 suffix = " requires " + cpi.readPermission + " or " + cpi.writePermission;
11127 }
11128 final String msg = "Permission Denial: opening provider " + cpi.name
11129 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
11130 + ", uid=" + callingUid + ")" + suffix;
11131 Slog.w(TAG, msg);
11132 return msg;
11133 }
11134
11135 /**
11136 * Returns if the ContentProvider has granted a uri to callingUid
11137 */
11138 boolean checkAuthorityGrants(int callingUid, ProviderInfo cpi, int userId, boolean checkUser) {
11139 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
11140 if (perms != null) {
11141 for (int i=perms.size()-1; i>=0; i--) {
11142 GrantUri grantUri = perms.keyAt(i);
11143 if (grantUri.sourceUserId == userId || !checkUser) {
11144 if (matchesProvider(grantUri.uri, cpi)) {
11145 return true;
11146 }
11147 }
11148 }
11149 }
11150 return false;
11151 }
11152
11153 /**
11154 * Returns true if the uri authority is one of the authorities specified in the provider.
11155 */
11156 boolean matchesProvider(Uri uri, ProviderInfo cpi) {
11157 String uriAuth = uri.getAuthority();
11158 String cpiAuth = cpi.authority;
11159 if (cpiAuth.indexOf(';') == -1) {
11160 return cpiAuth.equals(uriAuth);
11161 }
11162 String[] cpiAuths = cpiAuth.split(";");
11163 int length = cpiAuths.length;
11164 for (int i = 0; i < length; i++) {
11165 if (cpiAuths[i].equals(uriAuth)) return true;
11166 }
11167 return false;
11168 }
11169
11170 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
11171 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
11172 if (r != null) {
11173 for (int i=0; i<r.conProviders.size(); i++) {
11174 ContentProviderConnection conn = r.conProviders.get(i);
11175 if (conn.provider == cpr) {
11176 if (DEBUG_PROVIDER) Slog.v(TAG_PROVIDER,
11177 "Adding provider requested by "
11178 + r.processName + " from process "
11179 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
11180 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
11181 if (stable) {
11182 conn.stableCount++;
11183 conn.numStableIncs++;
11184 } else {
11185 conn.unstableCount++;
11186 conn.numUnstableIncs++;
11187 }
11188 return conn;
11189 }
11190 }
11191 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
11192 if (stable) {
11193 conn.stableCount = 1;
11194 conn.numStableIncs = 1;
11195 } else {
11196 conn.unstableCount = 1;
11197 conn.numUnstableIncs = 1;
11198 }
11199 cpr.connections.add(conn);
11200 r.conProviders.add(conn);
11201 startAssociationLocked(r.uid, r.processName, r.curProcState,
11202 cpr.uid, cpr.name, cpr.info.processName);
11203 return conn;
11204 }
11205 cpr.addExternalProcessHandleLocked(externalProcessToken);
11206 return null;
11207 }
11208
11209 boolean decProviderCountLocked(ContentProviderConnection conn,
11210 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
11211 if (conn != null) {
11212 cpr = conn.provider;
11213 if (DEBUG_PROVIDER) Slog.v(TAG_PROVIDER,
11214 "Removing provider requested by "
11215 + conn.client.processName + " from process "
11216 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
11217 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
11218 if (stable) {
11219 conn.stableCount--;
11220 } else {
11221 conn.unstableCount--;
11222 }
11223 if (conn.stableCount == 0 && conn.unstableCount == 0) {
11224 cpr.connections.remove(conn);
11225 conn.client.conProviders.remove(conn);
11226 if (conn.client.setProcState < ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
11227 // The client is more important than last activity -- note the time this
11228 // is happening, so we keep the old provider process around a bit as last
11229 // activity to avoid thrashing it.
11230 if (cpr.proc != null) {
11231 cpr.proc.lastProviderTime = SystemClock.uptimeMillis();
11232 }
11233 }
11234 stopAssociationLocked(conn.client.uid, conn.client.processName, cpr.uid, cpr.name);
11235 return true;
11236 }
11237 return false;
11238 }
11239 cpr.removeExternalProcessHandleLocked(externalProcessToken);
11240 return false;
11241 }
11242
11243 private void checkTime(long startTime, String where) {
11244 long now = SystemClock.uptimeMillis();
11245 if ((now-startTime) > 50) {
11246 // If we are taking more than 50ms, log about it.
11247 Slog.w(TAG, "Slow operation: " + (now-startTime) + "ms so far, now at " + where);
11248 }
11249 }
11250
11251 private static final int[] PROCESS_STATE_STATS_FORMAT = new int[] {
11252 PROC_SPACE_TERM,
11253 PROC_SPACE_TERM|PROC_PARENS,
11254 PROC_SPACE_TERM|PROC_CHAR|PROC_OUT_LONG, // 3: process state
11255 };
11256
11257 private final long[] mProcessStateStatsLongs = new long[1];
11258
11259 boolean isProcessAliveLocked(ProcessRecord proc) {
11260 if (proc.procStatFile == null) {
11261 proc.procStatFile = "/proc/" + proc.pid + "/stat";
11262 }
11263 mProcessStateStatsLongs[0] = 0;
11264 if (!readProcFile(proc.procStatFile, PROCESS_STATE_STATS_FORMAT, null,
11265 mProcessStateStatsLongs, null)) {
11266 if (DEBUG_OOM_ADJ) Slog.d(TAG, "UNABLE TO RETRIEVE STATE FOR " + proc.procStatFile);
11267 return false;
11268 }
11269 final long state = mProcessStateStatsLongs[0];
11270 if (DEBUG_OOM_ADJ) Slog.d(TAG, "RETRIEVED STATE FOR " + proc.procStatFile + ": "
11271 + (char)state);
11272 return state != 'Z' && state != 'X' && state != 'x' && state != 'K';
11273 }
11274
11275 private ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
11276 String name, IBinder token, boolean stable, int userId) {
11277 ContentProviderRecord cpr;
11278 ContentProviderConnection conn = null;
11279 ProviderInfo cpi = null;
11280
11281 synchronized(this) {
11282 long startTime = SystemClock.uptimeMillis();
11283
11284 ProcessRecord r = null;
11285 if (caller != null) {
11286 r = getRecordForAppLocked(caller);
11287 if (r == null) {
11288 throw new SecurityException(
11289 "Unable to find app for caller " + caller
11290 + " (pid=" + Binder.getCallingPid()
11291 + ") when getting content provider " + name);
11292 }
11293 }
11294
11295 boolean checkCrossUser = true;
11296
11297 checkTime(startTime, "getContentProviderImpl: getProviderByName");
11298
11299 // First check if this content provider has been published...
11300 cpr = mProviderMap.getProviderByName(name, userId);
11301 // If that didn't work, check if it exists for user 0 and then
11302 // verify that it's a singleton provider before using it.
11303 if (cpr == null && userId != UserHandle.USER_SYSTEM) {
11304 cpr = mProviderMap.getProviderByName(name, UserHandle.USER_SYSTEM);
11305 if (cpr != null) {
11306 cpi = cpr.info;
11307 if (isSingleton(cpi.processName, cpi.applicationInfo,
11308 cpi.name, cpi.flags)
11309 && isValidSingletonCall(r.uid, cpi.applicationInfo.uid)) {
11310 userId = UserHandle.USER_SYSTEM;
11311 checkCrossUser = false;
11312 } else {
11313 cpr = null;
11314 cpi = null;
11315 }
11316 }
11317 }
11318
11319 boolean providerRunning = cpr != null && cpr.proc != null && !cpr.proc.killed;
11320 if (providerRunning) {
11321 cpi = cpr.info;
11322 String msg;
11323 checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission");
11324 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser))
11325 != null) {
11326 throw new SecurityException(msg);
11327 }
11328 checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission");
11329
11330 if (r != null && cpr.canRunHere(r)) {
11331 // This provider has been published or is in the process
11332 // of being published... but it is also allowed to run
11333 // in the caller's process, so don't make a connection
11334 // and just let the caller instantiate its own instance.
11335 ContentProviderHolder holder = cpr.newHolder(null);
11336 // don't give caller the provider object, it needs
11337 // to make its own.
11338 holder.provider = null;
11339 return holder;
11340 }
11341 // Don't expose providers between normal apps and instant apps
11342 try {
11343 if (AppGlobals.getPackageManager()
11344 .resolveContentProvider(name, 0 /*flags*/, userId) == null) {
11345 return null;
11346 }
11347 } catch (RemoteException e) {
11348 }
11349
11350 final long origId = Binder.clearCallingIdentity();
11351
11352 checkTime(startTime, "getContentProviderImpl: incProviderCountLocked");
11353
11354 // In this case the provider instance already exists, so we can
11355 // return it right away.
11356 conn = incProviderCountLocked(r, cpr, token, stable);
11357 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
11358 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
11359 // If this is a perceptible app accessing the provider,
11360 // make sure to count it as being accessed and thus
11361 // back up on the LRU list. This is good because
11362 // content providers are often expensive to start.
11363 checkTime(startTime, "getContentProviderImpl: before updateLruProcess");
11364 updateLruProcessLocked(cpr.proc, false, null);
11365 checkTime(startTime, "getContentProviderImpl: after updateLruProcess");
11366 }
11367 }
11368
11369 checkTime(startTime, "getContentProviderImpl: before updateOomAdj");
11370 final int verifiedAdj = cpr.proc.verifiedAdj;
11371 boolean success = updateOomAdjLocked(cpr.proc, true);
11372 // XXX things have changed so updateOomAdjLocked doesn't actually tell us
11373 // if the process has been successfully adjusted. So to reduce races with
11374 // it, we will check whether the process still exists. Note that this doesn't
11375 // completely get rid of races with LMK killing the process, but should make
11376 // them much smaller.
11377 if (success && verifiedAdj != cpr.proc.setAdj && !isProcessAliveLocked(cpr.proc)) {
11378 success = false;
11379 }
11380 maybeUpdateProviderUsageStatsLocked(r, cpr.info.packageName, name);
11381 checkTime(startTime, "getContentProviderImpl: after updateOomAdj");
11382 if (DEBUG_PROVIDER) Slog.i(TAG_PROVIDER, "Adjust success: " + success);
11383 // NOTE: there is still a race here where a signal could be
11384 // pending on the process even though we managed to update its
11385 // adj level. Not sure what to do about this, but at least
11386 // the race is now smaller.
11387 if (!success) {
11388 // Uh oh... it looks like the provider's process
11389 // has been killed on us. We need to wait for a new
11390 // process to be started, and make sure its death
11391 // doesn't kill our process.
11392 Slog.i(TAG, "Existing provider " + cpr.name.flattenToShortString()
11393 + " is crashing; detaching " + r);
11394 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
11395 checkTime(startTime, "getContentProviderImpl: before appDied");
11396 appDiedLocked(cpr.proc);
11397 checkTime(startTime, "getContentProviderImpl: after appDied");
11398 if (!lastRef) {
11399 // This wasn't the last ref our process had on
11400 // the provider... we have now been killed, bail.
11401 return null;
11402 }
11403 providerRunning = false;
11404 conn = null;
11405 } else {
11406 cpr.proc.verifiedAdj = cpr.proc.setAdj;
11407 }
11408
11409 Binder.restoreCallingIdentity(origId);
11410 }
11411
11412 if (!providerRunning) {
11413 try {
11414 checkTime(startTime, "getContentProviderImpl: before resolveContentProvider");
11415 cpi = AppGlobals.getPackageManager().
11416 resolveContentProvider(name,
11417 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
11418 checkTime(startTime, "getContentProviderImpl: after resolveContentProvider");
11419 } catch (RemoteException ex) {
11420 }
11421 if (cpi == null) {
11422 return null;
11423 }
11424 // If the provider is a singleton AND
11425 // (it's a call within the same user || the provider is a
11426 // privileged app)
11427 // Then allow connecting to the singleton provider
11428 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
11429 cpi.name, cpi.flags)
11430 && isValidSingletonCall(r.uid, cpi.applicationInfo.uid);
11431 if (singleton) {
11432 userId = UserHandle.USER_SYSTEM;
11433 }
11434 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
11435 checkTime(startTime, "getContentProviderImpl: got app info for user");
11436
11437 String msg;
11438 checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission");
11439 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, !singleton))
11440 != null) {
11441 throw new SecurityException(msg);
11442 }
11443 checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission");
11444
11445 if (!mProcessesReady
11446 && !cpi.processName.equals("system")) {
11447 // If this content provider does not run in the system
11448 // process, and the system is not yet ready to run other
11449 // processes, then fail fast instead of hanging.
11450 throw new IllegalArgumentException(
11451 "Attempt to launch content provider before system ready");
11452 }
11453
11454 // Make sure that the user who owns this provider is running. If not,
11455 // we don't want to allow it to run.
11456 if (!mUserController.isUserRunningLocked(userId, 0)) {
11457 Slog.w(TAG, "Unable to launch app "
11458 + cpi.applicationInfo.packageName + "/"
11459 + cpi.applicationInfo.uid + " for provider "
11460 + name + ": user " + userId + " is stopped");
11461 return null;
11462 }
11463
11464 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
11465 checkTime(startTime, "getContentProviderImpl: before getProviderByClass");
11466 cpr = mProviderMap.getProviderByClass(comp, userId);
11467 checkTime(startTime, "getContentProviderImpl: after getProviderByClass");
11468 final boolean firstClass = cpr == null;
11469 if (firstClass) {
11470 final long ident = Binder.clearCallingIdentity();
11471
11472 // If permissions need a review before any of the app components can run,
11473 // we return no provider and launch a review activity if the calling app
11474 // is in the foreground.
11475 if (mPermissionReviewRequired) {
11476 if (!requestTargetProviderPermissionsReviewIfNeededLocked(cpi, r, userId)) {
11477 return null;
11478 }
11479 }
11480
11481 try {
11482 checkTime(startTime, "getContentProviderImpl: before getApplicationInfo");
11483 ApplicationInfo ai =
11484 AppGlobals.getPackageManager().
11485 getApplicationInfo(
11486 cpi.applicationInfo.packageName,
11487 STOCK_PM_FLAGS, userId);
11488 checkTime(startTime, "getContentProviderImpl: after getApplicationInfo");
11489 if (ai == null) {
11490 Slog.w(TAG, "No package info for content provider "
11491 + cpi.name);
11492 return null;
11493 }
11494 ai = getAppInfoForUser(ai, userId);
11495 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
11496 } catch (RemoteException ex) {
11497 // pm is in same process, this will never happen.
11498 } finally {
11499 Binder.restoreCallingIdentity(ident);
11500 }
11501 }
11502
11503 checkTime(startTime, "getContentProviderImpl: now have ContentProviderRecord");
11504
11505 if (r != null && cpr.canRunHere(r)) {
11506 // If this is a multiprocess provider, then just return its
11507 // info and allow the caller to instantiate it. Only do
11508 // this if the provider is the same user as the caller's
11509 // process, or can run as root (so can be in any process).
11510 return cpr.newHolder(null);
11511 }
11512
11513 if (DEBUG_PROVIDER) Slog.w(TAG_PROVIDER, "LAUNCHING REMOTE PROVIDER (myuid "
11514 + (r != null ? r.uid : null) + " pruid " + cpr.appInfo.uid + "): "
11515 + cpr.info.name + " callers=" + Debug.getCallers(6));
11516
11517 // This is single process, and our app is now connecting to it.
11518 // See if we are already in the process of launching this
11519 // provider.
11520 final int N = mLaunchingProviders.size();
11521 int i;
11522 for (i = 0; i < N; i++) {
11523 if (mLaunchingProviders.get(i) == cpr) {
11524 break;
11525 }
11526 }
11527
11528 // If the provider is not already being launched, then get it
11529 // started.
11530 if (i >= N) {
11531 final long origId = Binder.clearCallingIdentity();
11532
11533 try {
11534 // Content provider is now in use, its package can't be stopped.
11535 try {
11536 checkTime(startTime, "getContentProviderImpl: before set stopped state");
11537 AppGlobals.getPackageManager().setPackageStoppedState(
11538 cpr.appInfo.packageName, false, userId);
11539 checkTime(startTime, "getContentProviderImpl: after set stopped state");
11540 } catch (RemoteException e) {
11541 } catch (IllegalArgumentException e) {
11542 Slog.w(TAG, "Failed trying to unstop package "
11543 + cpr.appInfo.packageName + ": " + e);
11544 }
11545
11546 // Use existing process if already started
11547 checkTime(startTime, "getContentProviderImpl: looking for process record");
11548 ProcessRecord proc = getProcessRecordLocked(
11549 cpi.processName, cpr.appInfo.uid, false);
11550 if (proc != null && proc.thread != null && !proc.killed) {
11551 if (DEBUG_PROVIDER) Slog.d(TAG_PROVIDER,
11552 "Installing in existing process " + proc);
11553 if (!proc.pubProviders.containsKey(cpi.name)) {
11554 checkTime(startTime, "getContentProviderImpl: scheduling install");
11555 proc.pubProviders.put(cpi.name, cpr);
11556 try {
11557 proc.thread.scheduleInstallProvider(cpi);
11558 } catch (RemoteException e) {
11559 }
11560 }
11561 } else {
11562 checkTime(startTime, "getContentProviderImpl: before start process");
11563 proc = startProcessLocked(cpi.processName,
11564 cpr.appInfo, false, 0, "content provider",
11565 new ComponentName(cpi.applicationInfo.packageName,
11566 cpi.name), false, false, false);
11567 checkTime(startTime, "getContentProviderImpl: after start process");
11568 if (proc == null) {
11569 Slog.w(TAG, "Unable to launch app "
11570 + cpi.applicationInfo.packageName + "/"
11571 + cpi.applicationInfo.uid + " for provider "
11572 + name + ": process is bad");
11573 return null;
11574 }
11575 }
11576 cpr.launchingApp = proc;
11577 mLaunchingProviders.add(cpr);
11578 } finally {
11579 Binder.restoreCallingIdentity(origId);
11580 }
11581 }
11582
11583 checkTime(startTime, "getContentProviderImpl: updating data structures");
11584
11585 // Make sure the provider is published (the same provider class
11586 // may be published under multiple names).
11587 if (firstClass) {
11588 mProviderMap.putProviderByClass(comp, cpr);
11589 }
11590
11591 mProviderMap.putProviderByName(name, cpr);
11592 conn = incProviderCountLocked(r, cpr, token, stable);
11593 if (conn != null) {
11594 conn.waiting = true;
11595 }
11596 }
11597 checkTime(startTime, "getContentProviderImpl: done!");
11598
11599 grantEphemeralAccessLocked(userId, null /*intent*/,
11600 cpi.applicationInfo.uid, UserHandle.getAppId(Binder.getCallingUid()));
11601 }
11602
11603 // Wait for the provider to be published...
11604 synchronized (cpr) {
11605 while (cpr.provider == null) {
11606 if (cpr.launchingApp == null) {
11607 Slog.w(TAG, "Unable to launch app "
11608 + cpi.applicationInfo.packageName + "/"
11609 + cpi.applicationInfo.uid + " for provider "
11610 + name + ": launching app became null");
11611 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
11612 UserHandle.getUserId(cpi.applicationInfo.uid),
11613 cpi.applicationInfo.packageName,
11614 cpi.applicationInfo.uid, name);
11615 return null;
11616 }
11617 try {
11618 if (DEBUG_MU) Slog.v(TAG_MU,
11619 "Waiting to start provider " + cpr
11620 + " launchingApp=" + cpr.launchingApp);
11621 if (conn != null) {
11622 conn.waiting = true;
11623 }
11624 cpr.wait();
11625 } catch (InterruptedException ex) {
11626 } finally {
11627 if (conn != null) {
11628 conn.waiting = false;
11629 }
11630 }
11631 }
11632 }
11633 return cpr != null ? cpr.newHolder(conn) : null;
11634 }
11635
11636 private boolean requestTargetProviderPermissionsReviewIfNeededLocked(ProviderInfo cpi,
11637 ProcessRecord r, final int userId) {
11638 if (getPackageManagerInternalLocked().isPermissionsReviewRequired(
11639 cpi.packageName, userId)) {
11640
11641 final boolean callerForeground = r == null || r.setSchedGroup
11642 != ProcessList.SCHED_GROUP_BACKGROUND;
11643
11644 // Show a permission review UI only for starting from a foreground app
11645 if (!callerForeground) {
11646 Slog.w(TAG, "u" + userId + " Instantiating a provider in package"
11647 + cpi.packageName + " requires a permissions review");
11648 return false;
11649 }
11650
11651 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
11652 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
11653 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
11654 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, cpi.packageName);
11655
11656 if (DEBUG_PERMISSIONS_REVIEW) {
11657 Slog.i(TAG, "u" + userId + " Launching permission review "
11658 + "for package " + cpi.packageName);
11659 }
11660
11661 final UserHandle userHandle = new UserHandle(userId);
11662 mHandler.post(new Runnable() {
11663 @Override
11664 public void run() {
11665 mContext.startActivityAsUser(intent, userHandle);
11666 }
11667 });
11668
11669 return false;
11670 }
11671
11672 return true;
11673 }
11674
11675 PackageManagerInternal getPackageManagerInternalLocked() {
11676 if (mPackageManagerInt == null) {
11677 mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class);
11678 }
11679 return mPackageManagerInt;
11680 }
11681
11682 @Override
11683 public final ContentProviderHolder getContentProvider(
11684 IApplicationThread caller, String name, int userId, boolean stable) {
11685 enforceNotIsolatedCaller("getContentProvider");
11686 if (caller == null) {
11687 String msg = "null IApplicationThread when getting content provider "
11688 + name;
11689 Slog.w(TAG, msg);
11690 throw new SecurityException(msg);
11691 }
11692 // The incoming user check is now handled in checkContentProviderPermissionLocked() to deal
11693 // with cross-user grant.
11694 return getContentProviderImpl(caller, name, null, stable, userId);
11695 }
11696
11697 public ContentProviderHolder getContentProviderExternal(
11698 String name, int userId, IBinder token) {
11699 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
11700 "Do not have permission in call getContentProviderExternal()");
11701 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
11702 userId, false, ALLOW_FULL_ONLY, "getContentProvider", null);
11703 return getContentProviderExternalUnchecked(name, token, userId);
11704 }
11705
11706 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
11707 IBinder token, int userId) {
11708 return getContentProviderImpl(null, name, token, true, userId);
11709 }
11710
11711 /**
11712 * Drop a content provider from a ProcessRecord's bookkeeping
11713 */
11714 public void removeContentProvider(IBinder connection, boolean stable) {
11715 enforceNotIsolatedCaller("removeContentProvider");
11716 long ident = Binder.clearCallingIdentity();
11717 try {
11718 synchronized (this) {
11719 ContentProviderConnection conn;
11720 try {
11721 conn = (ContentProviderConnection)connection;
11722 } catch (ClassCastException e) {
11723 String msg ="removeContentProvider: " + connection
11724 + " not a ContentProviderConnection";
11725 Slog.w(TAG, msg);
11726 throw new IllegalArgumentException(msg);
11727 }
11728 if (conn == null) {
11729 throw new NullPointerException("connection is null");
11730 }
11731 if (decProviderCountLocked(conn, null, null, stable)) {
11732 updateOomAdjLocked();
11733 }
11734 }
11735 } finally {
11736 Binder.restoreCallingIdentity(ident);
11737 }
11738 }
11739
11740 public void removeContentProviderExternal(String name, IBinder token) {
11741 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
11742 "Do not have permission in call removeContentProviderExternal()");
11743 int userId = UserHandle.getCallingUserId();
11744 long ident = Binder.clearCallingIdentity();
11745 try {
11746 removeContentProviderExternalUnchecked(name, token, userId);
11747 } finally {
11748 Binder.restoreCallingIdentity(ident);
11749 }
11750 }
11751
11752 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
11753 synchronized (this) {
11754 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
11755 if(cpr == null) {
11756 //remove from mProvidersByClass
11757 if(DEBUG_ALL) Slog.v(TAG, name+" content provider not found in providers list");
11758 return;
11759 }
11760
11761 //update content provider record entry info
11762 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
11763 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
11764 if (localCpr.hasExternalProcessHandles()) {
11765 if (localCpr.removeExternalProcessHandleLocked(token)) {
11766 updateOomAdjLocked();
11767 } else {
11768 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
11769 + " with no external reference for token: "
11770 + token + ".");
11771 }
11772 } else {
11773 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
11774 + " with no external references.");
11775 }
11776 }
11777 }
11778
11779 public final void publishContentProviders(IApplicationThread caller,
11780 List<ContentProviderHolder> providers) {
11781 if (providers == null) {
11782 return;
11783 }
11784
11785 enforceNotIsolatedCaller("publishContentProviders");
11786 synchronized (this) {
11787 final ProcessRecord r = getRecordForAppLocked(caller);
11788 if (DEBUG_MU) Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
11789 if (r == null) {
11790 throw new SecurityException(
11791 "Unable to find app for caller " + caller
11792 + " (pid=" + Binder.getCallingPid()
11793 + ") when publishing content providers");
11794 }
11795
11796 final long origId = Binder.clearCallingIdentity();
11797
11798 final int N = providers.size();
11799 for (int i = 0; i < N; i++) {
11800 ContentProviderHolder src = providers.get(i);
11801 if (src == null || src.info == null || src.provider == null) {
11802 continue;
11803 }
11804 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
11805 if (DEBUG_MU) Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
11806 if (dst != null) {
11807 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
11808 mProviderMap.putProviderByClass(comp, dst);
11809 String names[] = dst.info.authority.split(";");
11810 for (int j = 0; j < names.length; j++) {
11811 mProviderMap.putProviderByName(names[j], dst);
11812 }
11813
11814 int launchingCount = mLaunchingProviders.size();
11815 int j;
11816 boolean wasInLaunchingProviders = false;
11817 for (j = 0; j < launchingCount; j++) {
11818 if (mLaunchingProviders.get(j) == dst) {
11819 mLaunchingProviders.remove(j);
11820 wasInLaunchingProviders = true;
11821 j--;
11822 launchingCount--;
11823 }
11824 }
11825 if (wasInLaunchingProviders) {
11826 mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, r);
11827 }
11828 synchronized (dst) {
11829 dst.provider = src.provider;
11830 dst.proc = r;
11831 dst.notifyAll();
11832 }
11833 updateOomAdjLocked(r, true);
11834 maybeUpdateProviderUsageStatsLocked(r, src.info.packageName,
11835 src.info.authority);
11836 }
11837 }
11838
11839 Binder.restoreCallingIdentity(origId);
11840 }
11841 }
11842
11843 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
11844 ContentProviderConnection conn;
11845 try {
11846 conn = (ContentProviderConnection)connection;
11847 } catch (ClassCastException e) {
11848 String msg ="refContentProvider: " + connection
11849 + " not a ContentProviderConnection";
11850 Slog.w(TAG, msg);
11851 throw new IllegalArgumentException(msg);
11852 }
11853 if (conn == null) {
11854 throw new NullPointerException("connection is null");
11855 }
11856
11857 synchronized (this) {
11858 if (stable > 0) {
11859 conn.numStableIncs += stable;
11860 }
11861 stable = conn.stableCount + stable;
11862 if (stable < 0) {
11863 throw new IllegalStateException("stableCount < 0: " + stable);
11864 }
11865
11866 if (unstable > 0) {
11867 conn.numUnstableIncs += unstable;
11868 }
11869 unstable = conn.unstableCount + unstable;
11870 if (unstable < 0) {
11871 throw new IllegalStateException("unstableCount < 0: " + unstable);
11872 }
11873
11874 if ((stable+unstable) <= 0) {
11875 throw new IllegalStateException("ref counts can't go to zero here: stable="
11876 + stable + " unstable=" + unstable);
11877 }
11878 conn.stableCount = stable;
11879 conn.unstableCount = unstable;
11880 return !conn.dead;
11881 }
11882 }
11883
11884 public void unstableProviderDied(IBinder connection) {
11885 ContentProviderConnection conn;
11886 try {
11887 conn = (ContentProviderConnection)connection;
11888 } catch (ClassCastException e) {
11889 String msg ="refContentProvider: " + connection
11890 + " not a ContentProviderConnection";
11891 Slog.w(TAG, msg);
11892 throw new IllegalArgumentException(msg);
11893 }
11894 if (conn == null) {
11895 throw new NullPointerException("connection is null");
11896 }
11897
11898 // Safely retrieve the content provider associated with the connection.
11899 IContentProvider provider;
11900 synchronized (this) {
11901 provider = conn.provider.provider;
11902 }
11903
11904 if (provider == null) {
11905 // Um, yeah, we're way ahead of you.
11906 return;
11907 }
11908
11909 // Make sure the caller is being honest with us.
11910 if (provider.asBinder().pingBinder()) {
11911 // Er, no, still looks good to us.
11912 synchronized (this) {
11913 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
11914 + " says " + conn + " died, but we don't agree");
11915 return;
11916 }
11917 }
11918
11919 // Well look at that! It's dead!
11920 synchronized (this) {
11921 if (conn.provider.provider != provider) {
11922 // But something changed... good enough.
11923 return;
11924 }
11925
11926 ProcessRecord proc = conn.provider.proc;
11927 if (proc == null || proc.thread == null) {
11928 // Seems like the process is already cleaned up.
11929 return;
11930 }
11931
11932 // As far as we're concerned, this is just like receiving a
11933 // death notification... just a bit prematurely.
11934 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
11935 + ") early provider death");
11936 final long ident = Binder.clearCallingIdentity();
11937 try {
11938 appDiedLocked(proc);
11939 } finally {
11940 Binder.restoreCallingIdentity(ident);
11941 }
11942 }
11943 }
11944
11945 @Override
11946 public void appNotRespondingViaProvider(IBinder connection) {
11947 enforceCallingPermission(
11948 android.Manifest.permission.REMOVE_TASKS, "appNotRespondingViaProvider()");
11949
11950 final ContentProviderConnection conn = (ContentProviderConnection) connection;
11951 if (conn == null) {
11952 Slog.w(TAG, "ContentProviderConnection is null");
11953 return;
11954 }
11955
11956 final ProcessRecord host = conn.provider.proc;
11957 if (host == null) {
11958 Slog.w(TAG, "Failed to find hosting ProcessRecord");
11959 return;
11960 }
11961
11962 mHandler.post(new Runnable() {
11963 @Override
11964 public void run() {
11965 mAppErrors.appNotResponding(host, null, null, false,
11966 "ContentProvider not responding");
11967 }
11968 });
11969 }
11970
11971 public final void installSystemProviders() {
11972 List<ProviderInfo> providers;
11973 synchronized (this) {
11974 ProcessRecord app = mProcessNames.get("system", SYSTEM_UID);
11975 providers = generateApplicationProvidersLocked(app);
11976 if (providers != null) {
11977 for (int i=providers.size()-1; i>=0; i--) {
11978 ProviderInfo pi = (ProviderInfo)providers.get(i);
11979 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
11980 Slog.w(TAG, "Not installing system proc provider " + pi.name
11981 + ": not system .apk");
11982 providers.remove(i);
11983 }
11984 }
11985 }
11986 }
11987 if (providers != null) {
11988 mSystemThread.installSystemProviders(providers);
11989 }
11990
11991 mConstants.start(mContext.getContentResolver());
11992 mCoreSettingsObserver = new CoreSettingsObserver(this);
11993 mFontScaleSettingObserver = new FontScaleSettingObserver();
11994
11995 // Now that the settings provider is published we can consider sending
11996 // in a rescue party.
11997 RescueParty.onSettingsProviderPublished(mContext);
11998
11999 //mUsageStatsService.monitorPackages();
12000 }
12001
12002 private void startPersistentApps(int matchFlags) {
12003 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return;
12004
12005 synchronized (this) {
12006 try {
12007 final List<ApplicationInfo> apps = AppGlobals.getPackageManager()
12008 .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList();
12009 for (ApplicationInfo app : apps) {
12010 if (!"android".equals(app.packageName)) {
12011 addAppLocked(app, null, false, null /* ABI override */);
12012 }
12013 }
12014 } catch (RemoteException ex) {
12015 }
12016 }
12017 }
12018
12019 /**
12020 * When a user is unlocked, we need to install encryption-unaware providers
12021 * belonging to any running apps.
12022 */
12023 private void installEncryptionUnawareProviders(int userId) {
12024 // We're only interested in providers that are encryption unaware, and
12025 // we don't care about uninstalled apps, since there's no way they're
12026 // running at this point.
12027 final int matchFlags = GET_PROVIDERS | MATCH_DIRECT_BOOT_UNAWARE;
12028
12029 synchronized (this) {
12030 final int NP = mProcessNames.getMap().size();
12031 for (int ip = 0; ip < NP; ip++) {
12032 final SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
12033 final int NA = apps.size();
12034 for (int ia = 0; ia < NA; ia++) {
12035 final ProcessRecord app = apps.valueAt(ia);
12036 if (app.userId != userId || app.thread == null || app.unlocked) continue;
12037
12038 final int NG = app.pkgList.size();
12039 for (int ig = 0; ig < NG; ig++) {
12040 try {
12041 final String pkgName = app.pkgList.keyAt(ig);
12042 final PackageInfo pkgInfo = AppGlobals.getPackageManager()
12043 .getPackageInfo(pkgName, matchFlags, userId);
12044 if (pkgInfo != null && !ArrayUtils.isEmpty(pkgInfo.providers)) {
12045 for (ProviderInfo pi : pkgInfo.providers) {
12046 // TODO: keep in sync with generateApplicationProvidersLocked
12047 final boolean processMatch = Objects.equals(pi.processName,
12048 app.processName) || pi.multiprocess;
12049 final boolean userMatch = isSingleton(pi.processName,
12050 pi.applicationInfo, pi.name, pi.flags)
12051 ? (app.userId == UserHandle.USER_SYSTEM) : true;
12052 if (processMatch && userMatch) {
12053 Log.v(TAG, "Installing " + pi);
12054 app.thread.scheduleInstallProvider(pi);
12055 } else {
12056 Log.v(TAG, "Skipping " + pi);
12057 }
12058 }
12059 }
12060 } catch (RemoteException ignored) {
12061 }
12062 }
12063 }
12064 }
12065 }
12066 }
12067
12068 /**
12069 * Allows apps to retrieve the MIME type of a URI.
12070 * If an app is in the same user as the ContentProvider, or if it is allowed to interact across
12071 * users, then it does not need permission to access the ContentProvider.
12072 * Either, it needs cross-user uri grants.
12073 *
12074 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
12075 *
12076 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
12077 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
12078 */
12079 public String getProviderMimeType(Uri uri, int userId) {
12080 enforceNotIsolatedCaller("getProviderMimeType");
12081 final String name = uri.getAuthority();
12082 int callingUid = Binder.getCallingUid();
12083 int callingPid = Binder.getCallingPid();
12084 long ident = 0;
12085 boolean clearedIdentity = false;
12086 synchronized (this) {
12087 userId = mUserController.unsafeConvertIncomingUserLocked(userId);
12088 }
12089 if (canClearIdentity(callingPid, callingUid, userId)) {
12090 clearedIdentity = true;
12091 ident = Binder.clearCallingIdentity();
12092 }
12093 ContentProviderHolder holder = null;
12094 try {
12095 holder = getContentProviderExternalUnchecked(name, null, userId);
12096 if (holder != null) {
12097 return holder.provider.getType(uri);
12098 }
12099 } catch (RemoteException e) {
12100 Log.w(TAG, "Content provider dead retrieving " + uri, e);
12101 return null;
12102 } catch (Exception e) {
12103 Log.w(TAG, "Exception while determining type of " + uri, e);
12104 return null;
12105 } finally {
12106 // We need to clear the identity to call removeContentProviderExternalUnchecked
12107 if (!clearedIdentity) {
12108 ident = Binder.clearCallingIdentity();
12109 }
12110 try {
12111 if (holder != null) {
12112 removeContentProviderExternalUnchecked(name, null, userId);
12113 }
12114 } finally {
12115 Binder.restoreCallingIdentity(ident);
12116 }
12117 }
12118
12119 return null;
12120 }
12121
12122 private boolean canClearIdentity(int callingPid, int callingUid, int userId) {
12123 if (UserHandle.getUserId(callingUid) == userId) {
12124 return true;
12125 }
12126 if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
12127 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
12128 || checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
12129 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
12130 return true;
12131 }
12132 return false;
12133 }

创建新的process record

 12135    // =========================================================
12136 // GLOBAL MANAGEMENT
12137 // =========================================================
12138
12139 final ProcessRecord newProcessRecordLocked(ApplicationInfo info, String customProcess,
12140 boolean isolated, int isolatedUid) {
12141 String proc = customProcess != null ? customProcess : info.processName;
12142 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12143 final int userId = UserHandle.getUserId(info.uid);
12144 int uid = info.uid;
12145 if (isolated) {
12146 if (isolatedUid == 0) {
12147 int stepsLeft = LAST_ISOLATED_UID - FIRST_ISOLATED_UID + 1;
12148 while (true) {
12149 if (mNextIsolatedProcessUid < FIRST_ISOLATED_UID
12150 || mNextIsolatedProcessUid > LAST_ISOLATED_UID) {
12151 mNextIsolatedProcessUid = FIRST_ISOLATED_UID;
12152 }
12153 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
12154 mNextIsolatedProcessUid++;
12155 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
12156 // No process for this uid, use it.
12157 break;
12158 }
12159 stepsLeft--;
12160 if (stepsLeft <= 0) {
12161 return null;
12162 }
12163 }
12164 } else {
12165 // Special case for startIsolatedProcess (internal only), where
12166 // the uid of the isolated process is specified by the caller.
12167 uid = isolatedUid;
12168 }
12169 getPackageManagerInternalLocked().addIsolatedUid(uid, info.uid);
12170
12171 // Register the isolated UID with this application so BatteryStats knows to
12172 // attribute resource usage to the application.
12173 //
12174 // NOTE: This is done here before addProcessNameLocked, which will tell BatteryStats
12175 // about the process state of the isolated UID *before* it is registered with the
12176 // owning application.
12177 mBatteryStatsService.addIsolatedUid(uid, info.uid);
12178 }
12179 final ProcessRecord r = new ProcessRecord(stats, info, proc, uid);
12180 if (!mBooted && !mBooting
12181 && userId == UserHandle.USER_SYSTEM
12182 && (info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) {
12183 r.persistent = true;
12184 r.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
12185 }
12186 addProcessNameLocked(r);
12187 return r;
12188 }

后台白名单相关

 12190    private boolean uidOnBackgroundWhitelist(final int uid) {
12191 final int appId = UserHandle.getAppId(uid);
12192 final int[] whitelist = mBackgroundAppIdWhitelist;
12193 final int N = whitelist.length;
12194 for (int i = 0; i < N; i++) {
12195 if (appId == whitelist[i]) {
12196 return true;
12197 }
12198 }
12199 return false;
12200 }
12201
12202 @Override
12203 public void backgroundWhitelistUid(final int uid) {
12204 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
12205 throw new SecurityException("Only the OS may call backgroundWhitelistUid()");
12206 }
12207
12208 if (DEBUG_BACKGROUND_CHECK) {
12209 Slog.i(TAG, "Adding uid " + uid + " to bg uid whitelist");
12210 }
12211 synchronized (this) {
12212 final int N = mBackgroundAppIdWhitelist.length;
12213 int[] newList = new int[N+1];
12214 System.arraycopy(mBackgroundAppIdWhitelist, 0, newList, 0, N);
12215 newList[N] = UserHandle.getAppId(uid);
12216 mBackgroundAppIdWhitelist = newList;
12217 }
12218 }

添加app

 12220    final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
12221 String abiOverride) {
12222 ProcessRecord app;
12223 if (!isolated) {
12224 app = getProcessRecordLocked(customProcess != null ? customProcess : info.processName,
12225 info.uid, true);
12226 } else {
12227 app = null;
12228 }
12229
12230 if (app == null) {
12231 app = newProcessRecordLocked(info, customProcess, isolated, 0);
12232 updateLruProcessLocked(app, false, null);
12233 updateOomAdjLocked();
12234 }
12235
12236 // This package really, really can not be stopped.
12237 try {
12238 AppGlobals.getPackageManager().setPackageStoppedState(
12239 info.packageName, false, UserHandle.getUserId(app.uid));
12240 } catch (RemoteException e) {
12241 } catch (IllegalArgumentException e) {
12242 Slog.w(TAG, "Failed trying to unstop package "
12243 + info.packageName + ": " + e);
12244 }
12245
12246 if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) {
12247 app.persistent = true;
12248 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
12249 }
12250 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
12251 mPersistentStartingProcesses.add(app);
12252 startProcessLocked(app, "added application",
12253 customProcess != null ? customProcess : app.processName, abiOverride,
12254 null /* entryPoint */, null /* entryPointArgs */);
12255 }
12256
12257 return app;
12258 }
12259

un handle back

 12260    public void unhandledBack() {
12261 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
12262 "unhandledBack()");
12263
12264 synchronized(this) {
12265 final long origId = Binder.clearCallingIdentity();
12266 try {
12267 getFocusedStack().unhandledBackLocked();
12268 } finally {
12269 Binder.restoreCallingIdentity(origId);
12270 }
12271 }
12272 }

打开content uri

 12274    public ParcelFileDescriptor openContentUri(String uriString) throws RemoteException {
12275 enforceNotIsolatedCaller("openContentUri");
12276 final int userId = UserHandle.getCallingUserId();
12277 final Uri uri = Uri.parse(uriString);
12278 String name = uri.getAuthority();
12279 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
12280 ParcelFileDescriptor pfd = null;
12281 if (cph != null) {
12282 // We record the binder invoker's uid in thread-local storage before
12283 // going to the content provider to open the file. Later, in the code
12284 // that handles all permissions checks, we look for this uid and use
12285 // that rather than the Activity Manager's own uid. The effect is that
12286 // we do the check against the caller's permissions even though it looks
12287 // to the content provider like the Activity Manager itself is making
12288 // the request.
12289 Binder token = new Binder();
12290 sCallerIdentity.set(new Identity(
12291 token, Binder.getCallingPid(), Binder.getCallingUid()));
12292 try {
12293 pfd = cph.provider.openFile(null, uri, "r", null, token);
12294 } catch (FileNotFoundException e) {
12295 // do nothing; pfd will be returned null
12296 } finally {
12297 // Ensure that whatever happens, we clean up the identity state
12298 sCallerIdentity.remove();
12299 // Ensure we're done with the provider.
12300 removeContentProviderExternalUnchecked(name, null, userId);
12301 }
12302 } else {
12303 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
12304 }
12305 return pfd;
12306 }

睡眠唤醒状态

 12308    // Actually is sleeping or shutting down or whatever else in the future
12309 // is an inactive state.
12310 boolean isSleepingOrShuttingDownLocked() {
12311 return isSleepingLocked() || mShuttingDown;
12312 }
12313
12314 boolean isShuttingDownLocked() {
12315 return mShuttingDown;
12316 }
12317
12318 boolean isSleepingLocked() {
12319 return mSleeping;
12320 }
12321
12322 void onWakefulnessChanged(int wakefulness) {
12323 synchronized(this) {
12324 mWakefulness = wakefulness;
12325 updateSleepIfNeededLocked();
12326 }
12327 }

结束运行的语音

 12329    void finishRunningVoiceLocked() {
12330 if (mRunningVoice != null) {
12331 mRunningVoice = null;
12332 mVoiceWakeLock.release();
12333 updateSleepIfNeededLocked();
12334 }
12335 }

开始track focused activity time

 12337    void startTimeTrackingFocusedActivityLocked() {
12338 final ActivityRecord resumedActivity = mStackSupervisor.getResumedActivityLocked();
12339 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
12340 mCurAppTimeTracker.start(resumedActivity.packageName);
12341 }
12342 }

睡眠相关

 12344    void updateSleepIfNeededLocked() {
12345 final boolean shouldSleep = shouldSleepLocked();
12346 if (mSleeping && !shouldSleep) {
12347 mSleeping = false;
12348 startTimeTrackingFocusedActivityLocked();
12349 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
12350 mStackSupervisor.comeOutOfSleepIfNeededLocked();
12351 sendNotifyVrManagerOfSleepState(false);
12352 updateOomAdjLocked();
12353 } else if (!mSleeping && shouldSleep) {
12354 mSleeping = true;
12355 if (mCurAppTimeTracker != null) {
12356 mCurAppTimeTracker.stop();
12357 }
12358 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
12359 mStackSupervisor.goingToSleepLocked();
12360 sendNotifyVrManagerOfSleepState(true);
12361 updateOomAdjLocked();
12362
12363 // Initialize the wake times of all processes.
12364 checkExcessivePowerUsageLocked(false);
12365 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
12366 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
12367 mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_DELAY);
12368 }
12369
12370 // Also update state in a special way for running foreground services UI.
12371 switch (mWakefulness) {
12372 case PowerManagerInternal.WAKEFULNESS_ASLEEP:
12373 case PowerManagerInternal.WAKEFULNESS_DREAMING:
12374 case PowerManagerInternal.WAKEFULNESS_DOZING:
12375 mServices.updateScreenStateLocked(false);
12376 break;
12377 case PowerManagerInternal.WAKEFULNESS_AWAKE:
12378 default:
12379 mServices.updateScreenStateLocked(true);
12380 break;
12381 }
12382 }
12383
12384 private boolean shouldSleepLocked() {
12385 // Resume applications while running a voice interactor.
12386 if (mRunningVoice != null) {
12387 return false;
12388 }
12389
12390 // TODO: Transform the lock screen state into a sleep token instead.
12391 switch (mWakefulness) {
12392 case PowerManagerInternal.WAKEFULNESS_AWAKE:
12393 case PowerManagerInternal.WAKEFULNESS_DREAMING:
12394 case PowerManagerInternal.WAKEFULNESS_DOZING:
12395 // Pause applications whenever the lock screen is shown or any sleep
12396 // tokens have been acquired.
12397 return mKeyguardController.isKeyguardShowing() || !mSleepTokens.isEmpty();
12398 case PowerManagerInternal.WAKEFULNESS_ASLEEP:
12399 default:
12400 // If we're asleep then pause applications unconditionally.
12401 return true;
12402 }
12403 }

通知 task持久化,task动画开始结束,清空网络

 12405    /** Pokes the task persister. */
12406 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
12407 mRecentTasks.notifyTaskPersisterLocked(task, flush);
12408 }
12409
12410 /**
12411 * Notifies all listeners when the pinned stack animation starts.
12412 */
12413 @Override
12414 public void notifyPinnedStackAnimationStarted() {
12415 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
12416 }
12417
12418 /**
12419 * Notifies all listeners when the pinned stack animation ends.
12420 */
12421 @Override
12422 public void notifyPinnedStackAnimationEnded() {
12423 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
12424 }
12425
12426 @Override
12427 public void notifyCleartextNetwork(int uid, byte[] firstPacket) {
12428 mHandler.obtainMessage(NOTIFY_CLEARTEXT_NETWORK_MSG, uid, 0, firstPacket).sendToTarget();
12429 }

关机

 12431    @Override
12432 public boolean shutdown(int timeout) {
12433 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
12434 != PackageManager.PERMISSION_GRANTED) {
12435 throw new SecurityException("Requires permission "
12436 + android.Manifest.permission.SHUTDOWN);
12437 }
12438
12439 boolean timedout = false;
12440
12441 synchronized(this) {
12442 mShuttingDown = true;
12443 updateEventDispatchingLocked();
12444 timedout = mStackSupervisor.shutdownLocked(timeout);
12445 }
12446
12447 mAppOpsService.shutdown();
12448 if (mUsageStatsService != null) {
12449 mUsageStatsService.prepareShutdown();
12450 }
12451 mBatteryStatsService.shutdown();
12452 synchronized (this) {
12453 mProcessStats.shutdownLocked();
12454 notifyTaskPersisterLocked(null, true);
12455 }
12456
12457 return timedout;
12458 }

activity休眠

 12460    public final void activitySlept(IBinder token) {
12461 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
12462
12463 final long origId = Binder.clearCallingIdentity();
12464
12465 synchronized (this) {
12466 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
12467 if (r != null) {
12468 mStackSupervisor.activitySleptLocked(r);
12469 }
12470 }
12471
12472 Binder.restoreCallingIdentity(origId);
12473 }

开始运行voice

 12475    void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
12476 Slog.d(TAG, "<<< startRunningVoiceLocked()");
12477 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
12478 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
12479 boolean wasRunningVoice = mRunningVoice != null;
12480 mRunningVoice = session;
12481 if (!wasRunningVoice) {
12482 mVoiceWakeLock.acquire();
12483 updateSleepIfNeededLocked();
12484 }
12485 }
12486 }

更新事件发送

 12488    private void updateEventDispatchingLocked() {
12489 mWindowManager.setEventDispatching(mBooted && !mShuttingDown);
12490 }
12491

设置锁屏

 12492    @Override
12493 public void setLockScreenShown(boolean showing) {
12494 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
12495 != PackageManager.PERMISSION_GRANTED) {
12496 throw new SecurityException("Requires permission "
12497 + android.Manifest.permission.DEVICE_POWER);
12498 }
12499
12500 synchronized(this) {
12501 long ident = Binder.clearCallingIdentity();
12502 try {
12503 mKeyguardController.setKeyguardShown(showing);
12504 } finally {
12505 Binder.restoreCallingIdentity(ident);
12506 }
12507 }
12508 }

通知锁住了配置文件

 12510    @Override
12511 public void notifyLockedProfile(@UserIdInt int userId) {
12512 try {
12513 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
12514 throw new SecurityException("Only privileged app can call notifyLockedProfile");
12515 }
12516 } catch (RemoteException ex) {
12517 throw new SecurityException("Fail to check is caller a privileged app", ex);
12518 }
12519
12520 synchronized (this) {
12521 final long ident = Binder.clearCallingIdentity();
12522 try {
12523 if (mUserController.shouldConfirmCredentials(userId)) {
12524 if (mKeyguardController.isKeyguardLocked()) {
12525 // Showing launcher to avoid user entering credential twice.
12526 final int currentUserId = mUserController.getCurrentUserIdLocked();
12527 startHomeActivityLocked(currentUserId, "notifyLockedProfile");
12528 }
12529 mStackSupervisor.lockAllProfileTasks(userId);
12530 }
12531 } finally {
12532 Binder.restoreCallingIdentity(ident);
12533 }
12534 }
12535 }

开始确认设备可信任

 12537    @Override
12538 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
12539 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
12540 synchronized (this) {
12541 final long ident = Binder.clearCallingIdentity();
12542 try {
12543 mActivityStarter.startConfirmCredentialIntent(intent, options);
12544 } finally {
12545 Binder.restoreCallingIdentity(ident);
12546 }
12547 }
12548 }

app切换相关

 12550    @Override
12551 public void stopAppSwitches() {
12552 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
12553 != PackageManager.PERMISSION_GRANTED) {
12554 throw new SecurityException("viewquires permission "
12555 + android.Manifest.permission.STOP_APP_SWITCHES);
12556 }
12557
12558 synchronized(this) {
12559 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
12560 + APP_SWITCH_DELAY_TIME;
12561 mDidAppSwitch = false;
12562 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
12563 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
12564 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
12565 }
12566 }
12567
12568 public void resumeAppSwitches() {
12569 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
12570 != PackageManager.PERMISSION_GRANTED) {
12571 throw new SecurityException("Requires permission "
12572 + android.Manifest.permission.STOP_APP_SWITCHES);
12573 }
12574
12575 synchronized(this) {
12576 // Note that we don't execute any pending app switches... we will
12577 // let those wait until either the timeout, or the next start
12578 // activity request.
12579 mAppSwitchesAllowedTime = 0;
12580 }
12581 }
12582
12583 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
12584 int callingPid, int callingUid, String name) {
12585 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
12586 return true;
12587 }
12588
12589 int perm = checkComponentPermission(
12590 android.Manifest.permission.STOP_APP_SWITCHES, sourcePid,
12591 sourceUid, -1, true);
12592 if (perm == PackageManager.PERMISSION_GRANTED) {
12593 return true;
12594 }
12595
12596 // If the actual IPC caller is different from the logical source, then
12597 // also see if they are allowed to control app switches.
12598 if (callingUid != -1 && callingUid != sourceUid) {
12599 perm = checkComponentPermission(
12600 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
12601 callingUid, -1, true);
12602 if (perm == PackageManager.PERMISSION_GRANTED) {
12603 return true;
12604 }
12605 }
12606
12607 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
12608 return false;
12609 }

设置debug app

 12611    public void setDebugApp(String packageName, boolean waitForDebugger,
12612 boolean persistent) {
12613 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
12614 "setDebugApp()");
12615
12616 long ident = Binder.clearCallingIdentity();
12617 try {
12618 // Note that this is not really thread safe if there are multiple
12619 // callers into it at the same time, but that's not a situation we
12620 // care about.
12621 if (persistent) {
12622 final ContentResolver resolver = mContext.getContentResolver();
12623 Settings.Global.putString(
12624 resolver, Settings.Global.DEBUG_APP,
12625 packageName);
12626 Settings.Global.putInt(
12627 resolver, Settings.Global.WAIT_FOR_DEBUGGER,
12628 waitForDebugger ? 1 : 0);
12629 }
12630
12631 synchronized (this) {
12632 if (!persistent) {
12633 mOrigDebugApp = mDebugApp;
12634 mOrigWaitForDebugger = mWaitForDebugger;
12635 }
12636 mDebugApp = packageName;
12637 mWaitForDebugger = waitForDebugger;
12638 mDebugTransient = !persistent;
12639 if (packageName != null) {
12640 forceStopPackageLocked(packageName, -1, false, false, true, true,
12641 false, UserHandle.USER_ALL, "set debug app");
12642 }
12643 }
12644 } finally {
12645 Binder.restoreCallingIdentity(ident);
12646 }
12647 }

debug相关

 12649    void setTrackAllocationApp(ApplicationInfo app, String processName) {
12650 synchronized (this) {
12651 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
12652 if (!isDebuggable) {
12653 if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
12654 throw new SecurityException("Process not debuggable: " + app.packageName);
12655 }
12656 }
12657
12658 mTrackAllocationApp = processName;
12659 }
12660 }
12661
12662 void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo) {
12663 synchronized (this) {
12664 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
12665 if (!isDebuggable) {
12666 if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
12667 throw new SecurityException("Process not debuggable: " + app.packageName);
12668 }
12669 }
12670 mProfileApp = processName;
12671 mProfileFile = profilerInfo.profileFile;
12672 if (mProfileFd != null) {
12673 try {
12674 mProfileFd.close();
12675 } catch (IOException e) {
12676 }
12677 mProfileFd = null;
12678 }
12679 mProfileFd = profilerInfo.profileFd;
12680 mSamplingInterval = profilerInfo.samplingInterval;
12681 mAutoStopProfiler = profilerInfo.autoStopProfiler;
12682 mStreamingOutput = profilerInfo.streamingOutput;
12683 mProfileType = 0;
12684 }
12685 }
12686
12687 void setNativeDebuggingAppLocked(ApplicationInfo app, String processName) {
12688 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
12689 if (!isDebuggable) {
12690 if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
12691 throw new SecurityException("Process not debuggable: " + app.packageName);
12692 }
12693 }
12694 mNativeDebuggingApp = processName;
12695 }
12696
12697 @Override
12698 public void setAlwaysFinish(boolean enabled) {
12699 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
12700 "setAlwaysFinish()");
12701
12702 long ident = Binder.clearCallingIdentity();
12703 try {
12704 Settings.Global.putInt(
12705 mContext.getContentResolver(),
12706 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
12707
12708 synchronized (this) {
12709 mAlwaysFinishActivities = enabled;
12710 }
12711 } finally {
12712 Binder.restoreCallingIdentity(ident);
12713 }
12714 }

设置activity控制器

 12716    @Override
12717 public void setActivityController(IActivityController controller, boolean imAMonkey) {
12718 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
12719 "setActivityController()");
12720 synchronized (this) {
12721 mController = controller;
12722 mControllerIsAMonkey = imAMonkey;
12723 Watchdog.getInstance().setActivityController(controller);
12724 }
12725 }

monkey相关

 12727    @Override
12728 public void setUserIsMonkey(boolean userIsMonkey) {
12729 synchronized (this) {
12730 synchronized (mPidsSelfLocked) {
12731 final int callingPid = Binder.getCallingPid();
12732 ProcessRecord proc = mPidsSelfLocked.get(callingPid);
12733 if (proc == null) {
12734 throw new SecurityException("Unknown process: " + callingPid);
12735 }
12736 if (proc.instr == null || proc.instr.mUiAutomationConnection == null) {
12737 throw new SecurityException("Only an instrumentation process "
12738 + "with a UiAutomation can call setUserIsMonkey");
12739 }
12740 }
12741 mUserIsMonkey = userIsMonkey;
12742 }
12743 }
12744
12745 @Override
12746 public boolean isUserAMonkey() {
12747 synchronized (this) {
12748 // If there is a controller also implies the user is a monkey.
12749 return (mUserIsMonkey || (mController != null && mControllerIsAMonkey));
12750 }
12751 }
12752

bugreport相关

 12753    /**
12754 * @deprecated This method is only used by a few internal components and it will soon be
12755 * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps).
12756 * No new code should be calling it.
12757 */
12758 @Deprecated
12759 @Override
12760 public void requestBugReport(int bugreportType) {
12761 String extraOptions = null;
12762 switch (bugreportType) {
12763 case ActivityManager.BUGREPORT_OPTION_FULL:
12764 // Default options.
12765 break;
12766 case ActivityManager.BUGREPORT_OPTION_INTERACTIVE:
12767 extraOptions = "bugreportplus";
12768 break;
12769 case ActivityManager.BUGREPORT_OPTION_REMOTE:
12770 extraOptions = "bugreportremote";
12771 break;
12772 case ActivityManager.BUGREPORT_OPTION_WEAR:
12773 extraOptions = "bugreportwear";
12774 break;
12775 case ActivityManager.BUGREPORT_OPTION_TELEPHONY:
12776 extraOptions = "bugreporttelephony";
12777 break;
12778 default:
12779 throw new IllegalArgumentException("Provided bugreport type is not correct, value: "
12780 + bugreportType);
12781 }
12782 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport");
12783 if (extraOptions != null) {
12784 SystemProperties.set("dumpstate.options", extraOptions);
12785 }
12786 SystemProperties.set("ctl.start", "bugreport");
12787 }
12788
12789 /**
12790 * @deprecated This method is only used by a few internal components and it will soon be
12791 * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps).
12792 * No new code should be calling it.
12793 */
12794 @Deprecated
12795 @Override
12796 public void requestTelephonyBugReport(String shareTitle, String shareDescription) {
12797
12798 if (!TextUtils.isEmpty(shareTitle)) {
12799 if (shareTitle.length() > MAX_BUGREPORT_TITLE_SIZE) {
12800 String errorStr = "shareTitle should be less than " +
12801 MAX_BUGREPORT_TITLE_SIZE + " characters";
12802 throw new IllegalArgumentException(errorStr);
12803 } else {
12804 if (!TextUtils.isEmpty(shareDescription)) {
12805 int length;
12806 try {
12807 length = shareDescription.getBytes("UTF-8").length;
12808 } catch (UnsupportedEncodingException e) {
12809 String errorStr = "shareDescription: UnsupportedEncodingException";
12810 throw new IllegalArgumentException(errorStr);
12811 }
12812 if (length > SystemProperties.PROP_VALUE_MAX) {
12813 String errorStr = "shareTitle should be less than " +
12814 SystemProperties.PROP_VALUE_MAX + " bytes";
12815 throw new IllegalArgumentException(errorStr);
12816 } else {
12817 SystemProperties.set("dumpstate.options.description", shareDescription);
12818 }
12819 }
12820 SystemProperties.set("dumpstate.options.title", shareTitle);
12821 }
12822 }
12823
12824 Slog.d(TAG, "Bugreport notification title " + shareTitle
12825 + " description " + shareDescription);
12826 requestBugReport(ActivityManager.BUGREPORT_OPTION_TELEPHONY);
12827 }

输入分发相关

 12829    public static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
12830 return r != null ? getInputDispatchingTimeoutLocked(r.app) : KEY_DISPATCHING_TIMEOUT;
12831 }
12832
12833 public static long getInputDispatchingTimeoutLocked(ProcessRecord r) {
12834 if (r != null && (r.instr != null || r.usingWrapper)) {
12835 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
12836 }
12837 return KEY_DISPATCHING_TIMEOUT;
12838 }
12839
12840 @Override
12841 public long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) {
12842 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
12843 != PackageManager.PERMISSION_GRANTED) {
12844 throw new SecurityException("Requires permission "
12845 + android.Manifest.permission.FILTER_EVENTS);
12846 }
12847 ProcessRecord proc;
12848 long timeout;
12849 synchronized (this) {
12850 synchronized (mPidsSelfLocked) {
12851 proc = mPidsSelfLocked.get(pid);
12852 }
12853 timeout = getInputDispatchingTimeoutLocked(proc);
12854 }
12855
12856 if (!inputDispatchingTimedOut(proc, null, null, aboveSystem, reason)) {
12857 return -1;
12858 }
12859
12860 return timeout;
12861 }
12862
12863 /**
12864 * Handle input dispatching timeouts.
12865 * Returns whether input dispatching should be aborted or not.
12866 */
12867 public boolean inputDispatchingTimedOut(final ProcessRecord proc,
12868 final ActivityRecord activity, final ActivityRecord parent,
12869 final boolean aboveSystem, String reason) {
12870 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
12871 != PackageManager.PERMISSION_GRANTED) {
12872 throw new SecurityException("Requires permission "
12873 + android.Manifest.permission.FILTER_EVENTS);
12874 }
12875
12876 final String annotation;
12877 if (reason == null) {
12878 annotation = "Input dispatching timed out";
12879 } else {
12880 annotation = "Input dispatching timed out (" + reason + ")";
12881 }
12882
12883 if (proc != null) {
12884 synchronized (this) {
12885 if (proc.debugging) {
12886 return false;
12887 }
12888
12889 if (mDidDexOpt) {
12890 // Give more time since we were dexopting.
12891 mDidDexOpt = false;
12892 return false;
12893 }
12894
12895 if (proc.instr != null) {
12896 Bundle info = new Bundle();
12897 info.putString("shortMsg", "keyDispatchingTimedOut");
12898 info.putString("longMsg", annotation);
12899 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
12900 return true;
12901 }
12902 }
12903 mHandler.post(new Runnable() {
12904 @Override
12905 public void run() {
12906 mAppErrors.appNotResponding(proc, activity, parent, aboveSystem, annotation);
12907 }
12908 });
12909 }
12910
12911 return true;
12912 }

辅助相关

 12914    @Override
12915 public Bundle getAssistContextExtras(int requestType) {
12916 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
12917 null, null, true /* focused */, true /* newSessionId */,
12918 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
12919 if (pae == null) {
12920 return null;
12921 }
12922 synchronized (pae) {
12923 while (!pae.haveResult) {
12924 try {
12925 pae.wait();
12926 } catch (InterruptedException e) {
12927 }
12928 }
12929 }
12930 synchronized (this) {
12931 buildAssistBundleLocked(pae, pae.result);
12932 mPendingAssistExtras.remove(pae);
12933 mUiHandler.removeCallbacks(pae);
12934 }
12935 return pae.extras;
12936 }
12937
12938 @Override
12939 public boolean isAssistDataAllowedOnCurrentActivity() {
12940 int userId;
12941 synchronized (this) {
12942 final ActivityStack focusedStack = getFocusedStack();
12943 if (focusedStack == null || focusedStack.isAssistantStack()) {
12944 return false;
12945 }
12946
12947 final ActivityRecord activity = focusedStack.topActivity();
12948 if (activity == null) {
12949 return false;
12950 }
12951 userId = activity.userId;
12952 }
12953 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
12954 Context.DEVICE_POLICY_SERVICE);
12955 return (dpm == null) || (!dpm.getScreenCaptureDisabled(null, userId));
12956 }
12957
12958 @Override
12959 public boolean showAssistFromActivity(IBinder token, Bundle args) {
12960 long ident = Binder.clearCallingIdentity();
12961 try {
12962 synchronized (this) {
12963 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
12964 ActivityRecord top = getFocusedStack().topActivity();
12965 if (top != caller) {
12966 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
12967 + " is not current top " + top);
12968 return false;
12969 }
12970 if (!top.nowVisible) {
12971 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
12972 + " is not visible");
12973 return false;
12974 }
12975 }
12976 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
12977 token);
12978 } finally {
12979 Binder.restoreCallingIdentity(ident);
12980 }
12981 }
12982
12983 @Override
12984 public boolean requestAssistContextExtras(int requestType, IResultReceiver receiver,
12985 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
12986 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
12987 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
12988 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
12989 }
12990
12991 @Override
12992 public boolean requestAutofillData(IResultReceiver receiver, Bundle receiverExtras,
12993 IBinder activityToken, int flags) {
12994 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
12995 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
12996 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
12997 }
12998
12999 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
13000 IResultReceiver receiver, Bundle receiverExtras, IBinder activityToken,
13001 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
13002 int flags) {
13003 enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
13004 "enqueueAssistContext()");
13005
13006 synchronized (this) {
13007 ActivityRecord activity = getFocusedStack().topActivity();
13008 if (activity == null) {
13009 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
13010 return null;
13011 }
13012 if (activity.app == null || activity.app.thread == null) {
13013 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
13014 return null;
13015 }
13016 if (focused) {
13017 if (activityToken != null) {
13018 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
13019 if (activity != caller) {
13020 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
13021 + " is not current top " + activity);
13022 return null;
13023 }
13024 }
13025 } else {
13026 activity = ActivityRecord.forTokenLocked(activityToken);
13027 if (activity == null) {
13028 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
13029 + " couldn't be found");
13030 return null;
13031 }
13032 }
13033
13034 PendingAssistExtras pae;
13035 Bundle extras = new Bundle();
13036 if (args != null) {
13037 extras.putAll(args);
13038 }
13039 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
13040 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.uid);
13041
13042 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
13043 userHandle);
13044 pae.isHome = activity.isHomeActivity();
13045
13046 // Increment the sessionId if necessary
13047 if (newSessionId) {
13048 mViSessionId++;
13049 }
13050 try {
13051 activity.app.thread.requestAssistContextExtras(activity.appToken, pae, requestType,
13052 mViSessionId, flags);
13053 mPendingAssistExtras.add(pae);
13054 mUiHandler.postDelayed(pae, timeout);
13055 } catch (RemoteException e) {
13056 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
13057 return null;
13058 }
13059 return pae;
13060 }
13061 }
13062
13063 void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
13064 IResultReceiver receiver;
13065 synchronized (this) {
13066 mPendingAssistExtras.remove(pae);
13067 receiver = pae.receiver;
13068 }
13069 if (receiver != null) {
13070 // Caller wants result sent back to them.
13071 Bundle sendBundle = new Bundle();
13072 // At least return the receiver extras
13073 sendBundle.putBundle(VoiceInteractionSession.KEY_RECEIVER_EXTRAS,
13074 pae.receiverExtras);
13075 try {
13076 pae.receiver.send(0, sendBundle);
13077 } catch (RemoteException e) {
13078 }
13079 }
13080 }
13081
13082 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
13083 if (result != null) {
13084 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
13085 }
13086 if (pae.hint != null) {
13087 pae.extras.putBoolean(pae.hint, true);
13088 }
13089 }
13090
13091 /** Called from an app when assist data is ready. */
13092 @Override
13093 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
13094 AssistContent content, Uri referrer) {
13095 PendingAssistExtras pae = (PendingAssistExtras)token;
13096 synchronized (pae) {
13097 pae.result = extras;
13098 pae.structure = structure;
13099 pae.content = content;
13100 if (referrer != null) {
13101 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
13102 }
13103 if (structure != null) {
13104 structure.setHomeActivity(pae.isHome);
13105 }
13106 pae.haveResult = true;
13107 pae.notifyAll();
13108 if (pae.intent == null && pae.receiver == null) {
13109 // Caller is just waiting for the result.
13110 return;
13111 }
13112 }
13113
13114 // We are now ready to launch the assist activity.
13115 IResultReceiver sendReceiver = null;
13116 Bundle sendBundle = null;
13117 synchronized (this) {
13118 buildAssistBundleLocked(pae, extras);
13119 boolean exists = mPendingAssistExtras.remove(pae);
13120 mUiHandler.removeCallbacks(pae);
13121 if (!exists) {
13122 // Timed out.
13123 return;
13124 }
13125 if ((sendReceiver=pae.receiver) != null) {
13126 // Caller wants result sent back to them.
13127 sendBundle = new Bundle();
13128 sendBundle.putBundle(VoiceInteractionSession.KEY_DATA, pae.extras);
13129 sendBundle.putParcelable(VoiceInteractionSession.KEY_STRUCTURE, pae.structure);
13130 sendBundle.putParcelable(VoiceInteractionSession.KEY_CONTENT, pae.content);
13131 sendBundle.putBundle(VoiceInteractionSession.KEY_RECEIVER_EXTRAS,
13132 pae.receiverExtras);
13133 }
13134 }
13135 if (sendReceiver != null) {
13136 try {
13137 sendReceiver.send(0, sendBundle);
13138 } catch (RemoteException e) {
13139 }
13140 return;
13141 }
13142
13143 long ident = Binder.clearCallingIdentity();
13144 try {
13145 pae.intent.replaceExtras(pae.extras);
13146 pae.intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
13147 | Intent.FLAG_ACTIVITY_SINGLE_TOP
13148 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
13149 closeSystemDialogs("assist");
13150 try {
13151 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
13152 } catch (ActivityNotFoundException e) {
13153 Slog.w(TAG, "No activity to handle assist action.", e);
13154 }
13155 } finally {
13156 Binder.restoreCallingIdentity(ident);
13157 }
13158 }
13159
13160 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
13161 Bundle args) {
13162 return enqueueAssistContext(requestType, intent, hint, null, null, null,
13163 true /* focused */, true /* newSessionId */, userHandle, args,
13164 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
13165 }

进程、uid观察者注册与取消

 13167    public void registerProcessObserver(IProcessObserver observer) {
13168 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
13169 "registerProcessObserver()");
13170 synchronized (this) {
13171 mProcessObservers.register(observer);
13172 }
13173 }
13174
13175 @Override
13176 public void unregisterProcessObserver(IProcessObserver observer) {
13177 synchronized (this) {
13178 mProcessObservers.unregister(observer);
13179 }
13180 }
13181
13182 @Override
13183 public int getUidProcessState(int uid, String callingPackage) {
13184 if (!hasUsageStatsPermission(callingPackage)) {
13185 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
13186 "getUidProcessState");
13187 }
13188
13189 synchronized (this) {
13190 UidRecord uidRec = mActiveUids.get(uid);
13191 return uidRec != null ? uidRec.curProcState : ActivityManager.PROCESS_STATE_NONEXISTENT;
13192 }
13193 }
13194
13195 @Override
13196 public void registerUidObserver(IUidObserver observer, int which, int cutpoint,
13197 String callingPackage) {
13198 if (!hasUsageStatsPermission(callingPackage)) {
13199 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
13200 "registerUidObserver");
13201 }
13202 synchronized (this) {
13203 mUidObservers.register(observer, new UidObserverRegistration(Binder.getCallingUid(),
13204 callingPackage, which, cutpoint));
13205 }
13206 }
13207
13208 @Override
13209 public void unregisterUidObserver(IUidObserver observer) {
13210 synchronized (this) {
13211 mUidObservers.unregister(observer);
13212 }
13213 }

可视性相关

 13215    @Override
13216 public boolean convertFromTranslucent(IBinder token) {
13217 final long origId = Binder.clearCallingIdentity();
13218 try {
13219 synchronized (this) {
13220 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
13221 if (r == null) {
13222 return false;
13223 }
13224 final boolean translucentChanged = r.changeWindowTranslucency(true);
13225 if (translucentChanged) {
13226 r.getStack().releaseBackgroundResources(r);
13227 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
13228 }
13229 mWindowManager.setAppFullscreen(token, true);
13230 return translucentChanged;
13231 }
13232 } finally {
13233 Binder.restoreCallingIdentity(origId);
13234 }
13235 }
13236
13237 @Override
13238 public boolean convertToTranslucent(IBinder token, Bundle options) {
13239 final long origId = Binder.clearCallingIdentity();
13240 try {
13241 synchronized (this) {
13242 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
13243 if (r == null) {
13244 return false;
13245 }
13246 final TaskRecord task = r.getTask();
13247 int index = task.mActivities.lastIndexOf(r);
13248 if (index > 0) {
13249 ActivityRecord under = task.mActivities.get(index - 1);
13250 under.returningOptions = ActivityOptions.fromBundle(options);
13251 }
13252 final boolean translucentChanged = r.changeWindowTranslucency(false);
13253 if (translucentChanged) {
13254 r.getStack().convertActivityToTranslucent(r);
13255 }
13256 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
13257 mWindowManager.setAppFullscreen(token, false);
13258 return translucentChanged;
13259 }
13260 } finally {
13261 Binder.restoreCallingIdentity(origId);
13262 }
13263 }
13264
13265 @Override
13266 public boolean requestVisibleBehind(IBinder token, boolean visible) {
13267 final long origId = Binder.clearCallingIdentity();
13268 try {
13269 synchronized (this) {
13270 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
13271 if (r != null) {
13272 return mStackSupervisor.requestVisibleBehindLocked(r, visible);
13273 }
13274 }
13275 return false;
13276 } finally {
13277 Binder.restoreCallingIdentity(origId);
13278 }
13279 }
13280
13281 @Override
13282 public boolean isBackgroundVisibleBehind(IBinder token) {
13283 final long origId = Binder.clearCallingIdentity();
13284 try {
13285 synchronized (this) {
13286 final ActivityStack stack = ActivityRecord.getStackLocked(token);
13287 final boolean visible = stack == null ? false : stack.hasVisibleBehindActivity();
13288 if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND,
13289 "isBackgroundVisibleBehind: stack=" + stack + " visible=" + visible);
13290 return visible;
13291 }
13292 } finally {
13293 Binder.restoreCallingIdentity(origId);
13294 }
13295 }

获取activity options

 13297    @Override
13298 public Bundle getActivityOptions(IBinder token) {
13299 final long origId = Binder.clearCallingIdentity();
13300 try {
13301 synchronized (this) {
13302 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
13303 if (r != null) {
13304 final ActivityOptions activityOptions = r.pendingOptions;
13305 r.pendingOptions = null;
13306 return activityOptions == null ? null : activityOptions.toBundle();
13307 }
13308 return null;
13309 }
13310 } finally {
13311 Binder.restoreCallingIdentity(origId);
13312 }
13313 }

vr相关

 13315    @Override
13316 public void setImmersive(IBinder token, boolean immersive) {
13317 synchronized(this) {
13318 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
13319 if (r == null) {
13320 throw new IllegalArgumentException();
13321 }
13322 r.immersive = immersive;
13323
13324 // update associated state if we're frontmost
13325 if (r == mStackSupervisor.getResumedActivityLocked()) {
13326 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
13327 applyUpdateLockStateLocked(r);
13328 }
13329 }
13330 }
13331
13332 @Override
13333 public boolean isImmersive(IBinder token) {
13334 synchronized (this) {
13335 ActivityRecord r = ActivityRecord.isInStackLocked(token);
13336 if (r == null) {
13337 throw new IllegalArgumentException();
13338 }
13339 return r.immersive;
13340 }
13341 }
13342
13343 @Override
13344 public void setVrThread(int tid) {
13345 enforceSystemHasVrFeature();
13346 synchronized (this) {
13347 synchronized (mPidsSelfLocked) {
13348 final int pid = Binder.getCallingPid();
13349 final ProcessRecord proc = mPidsSelfLocked.get(pid);
13350 mVrController.setVrThreadLocked(tid, pid, proc);
13351 }
13352 }
13353 }
13354
13355 @Override
13356 public void setPersistentVrThread(int tid) {
13357 if (checkCallingPermission(permission.RESTRICTED_VR_ACCESS) != PERMISSION_GRANTED) {
13358 final String msg = "Permission Denial: setPersistentVrThread() from pid="
13359 + Binder.getCallingPid()
13360 + ", uid=" + Binder.getCallingUid()
13361 + " requires " + permission.RESTRICTED_VR_ACCESS;
13362 Slog.w(TAG, msg);
13363 throw new SecurityException(msg);
13364 }
13365 enforceSystemHasVrFeature();
13366 synchronized (this) {
13367 synchronized (mPidsSelfLocked) {
13368 final int pid = Binder.getCallingPid();
13369 final ProcessRecord proc = mPidsSelfLocked.get(pid);
13370 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
13371 }
13372 }
13373 }

vr调度与模式

 13375    /**
13376 * Schedule the given thread a normal scheduling priority.
13377 *
13378 * @param newTid the tid of the thread to adjust the scheduling of.
13379 * @param suppressLogs {@code true} if any error logging should be disabled.
13380 *
13381 * @return {@code true} if this succeeded.
13382 */
13383 static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) {
13384 try {
13385 Process.setThreadScheduler(tid, Process.SCHED_OTHER, 0);
13386 return true;
13387 } catch (IllegalArgumentException e) {
13388 if (!suppressLogs) {
13389 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
13390 }
13391 }
13392 return false;
13393 }
13394
13395 /**
13396 * Schedule the given thread an FIFO scheduling priority.
13397 *
13398 * @param newTid the tid of the thread to adjust the scheduling of.
13399 * @param suppressLogs {@code true} if any error logging should be disabled.
13400 *
13401 * @return {@code true} if this succeeded.
13402 */
13403 static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) {
13404 try {
13405 Process.setThreadScheduler(tid, Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1);
13406 return true;
13407 } catch (IllegalArgumentException e) {
13408 if (!suppressLogs) {
13409 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
13410 }
13411 }
13412 return false;
13413 }
13414
13415 /**
13416 * Check that we have the features required for VR-related API calls, and throw an exception if
13417 * not.
13418 */
13419 private void enforceSystemHasVrFeature() {
13420 if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_VR_MODE)) {
13421 throw new UnsupportedOperationException("VR mode not supported on this device!");
13422 }
13423 }
13424
13425 @Override
13426 public void setRenderThread(int tid) {
13427 synchronized (this) {
13428 ProcessRecord proc;
13429 int pid = Binder.getCallingPid();
13430 if (pid == Process.myPid()) {
13431 demoteSystemServerRenderThread(tid);
13432 return;
13433 }
13434 synchronized (mPidsSelfLocked) {
13435 proc = mPidsSelfLocked.get(pid);
13436 if (proc != null && proc.renderThreadTid == 0 && tid > 0) {
13437 // ensure the tid belongs to the process
13438 if (!isThreadInProcess(pid, tid)) {
13439 throw new IllegalArgumentException(
13440 "Render thread does not belong to process");
13441 }
13442 proc.renderThreadTid = tid;
13443 if (DEBUG_OOM_ADJ) {
13444 Slog.d("UI_FIFO", "Set RenderThread tid " + tid + " for pid " + pid);
13445 }
13446 // promote to FIFO now
13447 if (proc.curSchedGroup == ProcessList.SCHED_GROUP_TOP_APP) {
13448 if (DEBUG_OOM_ADJ) Slog.d("UI_FIFO", "Promoting " + tid + "out of band");
13449 if (mUseFifoUiScheduling) {
13450 setThreadScheduler(proc.renderThreadTid,
13451 SCHED_FIFO | SCHED_RESET_ON_FORK, 1);
13452 } else {
13453 setThreadPriority(proc.renderThreadTid, TOP_APP_PRIORITY_BOOST);
13454 }
13455 }
13456 } else {
13457 if (DEBUG_OOM_ADJ) {
13458 Slog.d("UI_FIFO", "Didn't set thread from setRenderThread? " +
13459 "PID: " + pid + ", TID: " + tid + " FIFO: " +
13460 mUseFifoUiScheduling);
13461 }
13462 }
13463 }
13464 }
13465 }
13466
13467 /**
13468 * We only use RenderThread in system_server to store task snapshots to the disk, which should
13469 * happen in the background. Thus, demote render thread from system_server to a lower priority.
13470 *
13471 * @param tid the tid of the RenderThread
13472 */
13473 private void demoteSystemServerRenderThread(int tid) {
13474 setThreadPriority(tid, Process.THREAD_PRIORITY_BACKGROUND);
13475 }
13476
13477 @Override
13478 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
13479 if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_VR_MODE)) {
13480 throw new UnsupportedOperationException("VR mode not supported on this device!");
13481 }
13482
13483 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
13484
13485 ActivityRecord r;
13486 synchronized (this) {
13487 r = ActivityRecord.isInStackLocked(token);
13488 }
13489
13490 if (r == null) {
13491 throw new IllegalArgumentException();
13492 }
13493
13494 int err;
13495 if ((err = vrService.hasVrPackage(packageName, r.userId)) !=
13496 VrManagerInternal.NO_ERROR) {
13497 return err;
13498 }
13499
13500 synchronized(this) {
13501 r.requestedVrComponent = (enabled) ? packageName : null;
13502
13503 // Update associated state if this activity is currently focused
13504 if (r == mStackSupervisor.getResumedActivityLocked()) {
13505 applyUpdateVrModeLocked(r);
13506 }
13507 return 0;
13508 }
13509 }
13510
13511 @Override
13512 public boolean isVrModePackageEnabled(ComponentName packageName) {
13513 if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_VR_MODE)) {
13514 throw new UnsupportedOperationException("VR mode not supported on this device!");
13515 }
13516
13517 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
13518
13519 return vrService.hasVrPackage(packageName, UserHandle.getCallingUserId()) ==
13520 VrManagerInternal.NO_ERROR;
13521 }
13522
13523 public boolean isTopActivityImmersive() {
13524 enforceNotIsolatedCaller("startActivity");
13525 synchronized (this) {
13526 ActivityRecord r = getFocusedStack().topRunningActivityLocked();
13527 return (r != null) ? r.immersive : false;
13528 }
13529 }
13530
13531 /**
13532 * @return whether the system should disable UI modes incompatible with VR mode.
13533 */
13534 boolean shouldDisableNonVrUiLocked() {
13535 return mVrController.shouldDisableNonVrUiLocked();
13536 }

是否拥有top ui

 13549    @Override
13550 public void setHasTopUi(boolean hasTopUi) throws RemoteException {
13551 if (checkCallingPermission(permission.INTERNAL_SYSTEM_WINDOW) != PERMISSION_GRANTED) {
13552 String msg = "Permission Denial: setHasTopUi() from pid="
13553 + Binder.getCallingPid()
13554 + ", uid=" + Binder.getCallingUid()
13555 + " requires " + permission.INTERNAL_SYSTEM_WINDOW;
13556 Slog.w(TAG, msg);
13557 throw new SecurityException(msg);
13558 }
13559 final int pid = Binder.getCallingPid();
13560 final long origId = Binder.clearCallingIdentity();
13561 try {
13562 synchronized (this) {
13563 boolean changed = false;
13564 ProcessRecord pr;
13565 synchronized (mPidsSelfLocked) {
13566 pr = mPidsSelfLocked.get(pid);
13567 if (pr == null) {
13568 Slog.w(TAG, "setHasTopUi called on unknown pid: " + pid);
13569 return;
13570 }
13571 if (pr.hasTopUi != hasTopUi) {
13572 if (DEBUG_OOM_ADJ) {
13573 Slog.d(TAG, "Setting hasTopUi=" + hasTopUi + " for pid=" + pid);
13574 }
13575 pr.hasTopUi = hasTopUi;
13576 changed = true;
13577 }
13578 }
13579 if (changed) {
13580 updateOomAdjLocked(pr, true);
13581 }
13582 }
13583 } finally {
13584 Binder.restoreCallingIdentity(origId);
13585 }
13586 }

safe mode相关

 13588    public final void enterSafeMode() {
13589 synchronized(this) {
13590 // It only makes sense to do this before the system is ready
13591 // and started launching other packages.
13592 if (!mSystemReady) {
13593 try {
13594 AppGlobals.getPackageManager().enterSafeMode();
13595 } catch (RemoteException e) {
13596 }
13597 }
13598
13599 mSafeMode = true;
13600 }
13601 }
13602
13603 public final void showSafeModeOverlay() {
13604 View v = LayoutInflater.from(mContext).inflate(
13605 com.android.internal.R.layout.safe_mode, null);
13606 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
13607 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
13608 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
13609 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
13610 lp.gravity = Gravity.BOTTOM | Gravity.START;
13611 lp.format = v.getBackground().getOpacity();
13612 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
13613 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
13614 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
13615 ((WindowManager)mContext.getSystemService(
13616 Context.WINDOW_SERVICE)).addView(v, lp);
13617 }

通告alarm状态

 13619    public void noteWakeupAlarm(IIntentSender sender, int sourceUid, String sourcePkg, String tag) {
13620 if (sender != null && !(sender instanceof PendingIntentRecord)) {
13621 return;
13622 }
13623 final PendingIntentRecord rec = (PendingIntentRecord)sender;
13624 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13625 synchronized (stats) {
13626 if (mBatteryStatsService.isOnBattery()) {
13627 mBatteryStatsService.enforceCallingPermission();
13628 int MY_UID = Binder.getCallingUid();
13629 final int uid;
13630 if (sender == null) {
13631 uid = sourceUid;
13632 } else {
13633 uid = rec.uid == MY_UID ? SYSTEM_UID : rec.uid;
13634 }
13635 BatteryStatsImpl.Uid.Pkg pkg =
13636 stats.getPackageStatsLocked(sourceUid >= 0 ? sourceUid : uid,
13637 sourcePkg != null ? sourcePkg : rec.key.packageName);
13638 pkg.noteWakeupAlarmLocked(tag);
13639 }
13640 }
13641 }
13642
13643 public void noteAlarmStart(IIntentSender sender, int sourceUid, String tag) {
13644 if (sender != null && !(sender instanceof PendingIntentRecord)) {
13645 return;
13646 }
13647 final PendingIntentRecord rec = (PendingIntentRecord)sender;
13648 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13649 synchronized (stats) {
13650 mBatteryStatsService.enforceCallingPermission();
13651 int MY_UID = Binder.getCallingUid();
13652 final int uid;
13653 if (sender == null) {
13654 uid = sourceUid;
13655 } else {
13656 uid = rec.uid == MY_UID ? SYSTEM_UID : rec.uid;
13657 }
13658 mBatteryStatsService.noteAlarmStart(tag, sourceUid >= 0 ? sourceUid : uid);
13659 }
13660 }
13661
13662 public void noteAlarmFinish(IIntentSender sender, int sourceUid, String tag) {
13663 if (sender != null && !(sender instanceof PendingIntentRecord)) {
13664 return;
13665 }
13666 final PendingIntentRecord rec = (PendingIntentRecord)sender;
13667 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13668 synchronized (stats) {
13669 mBatteryStatsService.enforceCallingPermission();
13670 int MY_UID = Binder.getCallingUid();
13671 final int uid;
13672 if (sender == null) {
13673 uid = sourceUid;
13674 } else {
13675 uid = rec.uid == MY_UID ? SYSTEM_UID : rec.uid;
13676 }
13677 mBatteryStatsService.noteAlarmFinish(tag, sourceUid >= 0 ? sourceUid : uid);
13678 }
13679 }

杀进程,hang,restart系统

 13681    public boolean killPids(int[] pids, String pReason, boolean secure) {
13682 if (Binder.getCallingUid() != SYSTEM_UID) {
13683 throw new SecurityException("killPids only available to the system");
13684 }
13685 String reason = (pReason == null) ? "Unknown" : pReason;
13686 // XXX Note: don't acquire main activity lock here, because the window
13687 // manager calls in with its locks held.
13688
13689 boolean killed = false;
13690 synchronized (mPidsSelfLocked) {
13691 int worstType = 0;
13692 for (int i=0; i<pids.length; i++) {
13693 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
13694 if (proc != null) {
13695 int type = proc.setAdj;
13696 if (type > worstType) {
13697 worstType = type;
13698 }
13699 }
13700 }
13701
13702 // If the worst oom_adj is somewhere in the cached proc LRU range,
13703 // then constrain it so we will kill all cached procs.
13704 if (worstType < ProcessList.CACHED_APP_MAX_ADJ
13705 && worstType > ProcessList.CACHED_APP_MIN_ADJ) {
13706 worstType = ProcessList.CACHED_APP_MIN_ADJ;
13707 }
13708
13709 // If this is not a secure call, don't let it kill processes that
13710 // are important.
13711 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
13712 worstType = ProcessList.SERVICE_ADJ;
13713 }
13714
13715 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
13716 for (int i=0; i<pids.length; i++) {
13717 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
13718 if (proc == null) {
13719 continue;
13720 }
13721 int adj = proc.setAdj;
13722 if (adj >= worstType && !proc.killedByAm) {
13723 proc.kill(reason, true);
13724 killed = true;
13725 }
13726 }
13727 }
13728 return killed;
13729 }
13730
13731 @Override
13732 public void killUid(int appId, int userId, String reason) {
13733 enforceCallingPermission(Manifest.permission.KILL_UID, "killUid");
13734 synchronized (this) {
13735 final long identity = Binder.clearCallingIdentity();
13736 try {
13737 killPackageProcessesLocked(null, appId, userId,
13738 ProcessList.PERSISTENT_PROC_ADJ, false, true, true, true,
13739 reason != null ? reason : "kill uid");
13740 } finally {
13741 Binder.restoreCallingIdentity(identity);
13742 }
13743 }
13744 }
13745
13746 @Override
13747 public boolean killProcessesBelowForeground(String reason) {
13748 if (Binder.getCallingUid() != SYSTEM_UID) {
13749 throw new SecurityException("killProcessesBelowForeground() only available to system");
13750 }
13751
13752 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
13753 }
13754
13755 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
13756 if (Binder.getCallingUid() != SYSTEM_UID) {
13757 throw new SecurityException("killProcessesBelowAdj() only available to system");
13758 }
13759
13760 boolean killed = false;
13761 synchronized (mPidsSelfLocked) {
13762 final int size = mPidsSelfLocked.size();
13763 for (int i = 0; i < size; i++) {
13764 final int pid = mPidsSelfLocked.keyAt(i);
13765 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
13766 if (proc == null) continue;
13767
13768 final int adj = proc.setAdj;
13769 if (adj > belowAdj && !proc.killedByAm) {
13770 proc.kill(reason, true);
13771 killed = true;
13772 }
13773 }
13774 }
13775 return killed;
13776 }
13777
13778 @Override
13779 public void hang(final IBinder who, boolean allowRestart) {
13780 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13781 != PackageManager.PERMISSION_GRANTED) {
13782 throw new SecurityException("Requires permission "
13783 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13784 }
13785
13786 final IBinder.DeathRecipient death = new DeathRecipient() {
13787 @Override
13788 public void binderDied() {
13789 synchronized (this) {
13790 notifyAll();
13791 }
13792 }
13793 };
13794
13795 try {
13796 who.linkToDeath(death, 0);
13797 } catch (RemoteException e) {
13798 Slog.w(TAG, "hang: given caller IBinder is already dead.");
13799 return;
13800 }
13801
13802 synchronized (this) {
13803 Watchdog.getInstance().setAllowRestart(allowRestart);
13804 Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid());
13805 synchronized (death) {
13806 while (who.isBinderAlive()) {
13807 try {
13808 death.wait();
13809 } catch (InterruptedException e) {
13810 }
13811 }
13812 }
13813 Watchdog.getInstance().setAllowRestart(true);
13814 }
13815 }
13816
13817 @Override
13818 public void restart() {
13819 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13820 != PackageManager.PERMISSION_GRANTED) {
13821 throw new SecurityException("Requires permission "
13822 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13823 }
13824
13825 Log.i(TAG, "Sending shutdown broadcast...");
13826
13827 BroadcastReceiver br = new BroadcastReceiver() {
13828 @Override public void onReceive(Context context, Intent intent) {
13829 // Now the broadcast is done, finish up the low-level shutdown.
13830 Log.i(TAG, "Shutting down activity manager...");
13831 shutdown(10000);
13832 Log.i(TAG, "Shutdown complete, restarting!");
13833 killProcess(myPid());
13834 System.exit(10);
13835 }
13836 };
13837
13838 // First send the high-level shut down broadcast.
13839 Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
13840 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13841 intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
13842 /* For now we are not doing a clean shutdown, because things seem to get unhappy.
13843 mContext.sendOrderedBroadcastAsUser(intent,
13844 UserHandle.ALL, null, br, mHandler, 0, null, null);
13845 */
13846 br.onReceive(mContext, intent);
13847 }

low mem,idle处理

 13849    private long getLowRamTimeSinceIdle(long now) {
13850 return mLowRamTimeSinceLastIdle + (mLowRamStartTime > 0 ? (now-mLowRamStartTime) : 0);
13851 }
13852
13853 @Override
13854 public void performIdleMaintenance() {
13855 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13856 != PackageManager.PERMISSION_GRANTED) {
13857 throw new SecurityException("Requires permission "
13858 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13859 }
13860
13861 synchronized (this) {
13862 final long now = SystemClock.uptimeMillis();
13863 final long timeSinceLastIdle = now - mLastIdleTime;
13864 final long lowRamSinceLastIdle = getLowRamTimeSinceIdle(now);
13865 mLastIdleTime = now;
13866 mLowRamTimeSinceLastIdle = 0;
13867 if (mLowRamStartTime != 0) {
13868 mLowRamStartTime = now;
13869 }
13870
13871 StringBuilder sb = new StringBuilder(128);
13872 sb.append("Idle maintenance over ");
13873 TimeUtils.formatDuration(timeSinceLastIdle, sb);
13874 sb.append(" low RAM for ");
13875 TimeUtils.formatDuration(lowRamSinceLastIdle, sb);
13876 Slog.i(TAG, sb.toString());
13877
13878 // If at least 1/3 of our time since the last idle period has been spent
13879 // with RAM low, then we want to kill processes.
13880 boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3);
13881
13882 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13883 ProcessRecord proc = mLruProcesses.get(i);
13884 if (proc.notCachedSinceIdle) {
13885 if (proc.setProcState != ActivityManager.PROCESS_STATE_TOP_SLEEPING
13886 && proc.setProcState >= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
13887 && proc.setProcState <= ActivityManager.PROCESS_STATE_SERVICE) {
13888 if (doKilling && proc.initialIdlePss != 0
13889 && proc.lastPss > ((proc.initialIdlePss*3)/2)) {
13890 sb = new StringBuilder(128);
13891 sb.append("Kill");
13892 sb.append(proc.processName);
13893 sb.append(" in idle maint: pss=");
13894 sb.append(proc.lastPss);
13895 sb.append(", swapPss=");
13896 sb.append(proc.lastSwapPss);
13897 sb.append(", initialPss=");
13898 sb.append(proc.initialIdlePss);
13899 sb.append(", period=");
13900 TimeUtils.formatDuration(timeSinceLastIdle, sb);
13901 sb.append(", lowRamPeriod=");
13902 TimeUtils.formatDuration(lowRamSinceLastIdle, sb);
13903 Slog.wtfQuiet(TAG, sb.toString());
13904 proc.kill("idle maint (pss " + proc.lastPss
13905 + " from " + proc.initialIdlePss + ")", true);
13906 }
13907 }
13908 } else if (proc.setProcState < ActivityManager.PROCESS_STATE_HOME
13909 && proc.setProcState >= ActivityManager.PROCESS_STATE_PERSISTENT) {
13910 proc.notCachedSinceIdle = true;
13911 proc.initialIdlePss = 0;
13912 proc.nextPssTime = ProcessList.computeNextPssTime(proc.setProcState, true,
13913 mTestPssMode, isSleepingLocked(), now);
13914 }
13915 }
13916
13917 mHandler.removeMessages(REQUEST_ALL_PSS_MSG);
13918 mHandler.sendEmptyMessageDelayed(REQUEST_ALL_PSS_MSG, 2*60*1000);
13919 }
13920 }
13921

发送idle job触发器

 13922    @Override
13923 public void sendIdleJobTrigger() {
13924 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13925 != PackageManager.PERMISSION_GRANTED) {
13926 throw new SecurityException("Requires permission "
13927 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13928 }
13929
13930 final long ident = Binder.clearCallingIdentity();
13931 try {
13932 Intent intent = new Intent(ACTION_TRIGGER_IDLE)
13933 .setPackage("android")
13934 .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
13935 broadcastIntent(null, intent, null, null, 0, null, null, null,
13936 android.app.AppOpsManager.OP_NONE, null, true, false, UserHandle.USER_ALL);
13937 } finally {
13938 Binder.restoreCallingIdentity(ident);
13939 }
13940 }

获取setting变化

 13942    private void retrieveSettings() {
13943 final ContentResolver resolver = mContext.getContentResolver();
13944 final boolean freeformWindowManagement =
13945 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
13946 || Settings.Global.getInt(
13947 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
13948 final boolean supportsPictureInPicture =
13949 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
13950
13951 final boolean supportsMultiWindow = ActivityManager.supportsMultiWindow(mContext);
13952 final boolean supportsSplitScreenMultiWindow =
13953 ActivityManager.supportsSplitScreenMultiWindow(mContext);
13954 final boolean supportsMultiDisplay = mContext.getPackageManager()
13955 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
13956 final String debugApp = Settings.Global.getString(resolver, DEBUG_APP);
13957 final boolean waitForDebugger = Settings.Global.getInt(resolver, WAIT_FOR_DEBUGGER, 0) != 0;
13958 final boolean alwaysFinishActivities =
13959 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0;
13960 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
13961 final boolean forceResizable = Settings.Global.getInt(
13962 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
13963 final long waitForNetworkTimeoutMs = Settings.Global.getLong(resolver,
13964 NETWORK_ACCESS_TIMEOUT_MS, NETWORK_ACCESS_TIMEOUT_DEFAULT_MS);
13965 final boolean supportsLeanbackOnly =
13966 mContext.getPackageManager().hasSystemFeature(FEATURE_LEANBACK_ONLY);
13967
13968 // Transfer any global setting for forcing RTL layout, into a System Property
13969 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
13970
13971 final Configuration configuration = new Configuration();
13972 Settings.System.getConfiguration(resolver, configuration);
13973 if (forceRtl) {
13974 // This will take care of setting the correct layout direction flags
13975 configuration.setLayoutDirection(configuration.locale);
13976 }
13977
13978 synchronized (this) {
13979 mDebugApp = mOrigDebugApp = debugApp;
13980 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
13981 mAlwaysFinishActivities = alwaysFinishActivities;
13982 mSupportsLeanbackOnly = supportsLeanbackOnly;
13983 mForceResizableActivities = forceResizable;
13984 final boolean multiWindowFormEnabled = freeformWindowManagement
13985 || supportsSplitScreenMultiWindow
13986 || supportsPictureInPicture
13987 || supportsMultiDisplay;
13988 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
13989 mSupportsMultiWindow = true;
13990 mSupportsFreeformWindowManagement = freeformWindowManagement;
13991 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
13992 mSupportsPictureInPicture = supportsPictureInPicture;
13993 mSupportsMultiDisplay = supportsMultiDisplay;
13994 } else {
13995 mSupportsMultiWindow = false;
13996 mSupportsFreeformWindowManagement = false;
13997 mSupportsSplitScreenMultiWindow = false;
13998 mSupportsPictureInPicture = false;
13999 mSupportsMultiDisplay = false;
14000 }
14001 mWindowManager.setForceResizableTasks(mForceResizableActivities);
14002 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
14003 // This happens before any activities are started, so we can change global configuration
14004 // in-place.
14005 updateConfigurationLocked(configuration, null, true);
14006 final Configuration globalConfig = getGlobalConfiguration();
14007 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
14008
14009 // Load resources only after the current configuration has been set.
14010 final Resources res = mContext.getResources();
14011 mHasRecents = res.getBoolean(com.android.internal.R.bool.config_hasRecents);
14012 mThumbnailWidth = res.getDimensionPixelSize(
14013 com.android.internal.R.dimen.thumbnail_width);
14014 mThumbnailHeight = res.getDimensionPixelSize(
14015 com.android.internal.R.dimen.thumbnail_height);
14016 mAppErrors.loadAppsNotReportingCrashesFromConfigLocked(res.getString(
14017 com.android.internal.R.string.config_appsNotReportingCrashes));
14018 mUserController.mUserSwitchUiEnabled = !res.getBoolean(
14019 com.android.internal.R.bool.config_customUserSwitchUi);
14020 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
14021 mFullscreenThumbnailScale = (float) res
14022 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
14023 (float) globalConfig.screenWidthDp;
14024 } else {
14025 mFullscreenThumbnailScale = res.getFraction(
14026 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
14027 }
14028 mWaitForNetworkTimeoutMs = waitForNetworkTimeoutMs;
14029 }
14030 }

system ready回调

 14032    public void systemReady(final Runnable goingCallback, BootTimingsTraceLog traceLog) {
14033 traceLog.traceBegin("PhaseActivityManagerReady");
14034 synchronized(this) {
14035 if (mSystemReady) {
14036 // If we're done calling all the receivers, run the next "boot phase" passed in
14037 // by the SystemServer
14038 if (goingCallback != null) {
14039 goingCallback.run();
14040 }
14041 return;
14042 }
14043
14044 mLocalDeviceIdleController
14045 = LocalServices.getService(DeviceIdleController.LocalService.class);
14046 mAssistUtils = new AssistUtils(mContext);
14047 mVrController.onSystemReady();
14048 // Make sure we have the current profile info, since it is needed for security checks.
14049 mUserController.onSystemReady();
14050 mRecentTasks.onSystemReadyLocked();
14051 mAppOpsService.systemReady();
14052 mSystemReady = true;
14053 }
14054
14055 ArrayList<ProcessRecord> procsToKill = null;
14056 synchronized(mPidsSelfLocked) {
14057 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
14058 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
14059 if (!isAllowedWhileBooting(proc.info)){
14060 if (procsToKill == null) {
14061 procsToKill = new ArrayList<ProcessRecord>();
14062 }
14063 procsToKill.add(proc);
14064 }
14065 }
14066 }
14067
14068 synchronized(this) {
14069 if (procsToKill != null) {
14070 for (int i=procsToKill.size()-1; i>=0; i--) {
14071 ProcessRecord proc = procsToKill.get(i);
14072 Slog.i(TAG, "Removing system update proc: " + proc);
14073 removeProcessLocked(proc, true, false, "system update done");
14074 }
14075 }
14076
14077 // Now that we have cleaned up any update processes, we
14078 // are ready to start launching real processes and know that
14079 // we won't trample on them any more.
14080 mProcessesReady = true;
14081 }
14082
14083 Slog.i(TAG, "System now ready");
14084 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
14085 SystemClock.uptimeMillis());
14086
14087 synchronized(this) {
14088 // Make sure we have no pre-ready processes sitting around.
14089
14090 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
14091 ResolveInfo ri = mContext.getPackageManager()
14092 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
14093 STOCK_PM_FLAGS);
14094 CharSequence errorMsg = null;
14095 if (ri != null) {
14096 ActivityInfo ai = ri.activityInfo;
14097 ApplicationInfo app = ai.applicationInfo;
14098 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
14099 mTopAction = Intent.ACTION_FACTORY_TEST;
14100 mTopData = null;
14101 mTopComponent = new ComponentName(app.packageName,
14102 ai.name);
14103 } else {
14104 errorMsg = mContext.getResources().getText(
14105 com.android.internal.R.string.factorytest_not_system);
14106 }
14107 } else {
14108 errorMsg = mContext.getResources().getText(
14109 com.android.internal.R.string.factorytest_no_action);
14110 }
14111 if (errorMsg != null) {
14112 mTopAction = null;
14113 mTopData = null;
14114 mTopComponent = null;
14115 Message msg = Message.obtain();
14116 msg.what = SHOW_FACTORY_ERROR_UI_MSG;
14117 msg.getData().putCharSequence("msg", errorMsg);
14118 mUiHandler.sendMessage(msg);
14119 }
14120 }
14121 }
14122
14123 retrieveSettings();
14124 final int currentUserId;
14125 synchronized (this) {
14126 currentUserId = mUserController.getCurrentUserIdLocked();
14127 readGrantedUriPermissionsLocked();
14128 }
14129
14130 if (goingCallback != null) goingCallback.run();
14131 traceLog.traceBegin("ActivityManagerStartApps");
14132 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
14133 Integer.toString(currentUserId), currentUserId);
14134 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
14135 Integer.toString(currentUserId), currentUserId);
14136 mSystemServiceManager.startUser(currentUserId);
14137
14138 synchronized (this) {
14139 // Only start up encryption-aware persistent apps; once user is
14140 // unlocked we'll come back around and start unaware apps
14141 startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
14142
14143 // Start up initial activity.
14144 mBooting = true;
14145 // Enable home activity for system user, so that the system can always boot. We don't
14146 // do this when the system user is not setup since the setup wizard should be the one
14147 // to handle home activity in this case.
14148 if (UserManager.isSplitSystemUser() &&
14149 Settings.Secure.getInt(mContext.getContentResolver(),
14150 Settings.Secure.USER_SETUP_COMPLETE, 0) != 0) {
14151 ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
14152 try {
14153 AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
14154 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
14155 UserHandle.USER_SYSTEM);
14156 } catch (RemoteException e) {
14157 throw e.rethrowAsRuntimeException();
14158 }
14159 }
14160 startHomeActivityLocked(currentUserId, "systemReady");
14161
14162 try {
14163 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
14164 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
14165 + " data partition or your device will be unstable.");
14166 mUiHandler.obtainMessage(SHOW_UID_ERROR_UI_MSG).sendToTarget();
14167 }
14168 } catch (RemoteException e) {
14169 }
14170
14171 if (!Build.isBuildConsistent()) {
14172 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
14173 mUiHandler.obtainMessage(SHOW_FINGERPRINT_ERROR_UI_MSG).sendToTarget();
14174 }
14175
14176 long ident = Binder.clearCallingIdentity();
14177 try {
14178 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
14179 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14180 | Intent.FLAG_RECEIVER_FOREGROUND);
14181 intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
14182 broadcastIntentLocked(null, null, intent,
14183 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
14184 null, false, false, MY_PID, SYSTEM_UID,
14185 currentUserId);
14186 intent = new Intent(Intent.ACTION_USER_STARTING);
14187 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14188 intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
14189 broadcastIntentLocked(null, null, intent,
14190 null, new IIntentReceiver.Stub() {
14191 @Override
14192 public void performReceive(Intent intent, int resultCode, String data,
14193 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
14194 throws RemoteException {
14195 }
14196 }, 0, null, null,
14197 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
14198 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
14199 } catch (Throwable t) {
14200 Slog.wtf(TAG, "Failed sending first user broadcasts", t);
14201 } finally {
14202 Binder.restoreCallingIdentity(ident);
14203 }
14204 mStackSupervisor.resumeFocusedStackTopActivityLocked();
14205 mUserController.sendUserSwitchBroadcastsLocked(-1, currentUserId);
14206 traceLog.traceEnd(); // ActivityManagerStartApps
14207 traceLog.traceEnd(); // PhaseActivityManagerReady
14208 }
14209 }

根据用户请求杀掉app

 14211    void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
14212 synchronized (this) {
14213 mAppErrors.killAppAtUserRequestLocked(app, fromDialog);
14214 }
14215 }

跳过当前接收的广播

 14217    void skipCurrentReceiverLocked(ProcessRecord app) {
14218 for (BroadcastQueue queue : mBroadcastQueues) {
14219 queue.skipCurrentReceiverLocked(app);
14220 }
14221

【8.0.0_r4】AMS分析(十六)(ActivityManagerService.java上)的更多相关文章

  1. 《手把手教你》系列技巧篇(五十六)-java+ selenium自动化测试-下载文件-上篇(详细教程)

    1.简介 前边几篇文章讲解完如何上传文件,既然有上传,那么就可能会有下载文件.因此宏哥就接着讲解和分享一下:自动化测试下载文件.可能有的小伙伴或者童鞋们会觉得这不是很简单吗,还用你介绍和讲解啊,不说就 ...

  2. 《手把手教你》系列技巧篇(六十六)-java+ selenium自动化测试 - 读写excel文件 - 上篇(详细教程)

    1.简介 在自动化测试,有些我们的测试数据是放到excel文件中,尤其是在做数据驱动测试的时候,所以需要懂得如何操作获取excel内的内容.由于java不像python那样有直接操作Excle文件的类 ...

  3. 《手把手教你》系列基础篇(七十六)-java+ selenium自动化测试-框架设计基础-TestNG实现DDT - 下篇(详解教程)

    1.简介 今天这一篇宏哥主要是结合实际工作中将遇到的测试场景和前边两篇学习的知识结合起来给大家讲解和分享一下,希望以后大家在以后遇到其他的测试场景也可以将自己的所学的知识应用到测试场景中. 2.测试场 ...

  4. 《手把手教你》系列技巧篇(三十六)-java+ selenium自动化测试-单选和多选按钮操作-番外篇(详解教程)

    1.简介 前边几篇文章是宏哥自己在本地弄了一个单选和多选的demo,然后又找了网上相关联的例子给小伙伴或童鞋们演示了一下如何自动化测试,这一篇宏哥在网上找了一个问卷调查,给小伙伴或童鞋们来演示一下.上 ...

  5. 《手把手教你》系列基础篇(八十六)-java+ selenium自动化测试-框架设计基础-Log4j实现日志输出(详解教程)

    1.简介 自动化测试中如何输出日志文件.任何软件,都会涉及到日志输出.所以,在测试人员报bug,特别是崩溃的bug,一般都要提供软件产品的日志文件.开发通过看日志文件,知道这个崩溃产生的原因,至少知道 ...

  6. 从壹开始前后端分离 [ Vue2.0+.NET Core2.1] 十六 ║Vue基础:ES6初体验 & 模块化编程

    缘起 昨天说到了<从壹开始前后端分离 [ Vue2.0+.NET Core2.1] 十五 ║ Vue前篇:JS对象&字面量&this>,通过总体来看,好像大家对这一块不是很 ...

  7. 第十六周Java实验作业

    实验十六  线程技术 实验时间 2017-12-8 1.实验目的与要求 (1) 掌握线程概念: 多线程是进程执行过程中产生的多条执行线索,线程是比进程执行更小的单位. 线程不能独立存在,必须存在于进程 ...

  8. 《手把手教你》系列技巧篇(十六)-java+ selenium自动化测试-元素定位大法之By xpath下卷(详细教程)

    1.简介 按宏哥计划,本文继续介绍WebDriver关于元素定位大法,这篇介绍定位倒数二个方法:By xpath.xpath 的定位方法, 非常强大.  使用这种方法几乎可以定位到页面上的任意元素. ...

  9. 《手把手教你》系列技巧篇(四十六)-java+ selenium自动化测试-web页面定位toast-下篇(详解教程)

    1.简介 终于经过宏哥的不懈努力,偶然发现了一个toast的web页面,所以直接就用这个页面来夯实一下,上一篇学过的知识-处理toast元素. 2.安居客 事先声明啊,宏哥没有收他们的广告费啊,纯粹是 ...

随机推荐

  1. python中时间戳,datetime 和时间字符串之间得转换

    # datetime时间转为字符串def Changestr(datetime1):    str1 = datetime1.strftime('%Y-%m-%d %H:%M:%S')    retu ...

  2. HDU4405 Aeroplane chess (概率DP,转移)

    http://acm.hdu.edu.cn/showproblem.php?pid=4405 题意:在一个1×n的格子上掷色子,从0点出发,掷了多少前进几步,同时有些格点直接相连,即若a,b相连,当落 ...

  3. 线段树2(P3373)

    传送 感谢洛谷题解让我理清了这一撮标记 这里多了一个乘法操作,乘法的优先级高于加法.我们来思考一下有关标记的问题. 首先由两种操作,可以想到要有两个标记,一个标记乘法(mul[k]),一个标记加法(a ...

  4. windows10上使用一个tomcat部署2个项目

    前言:目前想在本机部署2个项目,网上查了之后,写下本篇随笔 1.准备工作 2.操作方法 3.运行2个项目 1.准备工作 2个war包(一个jprss.war和一个jenkins.war) 1个tomc ...

  5. 【春训团队赛第四场】补题 | MST上倍增 | LCA | DAG上最长路 | 思维 | 素数筛 | 找规律 | 计几 | 背包 | 并查集

    春训团队赛第四场 ID A B C D E F G H I J K L M AC O O O O O O O O O 补题 ? ? O O 传送门 题目链接(CF Gym102021) 题解链接(pd ...

  6. Mac010--IDEA安装及应用

    Mac--IDEA安装及应用 应用IDEA,首先确保已安装如下环境: JDK:JDK是整个java开发的核心,它包含了JAVA的运行环境,JAVA工具和JAVA基础的类库(安装 & 配置环境变 ...

  7. jQuery基础--jQuery特殊属性操作

    1.index() 会返回当前元素在所有兄弟元素里面的索引. <!DOCTYPE html> <html lang="zh-CN"> <head> ...

  8. TCP协议分析(包结构)---转

    TCP首部格式 tcp数据是被封装在IP数据包中的,和udp类似,在IP数据包的数据部分.tcp数据包的格式如下: 源端口号和目的端口号(寻址)与udp中类似,用于寻找发端和收端应用进程.这两个值加上 ...

  9. Linux系统的镜像文件iso下载地址

    CentOS-6.1-x86_64-bin-DVD1.iso 官方网址:http://archive.kernel.org/centos-vault/6.1/isos/x86_64/ 下载链接地址:h ...

  10. CentOS下编译Lua使得其支持动态链接

    在Linux下编译Lua时,我一般都是使用的make generic,这样编译没有什么问题,运行lua的程序也都OK,但是,这样在加载外部的C动态 链接库,却总是报下面的错误 dynamic libr ...