【8.0.0_r4】AMS分析(十六)(ActivityManagerService.java上)
2018-05-15 11:46 cascle 阅读(4593) 评论(0) 收藏 举报代码位于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接口
1 456public class ActivityManagerService extends IActivityManager.Stub 2 457 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback { 3 458
顶端app的启动优先级
1 459 /** 2 460 * Priority we boost main thread and RT of top app to. 3 461 */ 4 462 public static final int TOP_APP_PRIORITY_BOOST = -10; 5 463
相应tag
1 464 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM; 2 465 private static final String TAG_BACKUP = TAG + POSTFIX_BACKUP; 3 466 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST; 4 467 private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP; 5 468 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION; 6 469 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS; 7 470 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE; 8 471 private static final String TAG_LOCKSCREEN = TAG + POSTFIX_LOCKSCREEN; 9 472 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK; 10 473 private static final String TAG_LRU = TAG + POSTFIX_LRU; 11 474 private static final String TAG_MU = TAG + POSTFIX_MU; 12 475 private static final String TAG_NETWORK = TAG + POSTFIX_NETWORK; 13 476 private static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ; 14 477 private static final String TAG_POWER = TAG + POSTFIX_POWER; 15 478 private static final String TAG_PROCESS_OBSERVERS = TAG + POSTFIX_PROCESS_OBSERVERS; 16 479 private static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES; 17 480 private static final String TAG_PROVIDER = TAG + POSTFIX_PROVIDER; 18 481 private static final String TAG_PSS = TAG + POSTFIX_PSS; 19 482 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS; 20 483 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE; 21 484 private static final String TAG_STACK = TAG + POSTFIX_STACK; 22 485 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH; 23 486 private static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS; 24 487 private static final String TAG_URI_PERMISSION = TAG + POSTFIX_URI_PERMISSION; 25 488 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY; 26 489 private static final String TAG_VISIBLE_BEHIND = TAG + POSTFIX_VISIBLE_BEHIND;
trigger idle action字符串
1 491 // Mock "pretend we're idle now" broadcast action to the job scheduler; declared 2 492 // here so that while the job scheduler can depend on AMS, the other way around 3 493 // need not be the case. 4 494 public static final String ACTION_TRIGGER_IDLE = "com.android.server.ACTION_TRIGGER_IDLE";
monitor cpu时间间隔与状态
1 496 /** Control over CPU and battery monitoring */ 2 497 // write battery stats every 30 minutes. 3 498 static final long BATTERY_STATS_TIME = 30 * 60 * 1000; 4 499 static final boolean MONITOR_CPU_USAGE = true; 5 500 // don't sample cpu less than every 5 seconds. 6 501 static final long MONITOR_CPU_MIN_TIME = 5 * 1000; 7 502 // wait possibly forever for next cpu sample. 8 503 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; 9 504 static final boolean MONITOR_THREAD_CPU_USAGE = false;
出货的package manager flag
1 505 2 506 // The flags that are set for all calls we make to the package manager. 3 507 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
是否可以调试属性
1 509 static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
是否是user版本
1 511 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
相应的时间配置
1 513 // Amount of time after a call to stopAppSwitches() during which we will 2 514 // prevent further untrusted switches from happening. 3 515 static final long APP_SWITCH_DELAY_TIME = 5*1000; 4 516 5 517 // How long we wait for a launched process to attach to the activity manager 6 518 // before we decide it's never going to come up for real. 7 519 static final int PROC_START_TIMEOUT = 10*1000; 8 520 // How long we wait for an attached process to publish its content providers 9 521 // before we decide it must be hung. 10 522 static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT = 10*1000; 11 523 12 524 // How long we wait for a launched process to attach to the activity manager 13 525 // before we decide it's never going to come up for real, when the process was 14 526 // started with a wrapper for instrumentation (such as Valgrind) because it 15 527 // could take much longer than usual. 16 528 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000; 17 529 18 530 // How long we allow a receiver to run before giving up on it. 19 531 static final int BROADCAST_FG_TIMEOUT = 10*1000; 20 532 static final int BROADCAST_BG_TIMEOUT = 60*1000; 21 533 22 534 // How long we wait until we timeout on key dispatching. 23 535 static final int KEY_DISPATCHING_TIMEOUT = 5*1000; 24 536 25 537 // How long we wait until we timeout on key dispatching during instrumentation. 26 538 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000; 27 539 28 540 // How long to wait in getAssistContextExtras for the activity and foreground services 29 541 // to respond with the result. 30 542 static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500; 31 543 32 544 // How long top wait when going through the modern assist (which doesn't need to block 33 545 // on getting this result before starting to launch its UI). 34 546 static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000; 35 547 36 548 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result. 37 549 static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
一个package最大可被授权的权限数量
1 551 // Maximum number of persisted Uri grants a package is allowed 2 552 static final int MAX_PERSISTED_URI_GRANTS = 128;
my pid
1 554 static final int MY_PID = myPid();
空String数组
1 556 static final String[] EMPTY_STRING_ARRAY = new String[0];
dropbox大小,logcat line的保留byte数
1 558 // How many bytes to write into the dropbox log before truncating 2 559 static final int DROPBOX_MAX_SIZE = 192 * 1024; 3 560 // Assumes logcat entries average around 100 bytes; that's not perfect stack traces count 4 561 // as one line, but close enough for now. 5 562 static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100;
处理即将使用的用户的模式
1 564 // Access modes for handleIncomingUser. 2 565 static final int ALLOW_NON_FULL = 0; 3 566 static final int ALLOW_NON_FULL_IN_PROFILE = 1; 4 567 static final int ALLOW_FULL_ONLY = 2;
persistent app的flag
1 569 // Necessary ApplicationInfo flags to mark an app as persistent 2 570 private static final int PERSISTENT_MASK = 3 571 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT;
bugreport finish Intent
1 573 // Intent sent when remote bugreport collection has been completed 2 574 private static final String INTENT_REMOTE_BUGREPORT_FINISHED = 3 575 "com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED";
是否做动画,是否录屏
1 577 // Used to indicate that an app transition should be animated. 2 578 static final boolean ANIMATE = true; 3 579 4 580 // Determines whether to take full screen screenshots 5 581 static final boolean TAKE_FULLSCREEN_SCREENSHOTS = true;
网络状态
1 583 /** 2 584 * Default value for {@link Settings.Global#NETWORK_ACCESS_TIMEOUT_MS}. 3 585 */ 4 586 private static final long NETWORK_ACCESS_TIMEOUT_DEFAULT_MS = 200; // 0.2 sec 5 587 6 588 /** 7 589 * State indicating that there is no need for any blocking for network. 8 590 */ 9 591 @VisibleForTesting 10 592 static final int NETWORK_STATE_NO_CHANGE = 0; 11 593 12 594 /** 13 595 * State indicating that the main thread needs to be informed about the network wait. 14 596 */ 15 597 @VisibleForTesting 16 598 static final int NETWORK_STATE_BLOCK = 1; 17 599 18 600 /** 19 601 * State indicating that any threads waiting for network state to get updated can be unblocked. 20 602 */ 21 603 @VisibleForTesting 22 604 static final int NETWORK_STATE_UNBLOCK = 2;
bug report最大title size
1 606 // Max character limit for a notification title. If the notification title is larger than this 2 607 // the notification will not be legible to the user. 3 608 private static final int MAX_BUGREPORT_TITLE_SIZE = 50;
所有的系统服务和辅助工具
1 610 /** All system services */ 2 611 SystemServiceManager mSystemServiceManager; 3 612 AssistUtils mAssistUtils;
安装器
1 614 private Installer mInstaller;
activity stack管理者,锁屏,activity starter,task变更通知控制器,性能测试reporter,ActiveInstrumentation列表,IntentFirewall
1 616 /** Run all ActivityStacks through this */ 2 617 final ActivityStackSupervisor mStackSupervisor; 3 618 private final KeyguardController mKeyguardController; 4 619 5 620 final ActivityStarter mActivityStarter; 6 621 7 622 final TaskChangeNotificationController mTaskChangeNotificationController; 8 623 9 624 final InstrumentationReporter mInstrumentationReporter = new InstrumentationReporter(); 10 625 11 626 final ArrayList<ActiveInstrumentation> mActiveInstrumentation = new ArrayList<>(); 12 627 13 628 public final IntentFirewall mIntentFirewall;
是否显示dialog
1 630 // Whether we should show our dialogs (ANR, crash, etc) or just perform their 2 631 // default action automatically. Important for devices without direct input 3 632 // devices. 4 633 private boolean mShowDialogs = true;
vr控制器和其display
1 635 private final VrController mVrController; 2 636 3 637 // VR Vr2d Display Id. 4 638 int mVr2dDisplayId = INVALID_DISPLAY;
是否对ui线程使用fifo
1 640 // Whether we should use SCHED_FIFO for UI and RenderThreads. 2 641 private boolean mUseFifoUiScheduling = false;
broadcast queue和状态
1 643 BroadcastQueue mFgBroadcastQueue; 2 644 BroadcastQueue mBgBroadcastQueue; 3 645 // Convenient for easy iteration over the queues. Foreground is first 4 646 // so that dispatch of foreground broadcasts gets precedence. 5 647 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2]; 6 648 7 649 BroadcastStats mLastBroadcastStats; 8 650 BroadcastStats mCurBroadcastStats; 9 651 10 652 BroadcastQueue broadcastQueueForIntent(Intent intent) { 11 653 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0; 12 654 if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST, 13 655 "Broadcast intent " + intent + " on " 14 656 + (isFg ? "foreground" : "background") + " queue"); 15 657 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue; 16 658 } 17 659
相应的组件历史记录
1 660 /** 2 661 * The last resumed activity. This is identical to the current resumed activity most 3 662 * of the time but could be different when we're pausing one activity before we resume 4 663 * another activity. 5 664 */ 6 665 private ActivityRecord mLastResumedActivity; 7 666 8 667 /** 9 668 * If non-null, we are tracking the time the user spends in the currently focused app. 10 669 */ 11 670 private AppTimeTracker mCurAppTimeTracker; 12 671 13 672 /** 14 673 * List of intents that were used to start the most recent tasks. 15 674 */ 16 675 final RecentTasks mRecentTasks; 17 676 18 677 /** 19 678 * For addAppTask: cached of the last activity component that was added. 20 679 */ 21 680 ComponentName mLastAddedTaskComponent; 22 681 23 682 /** 24 683 * For addAppTask: cached of the last activity uid that was added. 25 684 */ 26 685 int mLastAddedTaskUid; 27 686 28 687 /** 29 688 * For addAppTask: cached of the last ActivityInfo that was added. 30 689 */ 31 690 ActivityInfo mLastAddedTaskActivity; 32 691 33 692 /** 34 693 * List of packages whitelisted by DevicePolicyManager for locktask. Indexed by userId. 35 694 */ 36 695 SparseArray<String[]> mLockTaskPackages = new SparseArray<>(); 37 696 38 697 /** 39 698 * The package name of the DeviceOwner. This package is not permitted to have its data cleared. 40 699 */ 41 700 String mDeviceOwnerName; 42 701 43 702 final UserController mUserController; 44 703 45 704 final AppErrors mAppErrors; 46 705 47 706 /** 48 707 * Dump of the activity state at the time of the last ANR. Cleared after 49 708 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS} 50 709 */ 51 710 String mLastANRState;
网络等待超时时长
1 712 /** 2 713 * Indicates the maximum time spent waiting for the network rules to get updated. 3 714 */ 4 715 @VisibleForTesting 5 716 long mWaitForNetworkTimeoutMs;
是否显示错误对话框
1 718 public boolean canShowErrorDialogs() { 2 719 return mShowDialogs && !mSleeping && !mShuttingDown 3 720 && !mKeyguardController.isKeyguardShowing(); 4 721 }
线程优先级booster
1 723 private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster( 2 724 THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_ACTIVITY); 3 725 4 726 static void boostPriorityForLockedSection() { 5 727 sThreadPriorityBooster.boost(); 6 728 } 7 729 8 730 static void resetPriorityAfterLockedSection() { 9 731 sThreadPriorityBooster.reset(); 10 732 }
pending辅助类
1 34 public class PendingAssistExtras extends Binder implements Runnable { 2 735 public final ActivityRecord activity; 3 736 public boolean isHome; 4 737 public final Bundle extras; 5 738 public final Intent intent; 6 739 public final String hint; 7 740 public final IResultReceiver receiver; 8 741 public final int userHandle; 9 742 public boolean haveResult = false; 10 743 public Bundle result = null; 11 744 public AssistStructure structure = null; 12 745 public AssistContent content = null; 13 746 public Bundle receiverExtras; 14 747 15 748 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent, 16 749 String _hint, IResultReceiver _receiver, Bundle _receiverExtras, int _userHandle) { 17 750 activity = _activity; 18 751 extras = _extras; 19 752 intent = _intent; 20 753 hint = _hint; 21 754 receiver = _receiver; 22 755 receiverExtras = _receiverExtras; 23 756 userHandle = _userHandle; 24 757 } 25 758 26 759 @Override 27 760 public void run() { 28 761 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity); 29 762 synchronized (this) { 30 763 haveResult = true; 31 764 notifyAll(); 32 765 } 33 766 pendingAssistExtrasTimedOut(this); 34 767 } 35 768 } 36 769 37 770 final ArrayList<PendingAssistExtras> mPendingAssistExtras 38 771 = new ArrayList<PendingAssistExtras>(); 39 772
进程相关变量
1 70 final ArrayList<PendingAssistExtras> mPendingAssistExtras 2 771 = new ArrayList<PendingAssistExtras>(); 3 772 4 773 /** 5 774 * Process management. 6 775 */ 7 776 final ProcessList mProcessList = new ProcessList(); 8 777 9 778 /** 10 779 * All of the applications we currently have running organized by name. 11 780 * The keys are strings of the application package name (as 12 781 * returned by the package manager), and the keys are ApplicationRecord 13 782 * objects. 14 783 */ 15 784 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>(); 16 785 17 786 /** 18 787 * Tracking long-term execution of processes to look for abuse and other 19 788 * bad app behavior. 20 789 */ 21 790 final ProcessStatsService mProcessStats; 22 791 23 792 /** 24 793 * The currently running isolated processes. 25 794 */ 26 795 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>(); 27 796 28 797 /** 29 798 * Counter for assigning isolated process uids, to avoid frequently reusing the 30 799 * same ones. 31 800 */ 32 801 int mNextIsolatedProcessUid = 0; 33 802 34 803 /** 35 804 * The currently running heavy-weight process, if any. 36 805 */ 37 806 ProcessRecord mHeavyWeightProcess = null; 38 807 39 808 /** 40 809 * Non-persistent appId whitelist for background restrictions 41 810 */ 42 811 int[] mBackgroundAppIdWhitelist = new int[] { 43 812 BLUETOOTH_UID 44 813 }; 45 814 46 815 /** 47 816 * Broadcast actions that will always be deliverable to unlaunched/background apps 48 817 */ 49 818 ArraySet<String> mBackgroundLaunchBroadcasts; 50 819 51 820 /** 52 821 * All of the processes we currently have running organized by pid. 53 822 * The keys are the pid running the application. 54 823 * 55 824 * <p>NOTE: This object is protected by its own lock, NOT the global 56 825 * activity manager lock! 57 826 */ 58 827 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
重要进程的token身份,包括名字, IBinder和原因
1 829 /** 2 830 * All of the processes that have been forced to be important. The key 3 831 * is the pid of the caller who requested it (we hold a death 4 832 * link on it). 5 833 */ 6 834 abstract class ImportanceToken implements IBinder.DeathRecipient { 7 835 final int pid; 8 836 final IBinder token; 9 837 final String reason; 10 838 11 839 ImportanceToken(int _pid, IBinder _token, String _reason) { 12 840 pid = _pid; 13 841 token = _token; 14 842 reason = _reason; 15 843 } 16 844 17 845 @Override 18 846 public String toString() { 19 847 return "ImportanceToken { " + Integer.toHexString(System.identityHashCode(this)) 20 848 + " " + reason + " " + pid + " " + token + " }"; 21 849 } 22 850 }
重要进程列表
1 851 final SparseArray<ImportanceToken> mImportantProcesses = new SparseArray<ImportanceToken>();
等待系统初始化完毕后启动的进程列表
1 853 /** 2 854 * List of records for processes that someone had tried to start before the 3 855 * system was ready. We don't start them at that point, but ensure they 4 856 * are started by the time booting is complete. 5 857 */ 6 858 final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>();
其他相关的进程信息
1 860 /** 2 861 * List of persistent applications that are in the process 3 862 * of being started. 4 863 */ 5 864 final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>(); 6 865 7 866 /** 8 867 * Processes that are being forcibly torn down. 9 868 */ 10 869 final ArrayList<ProcessRecord> mRemovedProcesses = new ArrayList<ProcessRecord>(); 11 870 12 871 /** 13 872 * List of running applications, sorted by recent usage. 14 873 * The first entry in the list is the least recently used. 15 874 */ 16 875 final ArrayList<ProcessRecord> mLruProcesses = new ArrayList<ProcessRecord>(); 17 876 18 877 /** 19 878 * Where in mLruProcesses that the processes hosting activities start. 20 879 */ 21 880 int mLruProcessActivityStart = 0; 22 881 23 882 /** 24 883 * Where in mLruProcesses that the processes hosting services start. 25 884 * This is after (lower index) than mLruProcessesActivityStart. 26 885 */ 27 886 int mLruProcessServiceStart = 0; 28 887 29 888 /** 30 889 * List of processes that should gc as soon as things are idle. 31 890 */ 32 891 final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>(); 33 892 34 893 /** 35 894 * Processes we want to collect PSS data from. 36 895 */ 37 896 final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>(); 38 897 39 898 private boolean mBinderTransactionTrackingEnabled = false; 40 899 41 900 /** 42 901 * Last time we requested PSS data of all processes. 43 902 */ 44 903 long mLastFullPssTime = SystemClock.uptimeMillis(); 45 904 46 905 /** 47 906 * If set, the next time we collect PSS data we should do a full collection 48 907 * with data from native processes and the kernel. 49 908 */ 50 909 boolean mFullPssPending = false; 51 910 52 911 /** 53 912 * This is the process holding what we currently consider to be 54 913 * the "home" activity. 55 914 */ 56 915 ProcessRecord mHomeProcess; 57 916 58 917 /** 59 918 * This is the process holding the activity the user last visited that 60 919 * is in a different process from the one they are currently in. 61 920 */ 62 921 ProcessRecord mPreviousProcess; 63 922 64 923 /** 65 924 * The time at which the previous process was last visible. 66 925 */ 67 926 long mPreviousProcessVisibleTime;
Uid相关
1 928 /** 2 929 * Track all uids that have actively running processes. 3 930 */ 4 931 final SparseArray<UidRecord> mActiveUids = new SparseArray<>(); 5 932 6 933 /** 7 934 * This is for verifying the UID report flow. 8 935 */ 9 936 static final boolean VALIDATE_UID_STATES = true; 10 937 final SparseArray<UidRecord> mValidateUids = new SparseArray<>();
兼容模式包
1 939 /** 2 940 * Packages that the user has asked to have run in screen size 3 941 * compatibility mode instead of filling the screen. 4 942 */ 5 943 final CompatModePackages mCompatModePackages; 6 944
Intent发送记录
1 945 /** 2 946 * Set of IntentSenderRecord objects that are currently active. 3 947 */ 4 948 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords 5 949 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
已经记录的违规log
1 951 /** 2 952 * Fingerprints (hashCode()) of stack traces that we've 3 953 * already logged DropBox entries for. Guarded by itself. If 4 954 * something (rogue user app) forces this over 5 955 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared. 6 956 */ 7 957 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>(); 8 958 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
strict mode buffer
1 960 /** 2 961 * Strict Mode background batched logging state. 3 962 * 4 963 * The string buffer is guarded by itself, and its lock is also 5 964 * used to determine if another batched write is already 6 965 * in-flight. 7 966 */ 8 967 private final StringBuilder mStrictModeBuffer = new StringBuilder();
已经注册的receiver
1 969 /** 2 970 * Keeps track of all IIntentReceivers that have been registered for broadcasts. 3 971 * Hash keys are the receiver IBinder, hash value is a ReceiverList. 4 972 */ 5 973 final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>(); 6 974
intent解析器
1 975 /** 2 976 * Resolver for broadcast intents to registered receivers. 3 977 * Holds BroadcastFilter (subclass of IntentFilter). 4 978 */ 5 979 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver 6 980 = new IntentResolver<BroadcastFilter, BroadcastFilter>() { 7 981 @Override 8 982 protected boolean allowFilterResult( 9 983 BroadcastFilter filter, List<BroadcastFilter> dest) { 10 984 IBinder target = filter.receiverList.receiver.asBinder(); 11 985 for (int i = dest.size() - 1; i >= 0; i--) { 12 986 if (dest.get(i).receiverList.receiver.asBinder() == target) { 13 987 return false; 14 988 } 15 989 } 16 990 return true; 17 991 } 18 992 19 993 @Override 20 994 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) { 21 995 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL 22 996 || userId == filter.owningUserId) { 23 997 return super.newResult(filter, match, userId); 24 998 } 25 999 return null; 26 1000 } 27 1001 28 1002 @Override 29 1003 protected BroadcastFilter[] newArray(int size) { 30 1004 return new BroadcastFilter[size]; 31 1005 } 32 1006 33 1007 @Override 34 1008 protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) { 35 1009 return packageName.equals(filter.packageName); 36 1010 } 37 1011 }; 38 1012
严格广播
1 1013 /** 2 1014 * State of all active sticky broadcasts per user. Keys are the action of the 3 1015 * sticky Intent, values are an ArrayList of all broadcasted intents with 4 1016 * that action (which should usually be one). The SparseArray is keyed 5 1017 * by the user ID the sticky is for, and can include UserHandle.USER_ALL 6 1018 * for stickies that are sent to all users. 7 1019 */ 8 1020 final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts = 9 1021 new SparseArray<ArrayMap<String, ArrayList<Intent>>>(); 10 1022
活跃的service
1 1023 final ActiveServices mServices;
进程间的关联
1 1025 final static class Association { 2 1026 final int mSourceUid; 3 1027 final String mSourceProcess; 4 1028 final int mTargetUid; 5 1029 final ComponentName mTargetComponent; 6 1030 final String mTargetProcess; 7 1031 8 1032 int mCount; 9 1033 long mTime; 10 1034 11 1035 int mNesting; 12 1036 long mStartTime; 13 1037 14 1038 // states of the source process when the bind occurred. 15 1039 int mLastState = ActivityManager.MAX_PROCESS_STATE + 1; 16 1040 long mLastStateUptime; 17 1041 long[] mStateTimes = new long[ActivityManager.MAX_PROCESS_STATE 18 1042 - ActivityManager.MIN_PROCESS_STATE+1]; 19 1043 20 1044 Association(int sourceUid, String sourceProcess, int targetUid, 21 1045 ComponentName targetComponent, String targetProcess) { 22 1046 mSourceUid = sourceUid; 23 1047 mSourceProcess = sourceProcess; 24 1048 mTargetUid = targetUid; 25 1049 mTargetComponent = targetComponent; 26 1050 mTargetProcess = targetProcess; 27 1051 } 28 1052 }
关联的列表和状态
1 1054 /** 2 1055 * When service association tracking is enabled, this is all of the associations we 3 1056 * have seen. Mapping is target uid -> target component -> source uid -> source process name 4 1057 * -> association data. 5 1058 */ 6 1059 final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>> 7 1060 mAssociations = new SparseArray<>(); 8 1061 boolean mTrackingAssociations;
back名字和目标
1 1063 /** 2 1064 * Backup/restore process management 3 1065 */ 4 1066 String mBackupAppName = null; 5 1067 BackupRecord mBackupTarget = null;
provider map
1 1069 final ProviderMap mProviderMap;
contentprovider 列表
1 1071 /** 2 1072 * List of content providers who have clients waiting for them. The 3 1073 * application is currently being launched and the provider will be 4 1074 * removed from this list once it is published. 5 1075 */ 6 1076 final ArrayList<ContentProviderRecord> mLaunchingProviders 7 1077 = new ArrayList<ContentProviderRecord>(); 8 1078
授权文件其其相关tag和java bean类
1 1079 /** 2 1080 * File storing persisted {@link #mGrantedUriPermissions}. 3 1081 */ 4 1082 private final AtomicFile mGrantFile; 5 1083 6 1084 /** XML constants used in {@link #mGrantFile} */ 7 1085 private static final String TAG_URI_GRANTS = "uri-grants"; 8 1086 private static final String TAG_URI_GRANT = "uri-grant"; 9 1087 private static final String ATTR_USER_HANDLE = "userHandle"; 10 1088 private static final String ATTR_SOURCE_USER_ID = "sourceUserId"; 11 1089 private static final String ATTR_TARGET_USER_ID = "targetUserId"; 12 1090 private static final String ATTR_SOURCE_PKG = "sourcePkg"; 13 1091 private static final String ATTR_TARGET_PKG = "targetPkg"; 14 1092 private static final String ATTR_URI = "uri"; 15 1093 private static final String ATTR_MODE_FLAGS = "modeFlags"; 16 1094 private static final String ATTR_CREATED_TIME = "createdTime"; 17 1095 private static final String ATTR_PREFIX = "prefix"; 18 1096 19 1097 /** 20 1098 * Global set of specific {@link Uri} permissions that have been granted. 21 1099 * This optimized lookup structure maps from {@link UriPermission#targetUid} 22 1100 * to {@link UriPermission#uri} to {@link UriPermission}. 23 1101 */ 24 1102 @GuardedBy("this") 25 1103 private final SparseArray<ArrayMap<GrantUri, UriPermission>> 26 1104 mGrantedUriPermissions = new SparseArray<ArrayMap<GrantUri, UriPermission>>(); 27 1105 28 1106 public static class GrantUri { 29 1107 public final int sourceUserId; 30 1108 public final Uri uri; 31 1109 public boolean prefix; 32 1110 33 1111 public GrantUri(int sourceUserId, Uri uri, boolean prefix) { 34 1112 this.sourceUserId = sourceUserId; 35 1113 this.uri = uri; 36 1114 this.prefix = prefix; 37 1115 } 38 1116 39 1117 @Override 40 1118 public int hashCode() { 41 1119 int hashCode = 1; 42 1120 hashCode = 31 * hashCode + sourceUserId; 43 1121 hashCode = 31 * hashCode + uri.hashCode(); 44 1122 hashCode = 31 * hashCode + (prefix ? 1231 : 1237); 45 1123 return hashCode; 46 1124 } 47 1125 48 1126 @Override 49 1127 public boolean equals(Object o) { 50 1128 if (o instanceof GrantUri) { 51 1129 GrantUri other = (GrantUri) o; 52 1130 return uri.equals(other.uri) && (sourceUserId == other.sourceUserId) 53 1131 && prefix == other.prefix; 54 1132 } 55 1133 return false; 56 1134 } 57 1135 58 1136 @Override 59 1137 public String toString() { 60 1138 String result = uri.toString() + " [user " + sourceUserId + "]"; 61 1139 if (prefix) result += " [prefix]"; 62 1140 return result; 63 1141 } 64 1142 65 1143 public String toSafeString() { 66 1144 String result = uri.toSafeString() + " [user " + sourceUserId + "]"; 67 1145 if (prefix) result += " [prefix]"; 68 1146 return result; 69 1147 } 70 1148 71 1149 public static GrantUri resolve(int defaultSourceUserHandle, Uri uri) { 72 1150 return new GrantUri(ContentProvider.getUserIdFromUri(uri, defaultSourceUserHandle), 73 1151 ContentProvider.getUriWithoutUserId(uri), false); 74 1152 } 75 1153 }
核心设置observer和字体缩放设置observer
1 1155 CoreSettingsObserver mCoreSettingsObserver; 2 1156 3 1157 FontScaleSettingObserver mFontScaleSettingObserver;
font scale observer类
1 1159 private final class FontScaleSettingObserver extends ContentObserver { 2 1160 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE); 3 1161 4 1162 public FontScaleSettingObserver() { 5 1163 super(mHandler); 6 1164 ContentResolver resolver = mContext.getContentResolver(); 7 1165 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL); 8 1166 } 9 1167 10 1168 @Override 11 1169 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) { 12 1170 if (mFontScaleUri.equals(uri)) { 13 1171 updateFontScaleIfNeeded(userId); 14 1172 } 15 1173 } 16 1174 }
内部类身份
1 1176 /** 2 1177 * Thread-local storage used to carry caller permissions over through 3 1178 * indirect content-provider access. 4 1179 */ 5 1180 private class Identity { 6 1181 public final IBinder token; 7 1182 public final int pid; 8 1183 public final int uid; 9 1184 10 1185 Identity(IBinder _token, int _pid, int _uid) { 11 1186 token = _token; 12 1187 pid = _pid; 13 1188 uid = _uid; 14 1189 } 15 1190 }
调用者身份
1 1192 private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
battery 和 usage stats service
1 1194 /** 2 1195 * All information we have collected about the runtime performance of 3 1196 * any user id that can impact battery performance. 4 1197 */ 5 1198 final BatteryStatsService mBatteryStatsService; 6 1199 7 1200 /** 8 1201 * Information about component usage 9 1202 */ 10 1203 UsageStatsManagerInternal mUsageStatsService;
device idle controller 和白名单
1 1205 /** 2 1206 * Access to DeviceIdleController service. 3 1207 */ 4 1208 DeviceIdleController.LocalService mLocalDeviceIdleController; 5 1209 6 1210 /** 7 1211 * Set of app ids that are whitelisted for device idle and thus background check. 8 1212 */ 9 1213 int[] mDeviceIdleWhitelist = new int[0]; 10 1214 11 1215 /** 12 1216 * Set of app ids that are temporarily allowed to escape bg check due to high-pri message 13 1217 */ 14 1218 int[] mDeviceIdleTempWhitelist = new int[0];
延迟白名单
1 1220 static final class PendingTempWhitelist { 2 1221 final int targetUid; 3 1222 final long duration; 4 1223 final String tag; 5 1224 6 1225 PendingTempWhitelist(int _targetUid, long _duration, String _tag) { 7 1226 targetUid = _targetUid; 8 1227 duration = _duration; 9 1228 tag = _tag; 10 1229 } 11 1230 } 12 1231 13 1232 final SparseArray<PendingTempWhitelist> mPendingTempWhitelist = new SparseArray<>();
app ops service
1 1234 /** 2 1235 * Information about and control over application operations 3 1236 */ 4 1237 final AppOpsService mAppOpsService;
config seq
1 1239 /** Current sequencing integer of the configuration, for skipping old configurations. */ 2 1240 private int mConfigurationSeq; 3 1241
临时config
1 1242 /** 2 1243 * Temp object used when global and/or display override configuration is updated. It is also 3 1244 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust 4 1245 * anyone... 5 1246 */ 6 1247 private Configuration mTempConfig = new Configuration();
临时更新config result
1 1249 private final UpdateConfigurationResult mTmpUpdateConfigurationResult = 2 1250 new UpdateConfigurationResult();
1 1251 private static final class UpdateConfigurationResult { 2 1252 // Configuration changes that were updated. 3 1253 int changes; 4 1254 // If the activity was relaunched to match the new configuration. 5 1255 boolean activityRelaunched; 6 1256 7 1257 void reset() { 8 1258 changes = 0; 9 1259 activityRelaunched = false; 10 1260 } 11 1261 }
是否抑制resize config change
1 1263 boolean mSuppressResizeConfigChanges; 2 1264
open gl es版本
1 1265 /** 2 1266 * Hardware-reported OpenGLES version. 3 1267 */ 4 1268 final int GL_ES_VERSION;
app binding args
1 1270 /** 2 1271 * List of initialization arguments to pass to all processes when binding applications to them. 3 1272 * For example, references to the commonly used services. 4 1273 */ 5 1274 HashMap<String, IBinder> mAppBindArgs; 6 1275 HashMap<String, IBinder> mIsolatedAppBindArgs;
string builder
1 1277 /** 2 1278 * Temporary to avoid allocations. Protected by main lock. 3 1279 */ 4 1280 final StringBuilder mStringBuilder = new StringBuilder(256);
顶端组件,action,data
1 1282 /** 2 1283 * Used to control how we initialize the service. 3 1284 */ 4 1285 ComponentName mTopComponent; 5 1286 String mTopAction = Intent.ACTION_MAIN; 6 1287 String mTopData; 7 1288
进程、系统等是否ready flag
1 1289 volatile boolean mProcessesReady = false; 2 1290 volatile boolean mSystemReady = false; 3 1291 volatile boolean mOnBattery = false; 4 1292 volatile int mFactoryTest; 5 1293 6 1294 @GuardedBy("this") boolean mBooting = false; 7 1295 @GuardedBy("this") boolean mCallFinishBooting = false; 8 1296 @GuardedBy("this") boolean mBootAnimationComplete = false; 9 1297 @GuardedBy("this") boolean mLaunchWarningShown = false; 10 1298 @GuardedBy("this") boolean mCheckedForSetup = false;
context和ui context
1 1300 final Context mContext; 2 1301 3 1302 /** 4 1303 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can 5 1304 * change at runtime. Use mContext for non-UI purposes. 6 1305 */ 7 1306 final Context mUiContext;
app切换
1 1308 /** 2 1309 * The time at which we will allow normal application switches again, 3 1310 * after a call to {@link #stopAppSwitches()}. 4 1311 */ 5 1312 long mAppSwitchesAllowedTime; 6 1313 7 1314 /** 8 1315 * This is set to true after the first switch after mAppSwitchesAllowedTime 9 1316 * is set; any switches after that will clear the time. 10 1317 */ 11 1318 boolean mDidAppSwitch; 12 1319
睡眠状态
1 1320 /** 2 1321 * Last time (in realtime) at which we checked for power usage. 3 1322 */ 4 1323 long mLastPowerCheckRealtime; 5 1324 6 1325 /** 7 1326 * Last time (in uptime) at which we checked for power usage. 8 1327 */ 9 1328 long mLastPowerCheckUptime; 10 1329 11 1330 /** 12 1331 * Set while we are wanting to sleep, to prevent any 13 1332 * activities from being started/resumed. 14 1333 * 15 1334 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping. 16 1335 * 17 1336 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true 18 1337 * while in the sleep state until there is a pending transition out of sleep, in which case 19 1338 * mSleeping is set to false, and remains false while awake. 20 1339 * 21 1340 * Whether mSleeping can quickly toggled between true/false without the device actually 22 1341 * display changing states is undefined. 23 1342 */ 24 1343 private boolean mSleeping = false;
进程状态
1 1345 /** 2 1346 * The process state used for processes that are running the top activities. 3 1347 * This changes between TOP and TOP_SLEEPING to following mSleeping. 4 1348 */ 5 1349 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
运行的voice
1 1351 /** 2 1352 * Set while we are running a voice interaction. This overrides 3 1353 * sleeping while it is active. 4 1354 */ 5 1355 private IVoiceInteractionSession mRunningVoice;
local power manager
1 1357 /** 2 1358 * For some direct access we need to power manager. 3 1359 */ 4 1360 PowerManagerInternal mLocalPowerManager;
voice wakelock
1 1362 /** 2 1363 * We want to hold a wake lock while running a voice interaction session, since 3 1364 * this may happen with the screen off and we need to keep the CPU running to 4 1365 * be able to continue to interact with the user. 5 1366 */ 6 1367 PowerManager.WakeLock mVoiceWakeLock; 7 1368
唤醒程度
1 1369 /** 2 1370 * State of external calls telling us if the device is awake or asleep. 3 1371 */ 4 1372 private int mWakefulness = PowerManagerInternal.WAKEFULNESS_AWAKE;
睡眠token列表
1 1374 /** 2 1375 * A list of tokens that cause the top activity to be put to sleep. 3 1376 * They are used by components that may hide and block interaction with underlying 4 1377 * activities. 5 1378 */ 6 1379 final ArrayList<SleepToken> mSleepTokens = new ArrayList<SleepToken>(); 7 1380
是否关机
1 1381 /** 2 1382 * Set if we are shutting down the system, similar to sleeping. 3 1383 */ 4 1384 boolean mShuttingDown = false;
adj,lru seq
1 1386 /** 2 1387 * Current sequence id for oom_adj computation traversal. 3 1388 */ 4 1389 int mAdjSeq = 0; 5 1390 6 1391 /** 7 1392 * Current sequence id for process LRU updating. 8 1393 */ 9 1394 int mLruSeq = 0;
cache process数量
1 1396 /** 2 1397 * Keep track of the non-cached/empty process we last found, to help 3 1398 * determine how to distribute cached/empty processes next time. 4 1399 */ 5 1400 int mNumNonCachedProcs = 0; 6 1401 7 1402 /** 8 1403 * Keep track of the number of cached hidden procs, to balance oom adj 9 1404 * distribution between those and empty procs. 10 1405 */ 11 1406 int mNumCachedHiddenProcs = 0;
进程数量
1 1408 /** 2 1409 * Keep track of the number of service processes we last found, to 3 1410 * determine on the next iteration which should be B services. 4 1411 */ 5 1412 int mNumServiceProcs = 0; 6 1413 int mNewNumAServiceProcs = 0; 7 1414 int mNewNumServiceProcs = 0;
允许的memory level
1 1416 /** 2 1417 * Allow the current computed overall memory level of the system to go down? 3 1418 * This is set to false when we are killing processes for reasons other than 4 1419 * memory management, so that the now smaller process list will not be taken as 5 1420 * an indication that memory is tighter. 6 1421 */ 7 1422 boolean mAllowLowerMemLevel = false; 8 1423
上一次的内存级别与进程数量
1 1424 /** 2 1425 * The last computed memory level, for holding when we are in a state that 3 1426 * processes are going away for other reasons. 4 1427 */ 5 1428 int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL; 6 1429 7 1430 /** 8 1431 * The last total number of process we have, to determine if changes actually look 9 1432 * like a shrinking number of process due to lower RAM. 10 1433 */ 11 1434 int mLastNumProcesses; 12 1435
上一次idle时间
1 1437 * The uptime of the last time we performed idle maintenance. 2 1438 */ 3 1439 long mLastIdleTime = SystemClock.uptimeMillis();
自从idle后低内存时间
1 1441 /** 2 1442 * Total time spent with RAM that has been added in the past since the last idle time. 3 1443 */ 4 1444 long mLowRamTimeSinceLastIdle = 0;
上一次低内存开始时间
1 1446 /** 2 1447 * If RAM is currently low, when that horrible situation started. 3 1448 */ 4 1449 long mLowRamStartTime = 0;
当前恢复的pacakge,当前恢复的uid
1 1451 /** 2 1452 * For reporting to battery stats the current top application. 3 1453 */ 4 1454 private String mCurResumedPackage = null; 5 1455 private int mCurResumedUid = -1;
前台运行的包
1 1457 /** 2 1458 * For reporting to battery stats the apps currently running foreground 3 1459 * service. The ProcessMap is package/uid tuples; each of these contain 4 1460 * an array of the currently foreground processes. 5 1461 */ 6 1462 final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages 7 1463 = new ProcessMap<ArrayList<ProcessRecord>>();
是否做了dexopt
1 1465 /** 2 1466 * This is set if we had to do a delayed dexopt of an app before launching 3 1467 * it, to increase the ANR timeouts in that case. 4 1468 */ 5 1469 boolean mDidDexOpt;
是否是安全模式
1 1471 /** 2 1472 * Set if the systemServer made a call to enterSafeMode. 3 1473 */ 4 1474 boolean mSafeMode;
是否是test pss模式
1 1476 /** 2 1477 * If true, we are running under a test environment so will sample PSS from processes 3 1478 * much more rapidly to try to collect better data when the tests are rapidly 4 1479 * running through apps. 5 1480 */ 6 1481 boolean mTestPssMode = false;
debug相关
1 1483 String mDebugApp = null; 2 1484 boolean mWaitForDebugger = false; 3 1485 boolean mDebugTransient = false; 4 1486 String mOrigDebugApp = null; 5 1487 boolean mOrigWaitForDebugger = false;
是否总是总是activity;是否强制resize activity
1 1488 boolean mAlwaysFinishActivities = false; 2 1489 boolean mForceResizableActivities;
支持的特性
1 1490 /** 2 1491 * Flag that indicates if multi-window is enabled. 3 1492 * 4 1493 * For any particular form of multi-window to be enabled, generic multi-window must be enabled 5 1494 * in {@link com.android.internal.R.bool.config_supportsMultiWindow} config or 6 1495 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set. 7 1496 * At least one of the forms of multi-window must be enabled in order for this flag to be 8 1497 * initialized to 'true'. 9 1498 * 10 1499 * @see #mSupportsSplitScreenMultiWindow 11 1500 * @see #mSupportsFreeformWindowManagement 12 1501 * @see #mSupportsPictureInPicture 13 1502 * @see #mSupportsMultiDisplay 14 1503 */ 15 1504 boolean mSupportsMultiWindow; 16 1505 boolean mSupportsSplitScreenMultiWindow; 17 1506 boolean mSupportsFreeformWindowManagement; 18 1507 boolean mSupportsPictureInPicture; 19 1508 boolean mSupportsMultiDisplay; 20 1509 boolean mSupportsLeanbackOnly;
activity controller
1 1510 IActivityController mController = null;
controller是否是monkey
1 1511 boolean mControllerIsAMonkey = false;
profile,memory watch相关
1 1512 String mProfileApp = null; 2 1513 ProcessRecord mProfileProc = null; 3 1514 String mProfileFile; 4 1515 ParcelFileDescriptor mProfileFd; 5 1516 int mSamplingInterval = 0; 6 1517 boolean mAutoStopProfiler = false; 7 1518 boolean mStreamingOutput = false; 8 1519 int mProfileType = 0; 9 1520 final ProcessMap<Pair<Long, String>> mMemWatchProcesses = new ProcessMap<>(); 10 1521 String mMemWatchDumpProcName; 11 1522 String mMemWatchDumpFile; 12 1523 int mMemWatchDumpPid; 13 1524 int mMemWatchDumpUid; 14 1525 String mTrackAllocationApp = null; 15 1526 String mNativeDebuggingApp = null;
两个临时long
1 1528 final long[] mTmpLong = new long[2];
临时广播队列
1 1530 private final ArraySet<BroadcastQueue> mTmpBroadcastQueue = new ArraySet(); 2 1531
进程状态序号计数器
1 1532 /** 2 1533 * A global counter for generating sequence numbers. 3 1534 * This value will be used when incrementing sequence numbers in individual uidRecords. 4 1535 * 5 1536 * Having a global counter ensures that seq numbers are monotonically increasing for a 6 1537 * particular uid even when the uidRecord is re-created. 7 1538 */ 8 1539 @GuardedBy("this") 9 1540 @VisibleForTesting 10 1541 long mProcStateSeqCounter = 0;
Injector类
1 1543 private final Injector mInjector;
进程改变项内部类
1 1545 static final class ProcessChangeItem { 2 1546 static final int CHANGE_ACTIVITIES = 1<<0; 3 1547 int changes; 4 1548 int uid; 5 1549 int pid; 6 1550 int processState; 7 1551 boolean foregroundActivities; 8 1552 }
uid观察者注册器
1 1554 static final class UidObserverRegistration { 2 1555 final int uid; 3 1556 final String pkg; 4 1557 final int which; 5 1558 final int cutpoint; 6 1559 7 1560 final SparseIntArray lastProcStates; 8 1561 9 1562 UidObserverRegistration(int _uid, String _pkg, int _which, int _cutpoint) { 10 1563 uid = _uid; 11 1564 pkg = _pkg; 12 1565 which = _which; 13 1566 cutpoint = _cutpoint; 14 1567 if (cutpoint >= ActivityManager.MIN_PROCESS_STATE) { 15 1568 lastProcStates = new SparseIntArray(); 16 1569 } else { 17 1570 lastProcStates = null; 18 1571 } 19 1572 } 20 1573 }
进程观察者和进程改变项数组
1 1575 final RemoteCallbackList<IProcessObserver> mProcessObservers = new RemoteCallbackList<>(); 2 1576 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
延迟的和可用的进程变化
1 1578 final ArrayList<ProcessChangeItem> mPendingProcessChanges = new ArrayList<>(); 2 1579 final ArrayList<ProcessChangeItem> mAvailProcessChanges = new ArrayList<>();
uid观察者和uid变化
1 1581 final RemoteCallbackList<IUidObserver> mUidObservers = new RemoteCallbackList<>(); 2 1582 UidRecord.ChangeItem[] mActiveUidChanges = new UidRecord.ChangeItem[5];
延迟的uid change和可用的uid change
1 1584 final ArrayList<UidRecord.ChangeItem> mPendingUidChanges = new ArrayList<>(); 2 1585 final ArrayList<UidRecord.ChangeItem> mAvailUidChanges = new ArrayList<>(); 3 1586
进程cpu所运行的线程
1 1587 /** 2 1588 * Runtime CPU use collection thread. This object's lock is used to 3 1589 * perform synchronization with the thread (notifying it to run). 4 1590 */ 5 1591 final Thread mProcessCpuThread;
进程使用cpu跟踪相关
1 1593 /** 2 1594 * Used to collect per-process CPU use for ANRs, battery stats, etc. 3 1595 * Must acquire this object's lock when accessing it. 4 1596 * NOTE: this lock will be held while doing long operations (trawling 5 1597 * through all processes in /proc), so it should never be acquired by 6 1598 * any critical paths such as when holding the main activity manager lock. 7 1599 */ 8 1600 final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker( 9 1601 MONITOR_THREAD_CPU_USAGE); 10 1602 final AtomicLong mLastCpuTime = new AtomicLong(0); 11 1603 final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true); 12 1604 final CountDownLatch mProcessCpuInitLatch = new CountDownLatch(1);
上一次写入时间
1 1606 long mLastWriteTime = 0;
更新锁
1 1608 /** 2 1609 * Used to retain an update lock when the foreground activity is in 3 1610 * immersive mode. 4 1611 */ 5 1612 final UpdateLock mUpdateLock = new UpdateLock("immersive");
是否完成boot
1 1614 /** 2 1615 * Set to true after the system has finished booting. 3 1616 */ 4 1617 boolean mBooted = false;
Window Manger Service和System Server所在ActivityThread
1 1619 WindowManagerService mWindowManager; 2 1620 final ActivityThread mSystemThread;
app死亡通知
1 1622 private final class AppDeathRecipient implements IBinder.DeathRecipient { 2 1623 final ProcessRecord mApp; 3 1624 final int mPid; 4 1625 final IApplicationThread mAppThread; 5 1626 6 1627 AppDeathRecipient(ProcessRecord app, int pid, 7 1628 IApplicationThread thread) { 8 1629 if (DEBUG_ALL) Slog.v( 9 1630 TAG, "New death recipient " + this 10 1631 + " for thread " + thread.asBinder()); 11 1632 mApp = app; 12 1633 mPid = pid; 13 1634 mAppThread = thread; 14 1635 } 15 1636 16 1637 @Override 17 1638 public void binderDied() { 18 1639 if (DEBUG_ALL) Slog.v( 19 1640 TAG, "Death received in " + this 20 1641 + " for thread " + mAppThread.asBinder()); 21 1642 synchronized(ActivityManagerService.this) { 22 1643 appDiedLocked(mApp, mPid, mAppThread, true); 23 1644 } 24 1645 } 25 1646 }
ui handler消息
1 1648 static final int SHOW_ERROR_UI_MSG = 1; 2 1649 static final int SHOW_NOT_RESPONDING_UI_MSG = 2; 3 1650 static final int SHOW_FACTORY_ERROR_UI_MSG = 3; 4 1651 static final int UPDATE_CONFIGURATION_MSG = 4; 5 1652 static final int GC_BACKGROUND_PROCESSES_MSG = 5; 6 1653 static final int WAIT_FOR_DEBUGGER_UI_MSG = 6; 7 1654 static final int SERVICE_TIMEOUT_MSG = 12; 8 1655 static final int UPDATE_TIME_ZONE = 13; 9 1656 static final int SHOW_UID_ERROR_UI_MSG = 14; 10 1657 static final int SHOW_FINGERPRINT_ERROR_UI_MSG = 15; 11 1658 static final int PROC_START_TIMEOUT_MSG = 20; 12 1659 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21; 13 1660 static final int KILL_APPLICATION_MSG = 22; 14 1661 static final int FINALIZE_PENDING_INTENT_MSG = 23; 15 1662 static final int POST_HEAVY_NOTIFICATION_MSG = 24; 16 1663 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25; 17 1664 static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26; 18 1665 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27; 19 1666 static final int CLEAR_DNS_CACHE_MSG = 28; 20 1667 static final int UPDATE_HTTP_PROXY_MSG = 29; 21 1668 static final int SHOW_COMPAT_MODE_DIALOG_UI_MSG = 30; 22 1669 static final int DISPATCH_PROCESSES_CHANGED_UI_MSG = 31; 23 1670 static final int DISPATCH_PROCESS_DIED_UI_MSG = 32; 24 1671 static final int REPORT_MEM_USAGE_MSG = 33; 25 1672 static final int REPORT_USER_SWITCH_MSG = 34; 26 1673 static final int CONTINUE_USER_SWITCH_MSG = 35; 27 1674 static final int USER_SWITCH_TIMEOUT_MSG = 36; 28 1675 static final int IMMERSIVE_MODE_LOCK_MSG = 37; 29 1676 static final int PERSIST_URI_GRANTS_MSG = 38; 30 1677 static final int REQUEST_ALL_PSS_MSG = 39; 31 1678 static final int START_PROFILES_MSG = 40; 32 1679 static final int UPDATE_TIME_PREFERENCE_MSG = 41; 33 1680 static final int SYSTEM_USER_START_MSG = 42; 34 1681 static final int SYSTEM_USER_CURRENT_MSG = 43; 35 1682 static final int ENTER_ANIMATION_COMPLETE_MSG = 44; 36 1683 static final int FINISH_BOOTING_MSG = 45; 37 1684 static final int START_USER_SWITCH_UI_MSG = 46; 38 1685 static final int SEND_LOCALE_TO_MOUNT_DAEMON_MSG = 47; 39 1686 static final int DISMISS_DIALOG_UI_MSG = 48; 40 1687 static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 49; 41 1688 static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 50; 42 1689 static final int DELETE_DUMPHEAP_MSG = 51; 43 1690 static final int FOREGROUND_PROFILE_CHANGED_MSG = 52; 44 1691 static final int DISPATCH_UIDS_CHANGED_UI_MSG = 53; 45 1692 static final int REPORT_TIME_TRACKER_MSG = 54; 46 1693 static final int REPORT_USER_SWITCH_COMPLETE_MSG = 55; 47 1694 static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 56; 48 1695 static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 57; 49 1696 static final int IDLE_UIDS_MSG = 58; 50 1697 static final int SYSTEM_USER_UNLOCK_MSG = 59; 51 1698 static final int LOG_STACK_STATE = 60; 52 1699 static final int VR_MODE_CHANGE_MSG = 61; 53 1700 static final int SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG = 62; 54 1701 static final int HANDLE_TRUST_STORAGE_UPDATE_MSG = 63; 55 1702 static final int REPORT_LOCKED_BOOT_COMPLETE_MSG = 64; 56 1703 static final int NOTIFY_VR_SLEEPING_MSG = 65; 57 1704 static final int SERVICE_FOREGROUND_TIMEOUT_MSG = 66; 58 1705 static final int DISPATCH_PENDING_INTENT_CANCEL_MSG = 67; 59 1706 static final int PUSH_TEMP_WHITELIST_UI_MSG = 68; 60 1707 static final int SERVICE_FOREGROUND_CRASH_MSG = 69; 61 1708 static final int START_USER_SWITCH_FG_MSG = 712;
第一个activity stack,broadcast queue,compat mode,supervisor stack消息
1 1710 static final int FIRST_ACTIVITY_STACK_MSG = 100; 2 1711 static final int FIRST_BROADCAST_QUEUE_MSG = 200; 3 1712 static final int FIRST_COMPAT_MODE_MSG = 300; 4 1713 static final int FIRST_SUPERVISOR_STACK_MSG = 100;
kill thread和其上的handler
1 1715 static ServiceThread sKillThread = null; 2 1716 static KillHandler sKillHandler = null; 3 1717
兼容模式对话框,不支持的显示size对话框,上一次内存使用报告时间
1 1718 CompatModeDialog mCompatModeDialog; 2 1719 UnsupportedDisplaySizeDialog mUnsupportedDisplaySizeDialog; 3 1720 long mLastMemUsageReportTime = 0;
用户是否是monkey
1 1722 /** 2 1723 * Flag whether the current user is a "monkey", i.e. whether 3 1724 * the UI is driven by a UI automation tool. 4 1725 */ 5 1726 private boolean mUserIsMonkey;
是否有recent UI
1 1728 /** Flag whether the device has a Recents UI */ 2 1729 boolean mHasRecents;
thumb尺寸
1 1731 /** The dimensions of the thumbnails in the Recents UI. */ 2 1732 int mThumbnailWidth; 3 1733 int mThumbnailHeight; 4 1734 float mFullscreenThumbnailScale;
main handler所在线程,main hander,ui handler
1 1736 final ServiceThread mHandlerThread; 2 1737 final MainHandler mHandler; 3 1738 final Handler mUiHandler;
ams常量
1 1740 final ActivityManagerConstants mConstants;
内部包管理器
1 1742 PackageManagerInternal mPackageManagerInt;
voice回话id
1 1744 // VoiceInteraction session ID that changes for each new request except when 2 1745 // being called for multiwindow assist in a single session. 3 1746 private int mViSessionId = 1000;
权限审查是否需要
1 1748 final boolean mPermissionReviewRequired;
获取全局配置
1 1750 /** 2 1751 * Current global configuration information. Contains general settings for the entire system, 3 1752 * also corresponds to the merged configuration of the default display. 4 1753 */ 5 1754 Configuration getGlobalConfiguration() { 6 1755 return mStackSupervisor.getConfiguration(); 7 1756 } 8 1757
获取全局配置
1 1750 /** 2 1751 * Current global configuration information. Contains general settings for the entire system, 3 1752 * also corresponds to the merged configuration of the default display. 4 1753 */ 5 1754 Configuration getGlobalConfiguration() { 6 1755 return mStackSupervisor.getConfiguration(); 7 1756 } 8 1757
杀进程handler
1 1758 final class KillHandler extends Handler { 2 1759 static final int KILL_PROCESS_GROUP_MSG = 4000; 3 1760 4 1761 public KillHandler(Looper looper) { 5 1762 super(looper, null, true); 6 1763 } 7 1764 8 1765 @Override 9 1766 public void handleMessage(Message msg) { 10 1767 switch (msg.what) { 11 1768 case KILL_PROCESS_GROUP_MSG: 12 1769 { 13 1770 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "killProcessGroup"); 14 1771 Process.killProcessGroup(msg.arg1 /* uid */, msg.arg2 /* pid */); 15 1772 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 16 1773 } 17 1774 break; 18 1775 19 1776 default: 20 1777 super.handleMessage(msg); 21 1778 } 22 1779 } 23 1780 } 24 1781
UI handler
1 1782 final class UiHandler extends Handler { 2 1783 public UiHandler() { 3 1784 super(com.android.server.UiThread.get().getLooper(), null, true); 4 1785 } 5 1786 6 1787 @Override 7 1788 public void handleMessage(Message msg) { 8 1789 switch (msg.what) { 9 1790 case SHOW_ERROR_UI_MSG: { 10 1791 mAppErrors.handleShowAppErrorUi(msg); 11 1792 ensureBootCompleted(); 12 1793 } break; 13 1794 case SHOW_NOT_RESPONDING_UI_MSG: { 14 1795 mAppErrors.handleShowAnrUi(msg); 15 1796 ensureBootCompleted(); 16 1797 } break; 17 1798 case SHOW_STRICT_MODE_VIOLATION_UI_MSG: { 18 1799 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 19 1800 synchronized (ActivityManagerService.this) { 20 1801 ProcessRecord proc = (ProcessRecord) data.get("app"); 21 1802 if (proc == null) { 22 1803 Slog.e(TAG, "App not found when showing strict mode dialog."); 23 1804 break; 24 1805 } 25 1806 if (proc.crashDialog != null) { 26 1807 Slog.e(TAG, "App already has strict mode dialog: " + proc); 27 1808 return; 28 1809 } 29 1810 AppErrorResult res = (AppErrorResult) data.get("result"); 30 1811 if (mShowDialogs && !mSleeping && !mShuttingDown) { 31 1812 Dialog d = new StrictModeViolationDialog(mUiContext, 32 1813 ActivityManagerService.this, res, proc); 33 1814 d.show(); 34 1815 proc.crashDialog = d; 35 1816 } else { 36 1817 // The device is asleep, so just pretend that the user 37 1818 // saw a crash dialog and hit "force quit". 38 1819 res.set(0); 39 1820 } 40 1821 } 41 1822 ensureBootCompleted(); 42 1823 } break; 43 1824 case SHOW_FACTORY_ERROR_UI_MSG: { 44 1825 Dialog d = new FactoryErrorDialog( 45 1826 mUiContext, msg.getData().getCharSequence("msg")); 46 1827 d.show(); 47 1828 ensureBootCompleted(); 48 1829 } break; 49 1830 case WAIT_FOR_DEBUGGER_UI_MSG: { 50 1831 synchronized (ActivityManagerService.this) { 51 1832 ProcessRecord app = (ProcessRecord)msg.obj; 52 1833 if (msg.arg1 != 0) { 53 1834 if (!app.waitedForDebugger) { 54 1835 Dialog d = new AppWaitingForDebuggerDialog( 55 1836 ActivityManagerService.this, 56 1837 mUiContext, app); 57 1838 app.waitDialog = d; 58 1839 app.waitedForDebugger = true; 59 1840 d.show(); 60 1841 } 61 1842 } else { 62 1843 if (app.waitDialog != null) { 63 1844 app.waitDialog.dismiss(); 64 1845 app.waitDialog = null; 65 1846 } 66 1847 } 67 1848 } 68 1849 } break; 69 1850 case SHOW_UID_ERROR_UI_MSG: { 70 1851 if (mShowDialogs) { 71 1852 AlertDialog d = new BaseErrorDialog(mUiContext); 72 1853 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR); 73 1854 d.setCancelable(false); 74 1855 d.setTitle(mUiContext.getText(R.string.android_system_label)); 75 1856 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data)); 76 1857 d.setButton(DialogInterface.BUTTON_POSITIVE, mUiContext.getText(R.string.ok), 77 1858 obtainMessage(DISMISS_DIALOG_UI_MSG, d)); 78 1859 d.show(); 79 1860 } 80 1861 } break; 81 1862 case SHOW_FINGERPRINT_ERROR_UI_MSG: { 82 1863 if (mShowDialogs) { 83 1864 AlertDialog d = new BaseErrorDialog(mUiContext); 84 1865 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR); 85 1866 d.setCancelable(false); 86 1867 d.setTitle(mUiContext.getText(R.string.android_system_label)); 87 1868 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer)); 88 1869 d.setButton(DialogInterface.BUTTON_POSITIVE, mUiContext.getText(R.string.ok), 89 1870 obtainMessage(DISMISS_DIALOG_UI_MSG, d)); 90 1871 d.show(); 91 1872 } 92 1873 } break; 93 1874 case SHOW_COMPAT_MODE_DIALOG_UI_MSG: { 94 1875 synchronized (ActivityManagerService.this) { 95 1876 ActivityRecord ar = (ActivityRecord) msg.obj; 96 1877 if (mCompatModeDialog != null) { 97 1878 if (mCompatModeDialog.mAppInfo.packageName.equals( 98 1879 ar.info.applicationInfo.packageName)) { 99 1880 return; 100 1881 } 101 1882 mCompatModeDialog.dismiss(); 102 1883 mCompatModeDialog = null; 103 1884 } 104 1885 if (ar != null && false) { 105 1886 if (mCompatModePackages.getPackageAskCompatModeLocked( 106 1887 ar.packageName)) { 107 1888 int mode = mCompatModePackages.computeCompatModeLocked( 108 1889 ar.info.applicationInfo); 109 1890 if (mode == ActivityManager.COMPAT_MODE_DISABLED 110 1891 || mode == ActivityManager.COMPAT_MODE_ENABLED) { 111 1892 mCompatModeDialog = new CompatModeDialog( 112 1893 ActivityManagerService.this, mUiContext, 113 1894 ar.info.applicationInfo); 114 1895 mCompatModeDialog.show(); 115 1896 } 116 1897 } 117 1898 } 118 1899 } 119 1900 break; 120 1901 } 121 1902 case SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG: { 122 1903 synchronized (ActivityManagerService.this) { 123 1904 final ActivityRecord ar = (ActivityRecord) msg.obj; 124 1905 if (mUnsupportedDisplaySizeDialog != null) { 125 1906 mUnsupportedDisplaySizeDialog.dismiss(); 126 1907 mUnsupportedDisplaySizeDialog = null; 127 1908 } 128 1909 if (ar != null && mCompatModePackages.getPackageNotifyUnsupportedZoomLocked( 129 1910 ar.packageName)) { 130 1911 // TODO(multi-display): Show dialog on appropriate display. 131 1912 mUnsupportedDisplaySizeDialog = new UnsupportedDisplaySizeDialog( 132 1913 ActivityManagerService.this, mUiContext, ar.info.applicationInfo); 133 1914 mUnsupportedDisplaySizeDialog.show(); 134 1915 } 135 1916 } 136 1917 break; 137 1918 } 138 1919 case START_USER_SWITCH_UI_MSG: { 139 1920 mUserController.showUserSwitchDialog((Pair<UserInfo, UserInfo>) msg.obj); 140 1921 break; 141 1922 } 142 1923 case DISMISS_DIALOG_UI_MSG: { 143 1924 final Dialog d = (Dialog) msg.obj; 144 1925 d.dismiss(); 145 1926 break; 146 1927 } 147 1928 case DISPATCH_PROCESSES_CHANGED_UI_MSG: { 148 1929 dispatchProcessesChanged(); 149 1930 break; 150 1931 } 151 1932 case DISPATCH_PROCESS_DIED_UI_MSG: { 152 1933 final int pid = msg.arg1; 153 1934 final int uid = msg.arg2; 154 1935 dispatchProcessDied(pid, uid); 155 1936 break; 156 1937 } 157 1938 case DISPATCH_UIDS_CHANGED_UI_MSG: { 158 1939 dispatchUidsChanged(); 159 1940 } break; 160 1941 case PUSH_TEMP_WHITELIST_UI_MSG: { 161 1942 pushTempWhitelist(); 162 1943 } break; 163 1944 } 164 1945 } 165 1946 }
主handler
1 1948 final class MainHandler extends Handler { 2 1949 public MainHandler(Looper looper) { 3 1950 super(looper, null, true); 4 1951 } 5 1952 6 1953 @Override 7 1954 public void handleMessage(Message msg) { 8 1955 switch (msg.what) { 9 1956 case UPDATE_CONFIGURATION_MSG: { 10 1957 final ContentResolver resolver = mContext.getContentResolver(); 11 1958 Settings.System.putConfigurationForUser(resolver, (Configuration) msg.obj, 12 1959 msg.arg1); 13 1960 } break; 14 1961 case GC_BACKGROUND_PROCESSES_MSG: { 15 1962 synchronized (ActivityManagerService.this) { 16 1963 performAppGcsIfAppropriateLocked(); 17 1964 } 18 1965 } break; 19 1966 case SERVICE_TIMEOUT_MSG: { 20 1967 if (mDidDexOpt) { 21 1968 mDidDexOpt = false; 22 1969 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG); 23 1970 nmsg.obj = msg.obj; 24 1971 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT); 25 1972 return; 26 1973 } 27 1974 mServices.serviceTimeout((ProcessRecord)msg.obj); 28 1975 } break; 29 1976 case SERVICE_FOREGROUND_TIMEOUT_MSG: { 30 1977 mServices.serviceForegroundTimeout((ServiceRecord)msg.obj); 31 1978 } break; 32 1979 case SERVICE_FOREGROUND_CRASH_MSG: { 33 1980 mServices.serviceForegroundCrash((ProcessRecord)msg.obj); 34 1981 } break; 35 1982 case DISPATCH_PENDING_INTENT_CANCEL_MSG: { 36 1983 RemoteCallbackList<IResultReceiver> callbacks 37 1984 = (RemoteCallbackList<IResultReceiver>)msg.obj; 38 1985 int N = callbacks.beginBroadcast(); 39 1986 for (int i = 0; i < N; i++) { 40 1987 try { 41 1988 callbacks.getBroadcastItem(i).send(Activity.RESULT_CANCELED, null); 42 1989 } catch (RemoteException e) { 43 1990 } 44 1991 } 45 1992 callbacks.finishBroadcast(); 46 1993 } break; 47 1994 case UPDATE_TIME_ZONE: { 48 1995 synchronized (ActivityManagerService.this) { 49 1996 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 50 1997 ProcessRecord r = mLruProcesses.get(i); 51 1998 if (r.thread != null) { 52 1999 try { 53 2000 r.thread.updateTimeZone(); 54 2001 } catch (RemoteException ex) { 55 2002 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName); 56 2003 } 57 2004 } 58 2005 } 59 2006 } 60 2007 } break; 61 2008 case CLEAR_DNS_CACHE_MSG: { 62 2009 synchronized (ActivityManagerService.this) { 63 2010 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 64 2011 ProcessRecord r = mLruProcesses.get(i); 65 2012 if (r.thread != null) { 66 2013 try { 67 2014 r.thread.clearDnsCache(); 68 2015 } catch (RemoteException ex) { 69 2016 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName); 70 2017 } 71 2018 } 72 2019 } 73 2020 } 74 2021 } break; 75 2022 case UPDATE_HTTP_PROXY_MSG: { 76 2023 ProxyInfo proxy = (ProxyInfo)msg.obj; 77 2024 String host = ""; 78 2025 String port = ""; 79 2026 String exclList = ""; 80 2027 Uri pacFileUrl = Uri.EMPTY; 81 2028 if (proxy != null) { 82 2029 host = proxy.getHost(); 83 2030 port = Integer.toString(proxy.getPort()); 84 2031 exclList = proxy.getExclusionListAsString(); 85 2032 pacFileUrl = proxy.getPacFileUrl(); 86 2033 } 87 2034 synchronized (ActivityManagerService.this) { 88 2035 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 89 2036 ProcessRecord r = mLruProcesses.get(i); 90 2037 if (r.thread != null) { 91 2038 try { 92 2039 r.thread.setHttpProxy(host, port, exclList, pacFileUrl); 93 2040 } catch (RemoteException ex) { 94 2041 Slog.w(TAG, "Failed to update http proxy for: " + 95 2042 r.info.processName); 96 2043 } 97 2044 } 98 2045 } 99 2046 } 100 2047 } break; 101 2048 case PROC_START_TIMEOUT_MSG: { 102 2049 if (mDidDexOpt) { 103 2050 mDidDexOpt = false; 104 2051 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 105 2052 nmsg.obj = msg.obj; 106 2053 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT); 107 2054 return; 108 2055 } 109 2056 ProcessRecord app = (ProcessRecord)msg.obj; 110 2057 synchronized (ActivityManagerService.this) { 111 2058 processStartTimedOutLocked(app); 112 2059 } 113 2060 } break; 114 2061 case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: { 115 2062 ProcessRecord app = (ProcessRecord)msg.obj; 116 2063 synchronized (ActivityManagerService.this) { 117 2064 processContentProviderPublishTimedOutLocked(app); 118 2065 } 119 2066 } break; 120 2067 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: { 121 2068 synchronized (ActivityManagerService.this) { 122 2069 mActivityStarter.doPendingActivityLaunchesLocked(true); 123 2070 } 124 2071 } break; 125 2072 case KILL_APPLICATION_MSG: { 126 2073 synchronized (ActivityManagerService.this) { 127 2074 final int appId = msg.arg1; 128 2075 final int userId = msg.arg2; 129 2076 Bundle bundle = (Bundle)msg.obj; 130 2077 String pkg = bundle.getString("pkg"); 131 2078 String reason = bundle.getString("reason"); 132 2079 forceStopPackageLocked(pkg, appId, false, false, true, false, 133 2080 false, userId, reason); 134 2081 } 135 2082 } break; 136 2083 case FINALIZE_PENDING_INTENT_MSG: { 137 2084 ((PendingIntentRecord)msg.obj).completeFinalize(); 138 2085 } break; 139 2086 case POST_HEAVY_NOTIFICATION_MSG: { 140 2087 INotificationManager inm = NotificationManager.getService(); 141 2088 if (inm == null) { 142 2089 return; 143 2090 } 144 2091 145 2092 ActivityRecord root = (ActivityRecord)msg.obj; 146 2093 ProcessRecord process = root.app; 147 2094 if (process == null) { 148 2095 return; 149 2096 } 150 2097 151 2098 try { 152 2099 Context context = mContext.createPackageContext(process.info.packageName, 0); 153 2100 String text = mContext.getString(R.string.heavy_weight_notification, 154 2101 context.getApplicationInfo().loadLabel(context.getPackageManager())); 155 2102 Notification notification = 156 2103 new Notification.Builder(context, SystemNotificationChannels.DEVELOPER) 157 2104 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb) 158 2105 .setWhen(0) 159 2106 .setOngoing(true) 160 2107 .setTicker(text) 161 2108 .setColor(mContext.getColor( 162 2109 com.android.internal.R.color.system_notification_accent_color)) 163 2110 .setContentTitle(text) 164 2111 .setContentText( 165 2112 mContext.getText(R.string.heavy_weight_notification_detail)) 166 2113 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, 167 2114 root.intent, PendingIntent.FLAG_CANCEL_CURRENT, null, 168 2115 new UserHandle(root.userId))) 169 2116 .build(); 170 2117 try { 171 2118 inm.enqueueNotificationWithTag("android", "android", null, 172 2119 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, 173 2120 notification, root.userId); 174 2121 } catch (RuntimeException e) { 175 2122 Slog.w(ActivityManagerService.TAG, 176 2123 "Error showing notification for heavy-weight app", e); 177 2124 } catch (RemoteException e) { 178 2125 } 179 2126 } catch (NameNotFoundException e) { 180 2127 Slog.w(TAG, "Unable to create context for heavy notification", e); 181 2128 } 182 2129 } break; 183 2130 case CANCEL_HEAVY_NOTIFICATION_MSG: { 184 2131 INotificationManager inm = NotificationManager.getService(); 185 2132 if (inm == null) { 186 2133 return; 187 2134 } 188 2135 try { 189 2136 inm.cancelNotificationWithTag("android", null, 190 2137 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, msg.arg1); 191 2138 } catch (RuntimeException e) { 192 2139 Slog.w(ActivityManagerService.TAG, 193 2140 "Error canceling notification for service", e); 194 2141 } catch (RemoteException e) { 195 2142 } 196 2143 } break; 197 2144 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: { 198 2145 synchronized (ActivityManagerService.this) { 199 2146 checkExcessivePowerUsageLocked(true); 200 2147 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 201 2148 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 202 2149 sendMessageDelayed(nmsg, mConstants.POWER_CHECK_DELAY); 203 2150 } 204 2151 } break; 205 2152 case REPORT_MEM_USAGE_MSG: { 206 2153 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj; 207 2154 Thread thread = new Thread() { 208 2155 @Override public void run() { 209 2156 reportMemUsage(memInfos); 210 2157 } 211 2158 }; 212 2159 thread.start(); 213 2160 break; 214 2161 } 215 2162 case START_USER_SWITCH_FG_MSG: { 216 2163 mUserController.startUserInForeground(msg.arg1); 217 2164 break; 218 2165 } 219 2166 case REPORT_USER_SWITCH_MSG: { 220 2167 mUserController.dispatchUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2); 221 2168 break; 222 2169 } 223 2170 case CONTINUE_USER_SWITCH_MSG: { 224 2171 mUserController.continueUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2); 225 2172 break; 226 2173 } 227 2174 case USER_SWITCH_TIMEOUT_MSG: { 228 2175 mUserController.timeoutUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2); 229 2176 break; 230 2177 } 231 2178 case IMMERSIVE_MODE_LOCK_MSG: { 232 2179 final boolean nextState = (msg.arg1 != 0); 233 2180 if (mUpdateLock.isHeld() != nextState) { 234 2181 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, 235 2182 "Applying new update lock state '" + nextState 236 2183 + "' for " + (ActivityRecord)msg.obj); 237 2184 if (nextState) { 238 2185 mUpdateLock.acquire(); 239 2186 } else { 240 2187 mUpdateLock.release(); 241 2188 } 242 2189 } 243 2190 break; 244 2191 } 245 2192 case PERSIST_URI_GRANTS_MSG: { 246 2193 writeGrantedUriPermissions(); 247 2194 break; 248 2195 } 249 2196 case REQUEST_ALL_PSS_MSG: { 250 2197 synchronized (ActivityManagerService.this) { 251 2198 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false); 252 2199 } 253 2200 break; 254 2201 } 255 2202 case START_PROFILES_MSG: { 256 2203 synchronized (ActivityManagerService.this) { 257 2204 mUserController.startProfilesLocked(); 258 2205 } 259 2206 break; 260 2207 } 261 2208 case UPDATE_TIME_PREFERENCE_MSG: { 262 2209 // The user's time format preference might have changed. 263 2210 // For convenience we re-use the Intent extra values. 264 2211 synchronized (ActivityManagerService.this) { 265 2212 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 266 2213 ProcessRecord r = mLruProcesses.get(i); 267 2214 if (r.thread != null) { 268 2215 try { 269 2216 r.thread.updateTimePrefs(msg.arg1); 270 2217 } catch (RemoteException ex) { 271 2218 Slog.w(TAG, "Failed to update preferences for: " 272 2219 + r.info.processName); 273 2220 } 274 2221 } 275 2222 } 276 2223 } 277 2224 break; 278 2225 } 279 2226 case SYSTEM_USER_START_MSG: { 280 2227 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, 281 2228 Integer.toString(msg.arg1), msg.arg1); 282 2229 mSystemServiceManager.startUser(msg.arg1); 283 2230 break; 284 2231 } 285 2232 case SYSTEM_USER_UNLOCK_MSG: { 286 2233 final int userId = msg.arg1; 287 2234 mSystemServiceManager.unlockUser(userId); 288 2235 synchronized (ActivityManagerService.this) { 289 2236 mRecentTasks.loadUserRecentsLocked(userId); 290 2237 } 291 2238 if (userId == UserHandle.USER_SYSTEM) { 292 2239 startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_UNAWARE); 293 2240 } 294 2241 installEncryptionUnawareProviders(userId); 295 2242 mUserController.finishUserUnlocked((UserState) msg.obj); 296 2243 break; 297 2244 } 298 2245 case SYSTEM_USER_CURRENT_MSG: { 299 2246 mBatteryStatsService.noteEvent( 300 2247 BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_FINISH, 301 2248 Integer.toString(msg.arg2), msg.arg2); 302 2249 mBatteryStatsService.noteEvent( 303 2250 BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, 304 2251 Integer.toString(msg.arg1), msg.arg1); 305 2252 mSystemServiceManager.switchUser(msg.arg1); 306 2253 break; 307 2254 } 308 2255 case ENTER_ANIMATION_COMPLETE_MSG: { 309 2256 synchronized (ActivityManagerService.this) { 310 2257 ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj); 311 2258 if (r != null && r.app != null && r.app.thread != null) { 312 2259 try { 313 2260 r.app.thread.scheduleEnterAnimationComplete(r.appToken); 314 2261 } catch (RemoteException e) { 315 2262 } 316 2263 } 317 2264 } 318 2265 break; 319 2266 } 320 2267 case FINISH_BOOTING_MSG: { 321 2268 if (msg.arg1 != 0) { 322 2269 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "FinishBooting"); 323 2270 finishBooting(); 324 2271 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 325 2272 } 326 2273 if (msg.arg2 != 0) { 327 2274 enableScreenAfterBoot(); 328 2275 } 329 2276 break; 330 2277 } 331 2278 case SEND_LOCALE_TO_MOUNT_DAEMON_MSG: { 332 2279 try { 333 2280 Locale l = (Locale) msg.obj; 334 2281 IBinder service = ServiceManager.getService("mount"); 335 2282 IStorageManager storageManager = IStorageManager.Stub.asInterface(service); 336 2283 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI"); 337 2284 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag()); 338 2285 } catch (RemoteException e) { 339 2286 Log.e(TAG, "Error storing locale for decryption UI", e); 340 2287 } 341 2288 break; 342 2289 } 343 2290 case NOTIFY_CLEARTEXT_NETWORK_MSG: { 344 2291 final int uid = msg.arg1; 345 2292 final byte[] firstPacket = (byte[]) msg.obj; 346 2293 347 2294 synchronized (mPidsSelfLocked) { 348 2295 for (int i = 0; i < mPidsSelfLocked.size(); i++) { 349 2296 final ProcessRecord p = mPidsSelfLocked.valueAt(i); 350 2297 if (p.uid == uid) { 351 2298 try { 352 2299 p.thread.notifyCleartextNetwork(firstPacket); 353 2300 } catch (RemoteException ignored) { 354 2301 } 355 2302 } 356 2303 } 357 2304 } 358 2305 break; 359 2306 } 360 2307 case POST_DUMP_HEAP_NOTIFICATION_MSG: { 361 2308 final String procName; 362 2309 final int uid; 363 2310 final long memLimit; 364 2311 final String reportPackage; 365 2312 synchronized (ActivityManagerService.this) { 366 2313 procName = mMemWatchDumpProcName; 367 2314 uid = mMemWatchDumpUid; 368 2315 Pair<Long, String> val = mMemWatchProcesses.get(procName, uid); 369 2316 if (val == null) { 370 2317 val = mMemWatchProcesses.get(procName, 0); 371 2318 } 372 2319 if (val != null) { 373 2320 memLimit = val.first; 374 2321 reportPackage = val.second; 375 2322 } else { 376 2323 memLimit = 0; 377 2324 reportPackage = null; 378 2325 } 379 2326 } 380 2327 if (procName == null) { 381 2328 return; 382 2329 } 383 2330 384 2331 if (DEBUG_PSS) Slog.d(TAG_PSS, 385 2332 "Showing dump heap notification from " + procName + "/" + uid); 386 2333 387 2334 INotificationManager inm = NotificationManager.getService(); 388 2335 if (inm == null) { 389 2336 return; 390 2337 } 391 2338 392 2339 String text = mContext.getString(R.string.dump_heap_notification, procName); 393 2340 394 2341 395 2342 Intent deleteIntent = new Intent(); 396 2343 deleteIntent.setAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP); 397 2344 Intent intent = new Intent(); 398 2345 intent.setClassName("android", DumpHeapActivity.class.getName()); 399 2346 intent.putExtra(DumpHeapActivity.KEY_PROCESS, procName); 400 2347 intent.putExtra(DumpHeapActivity.KEY_SIZE, memLimit); 401 2348 if (reportPackage != null) { 402 2349 intent.putExtra(DumpHeapActivity.KEY_DIRECT_LAUNCH, reportPackage); 403 2350 } 404 2351 int userId = UserHandle.getUserId(uid); 405 2352 Notification notification = 406 2353 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER) 407 2354 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb) 408 2355 .setWhen(0) 409 2356 .setOngoing(true) 410 2357 .setAutoCancel(true) 411 2358 .setTicker(text) 412 2359 .setColor(mContext.getColor( 413 2360 com.android.internal.R.color.system_notification_accent_color)) 414 2361 .setContentTitle(text) 415 2362 .setContentText( 416 2363 mContext.getText(R.string.dump_heap_notification_detail)) 417 2364 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, 418 2365 intent, PendingIntent.FLAG_CANCEL_CURRENT, null, 419 2366 new UserHandle(userId))) 420 2367 .setDeleteIntent(PendingIntent.getBroadcastAsUser(mContext, 0, 421 2368 deleteIntent, 0, UserHandle.SYSTEM)) 422 2369 .build(); 423 2370 424 2371 try { 425 2372 inm.enqueueNotificationWithTag("android", "android", null, 426 2373 SystemMessage.NOTE_DUMP_HEAP_NOTIFICATION, 427 2374 notification, userId); 428 2375 } catch (RuntimeException e) { 429 2376 Slog.w(ActivityManagerService.TAG, 430 2377 "Error showing notification for dump heap", e); 431 2378 } catch (RemoteException e) { 432 2379 } 433 2380 } break; 434 2381 case DELETE_DUMPHEAP_MSG: { 435 2382 revokeUriPermission(ActivityThread.currentActivityThread().getApplicationThread(), 436 2383 null, DumpHeapActivity.JAVA_URI, 437 2384 Intent.FLAG_GRANT_READ_URI_PERMISSION 438 2385 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION, 439 2386 UserHandle.myUserId()); 440 2387 synchronized (ActivityManagerService.this) { 441 2388 mMemWatchDumpFile = null; 442 2389 mMemWatchDumpProcName = null; 443 2390 mMemWatchDumpPid = -1; 444 2391 mMemWatchDumpUid = -1; 445 2392 } 446 2393 } break; 447 2394 case FOREGROUND_PROFILE_CHANGED_MSG: { 448 2395 mUserController.dispatchForegroundProfileChanged(msg.arg1); 449 2396 } break; 450 2397 case REPORT_TIME_TRACKER_MSG: { 451 2398 AppTimeTracker tracker = (AppTimeTracker)msg.obj; 452 2399 tracker.deliverResult(mContext); 453 2400 } break; 454 2401 case REPORT_USER_SWITCH_COMPLETE_MSG: { 455 2402 mUserController.dispatchUserSwitchComplete(msg.arg1); 456 2403 } break; 457 2404 case REPORT_LOCKED_BOOT_COMPLETE_MSG: { 458 2405 mUserController.dispatchLockedBootComplete(msg.arg1); 459 2406 } break; 460 2407 case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: { 461 2408 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj; 462 2409 try { 463 2410 connection.shutdown(); 464 2411 } catch (RemoteException e) { 465 2412 Slog.w(TAG, "Error shutting down UiAutomationConnection"); 466 2413 } 467 2414 // Only a UiAutomation can set this flag and now that 468 2415 // it is finished we make sure it is reset to its default. 469 2416 mUserIsMonkey = false; 470 2417 } break; 471 2418 case IDLE_UIDS_MSG: { 472 2419 idleUids(); 473 2420 } break; 474 2421 case VR_MODE_CHANGE_MSG: { 475 2422 if (!mVrController.onVrModeChanged((ActivityRecord) msg.obj)) { 476 2423 return; 477 2424 } 478 2425 synchronized (ActivityManagerService.this) { 479 2426 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked(); 480 2427 mWindowManager.disableNonVrUi(disableNonVrUi); 481 2428 if (disableNonVrUi) { 482 2429 // If we are in a VR mode where Picture-in-Picture mode is unsupported, 483 2430 // then remove the pinned stack. 484 2431 final PinnedActivityStack pinnedStack = mStackSupervisor.getStack( 485 2432 PINNED_STACK_ID); 486 2433 if (pinnedStack != null) { 487 2434 mStackSupervisor.removeStackLocked(PINNED_STACK_ID); 488 2435 } 489 2436 } 490 2437 } 491 2438 } break; 492 2439 case NOTIFY_VR_SLEEPING_MSG: { 493 2440 notifyVrManagerOfSleepState(msg.arg1 != 0); 494 2441 } break; 495 2442 case HANDLE_TRUST_STORAGE_UPDATE_MSG: { 496 2443 synchronized (ActivityManagerService.this) { 497 2444 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 498 2445 ProcessRecord r = mLruProcesses.get(i); 499 2446 if (r.thread != null) { 500 2447 try { 501 2448 r.thread.handleTrustStorageUpdate(); 502 2449 } catch (RemoteException ex) { 503 2450 Slog.w(TAG, "Failed to handle trust storage update for: " + 504 2451 r.info.processName); 505 2452 } 506 2453 } 507 2454 } 508 2455 } 509 2456 } break; 510 2457 } 511 2458 } 512 2459 };
后台收集pss消息
1 2461 static final int COLLECT_PSS_BG_MSG = 1;
bg handler
1 2463 final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) { 2 2464 @Override 3 2465 public void handleMessage(Message msg) { 4 2466 switch (msg.what) { 5 2467 case COLLECT_PSS_BG_MSG: { 6 2468 long start = SystemClock.uptimeMillis(); 7 2469 MemInfoReader memInfo = null; 8 2470 synchronized (ActivityManagerService.this) { 9 2471 if (mFullPssPending) { 10 2472 mFullPssPending = false; 11 2473 memInfo = new MemInfoReader(); 12 2474 } 13 2475 } 14 2476 if (memInfo != null) { 15 2477 updateCpuStatsNow(); 16 2478 long nativeTotalPss = 0; 17 2479 final List<ProcessCpuTracker.Stats> stats; 18 2480 synchronized (mProcessCpuTracker) { 19 2481 stats = mProcessCpuTracker.getStats( (st)-> { 20 2482 return st.vsize > 0 && st.uid < FIRST_APPLICATION_UID; 21 2483 }); 22 2484 } 23 2485 final int N = stats.size(); 24 2486 for (int j = 0; j < N; j++) { 25 2487 synchronized (mPidsSelfLocked) { 26 2488 if (mPidsSelfLocked.indexOfKey(stats.get(j).pid) >= 0) { 27 2489 // This is one of our own processes; skip it. 28 2490 continue; 29 2491 } 30 2492 } 31 2493 nativeTotalPss += Debug.getPss(stats.get(j).pid, null, null); 32 2494 } 33 2495 memInfo.readMemInfo(); 34 2496 synchronized (ActivityManagerService.this) { 35 2497 if (DEBUG_PSS) Slog.d(TAG_PSS, "Collected native and kernel memory in " 36 2498 + (SystemClock.uptimeMillis()-start) + "ms"); 37 2499 final long cachedKb = memInfo.getCachedSizeKb(); 38 2500 final long freeKb = memInfo.getFreeSizeKb(); 39 2501 final long zramKb = memInfo.getZramTotalSizeKb(); 40 2502 final long kernelKb = memInfo.getKernelUsedSizeKb(); 41 2503 EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024, 42 2504 kernelKb*1024, nativeTotalPss*1024); 43 2505 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, 44 2506 nativeTotalPss); 45 2507 } 46 2508 } 47 2509 48 2510 int num = 0; 49 2511 long[] tmp = new long[2]; 50 2512 do { 51 2513 ProcessRecord proc; 52 2514 int procState; 53 2515 int pid; 54 2516 long lastPssTime; 55 2517 synchronized (ActivityManagerService.this) { 56 2518 if (mPendingPssProcesses.size() <= 0) { 57 2519 if (mTestPssMode || DEBUG_PSS) Slog.d(TAG_PSS, 58 2520 "Collected PSS of " + num + " processes in " 59 2521 + (SystemClock.uptimeMillis() - start) + "ms"); 60 2522 mPendingPssProcesses.clear(); 61 2523 return; 62 2524 } 63 2525 proc = mPendingPssProcesses.remove(0); 64 2526 procState = proc.pssProcState; 65 2527 lastPssTime = proc.lastPssTime; 66 2528 if (proc.thread != null && procState == proc.setProcState 67 2529 && (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE) 68 2530 < SystemClock.uptimeMillis()) { 69 2531 pid = proc.pid; 70 2532 } else { 71 2533 proc = null; 72 2534 pid = 0; 73 2535 } 74 2536 } 75 2537 if (proc != null) { 76 2538 long pss = Debug.getPss(pid, tmp, null); 77 2539 synchronized (ActivityManagerService.this) { 78 2540 if (pss != 0 && proc.thread != null && proc.setProcState == procState 79 2541 && proc.pid == pid && proc.lastPssTime == lastPssTime) { 80 2542 num++; 81 2543 recordPssSampleLocked(proc, procState, pss, tmp[0], tmp[1], 82 2544 SystemClock.uptimeMillis()); 83 2545 } 84 2546 } 85 2547 } 86 2548 } while (true); 87 2549 } 88 2550 } 89 2551 } 90 2552 };
设置为系统进程
1 2554 public void setSystemProcess() { 2 2555 try { 3 2556 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true); 4 2557 ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats); 5 2558 ServiceManager.addService("meminfo", new MemBinder(this)); 6 2559 ServiceManager.addService("gfxinfo", new GraphicsBinder(this)); 7 2560 ServiceManager.addService("dbinfo", new DbBinder(this)); 8 2561 if (MONITOR_CPU_USAGE) { 9 2562 ServiceManager.addService("cpuinfo", new CpuBinder(this)); 10 2563 } 11 2564 ServiceManager.addService("permission", new PermissionController(this)); 12 2565 ServiceManager.addService("processinfo", new ProcessInfoService(this)); 13 2566 14 2567 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 15 2568 "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY); 16 2569 mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader()); 17 2570 18 2571 synchronized (this) { 19 2572 ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0); 20 2573 app.persistent = true; 21 2574 app.pid = MY_PID; 22 2575 app.maxAdj = ProcessList.SYSTEM_ADJ; 23 2576 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats); 24 2577 synchronized (mPidsSelfLocked) { 25 2578 mPidsSelfLocked.put(app.pid, app); 26 2579 } 27 2580 updateLruProcessLocked(app, false, null); 28 2581 updateOomAdjLocked(); 29 2582 } 30 2583 } catch (PackageManager.NameNotFoundException e) { 31 2584 throw new RuntimeException( 32 2585 "Unable to find android system package", e); 33 2586 } 34 2587 }
设置window manager
1 2589 public void setWindowManager(WindowManagerService wm) { 2 2590 mWindowManager = wm; 3 2591 mStackSupervisor.setWindowManager(wm); 4 2592 mActivityStarter.setWindowManager(wm); 5 2593 }
设置usage stats manager
1 2595 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) { 2 2596 mUsageStatsService = usageStatsManager; 3 2597 }
开始观察本地crash;获取app ops service
1 2599 public void startObservingNativeCrashes() { 2 2600 final NativeCrashListener ncl = new NativeCrashListener(this); 3 2601 ncl.start(); 4 2602 } 5 2603 6 2604 public IAppOpsService getAppOpsService() { 7 2605 return mAppOpsService; 8 2606 }
mem binder
1 2608 static class MemBinder extends Binder { 2 2609 ActivityManagerService mActivityManagerService; 3 2610 MemBinder(ActivityManagerService activityManagerService) { 4 2611 mActivityManagerService = activityManagerService; 5 2612 } 6 2613 7 2614 @Override 8 2615 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 9 2616 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 10 2617 "meminfo", pw)) return; 11 2618 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args, false, null); 12 2619 } 13 2620 }
graphics binder
1 2622 static class GraphicsBinder extends Binder { 2 2623 ActivityManagerService mActivityManagerService; 3 2624 GraphicsBinder(ActivityManagerService activityManagerService) { 4 2625 mActivityManagerService = activityManagerService; 5 2626 } 6 2627 7 2628 @Override 8 2629 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 9 2630 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 10 2631 "gfxinfo", pw)) return; 11 2632 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args); 12 2633 } 13 2634 }
db binder
1 2636 static class DbBinder extends Binder { 2 2637 ActivityManagerService mActivityManagerService; 3 2638 DbBinder(ActivityManagerService activityManagerService) { 4 2639 mActivityManagerService = activityManagerService; 5 2640 } 6 2641 7 2642 @Override 8 2643 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 9 2644 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 10 2645 "dbinfo", pw)) return; 11 2646 mActivityManagerService.dumpDbInfo(fd, pw, args); 12 2647 } 13 2648 }
cpu binder
1 2650 static class CpuBinder extends Binder { 2 2651 ActivityManagerService mActivityManagerService; 3 2652 CpuBinder(ActivityManagerService activityManagerService) { 4 2653 mActivityManagerService = activityManagerService; 5 2654 } 6 2655 7 2656 @Override 8 2657 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 9 2658 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext, 10 2659 "cpuinfo", pw)) return; 11 2660 synchronized (mActivityManagerService.mProcessCpuTracker) { 12 2661 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad()); 13 2662 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState( 14 2663 SystemClock.uptimeMillis())); 15 2664 } 16 2665 } 17 2666 }
lifecycle
1 2668 public static final class Lifecycle extends SystemService { 2 2669 private final ActivityManagerService mService; 3 2670 4 2671 public Lifecycle(Context context) { 5 2672 super(context); 6 2673 mService = new ActivityManagerService(context); 7 2674 } 8 2675 9 2676 @Override 10 2677 public void onStart() { 11 2678 mService.start(); 12 2679 } 13 2680 14 2681 public ActivityManagerService getService() { 15 2682 return mService; 16 2683 } 17 2684 }
构造方法
1 2686 @VisibleForTesting 2 2687 public ActivityManagerService(Injector injector) { 3 2688 mInjector = injector; 4 2689 mContext = mInjector.getContext(); 5 2690 mUiContext = null; 6 2691 GL_ES_VERSION = 0; 7 2692 mActivityStarter = null; 8 2693 mAppErrors = null; 9 2694 mAppOpsService = mInjector.getAppOpsService(null, null); 10 2695 mBatteryStatsService = null; 11 2696 mCompatModePackages = null; 12 2697 mConstants = null; 13 2698 mGrantFile = null; 14 2699 mHandler = null; 15 2700 mHandlerThread = null; 16 2701 mIntentFirewall = null; 17 2702 mKeyguardController = null; 18 2703 mPermissionReviewRequired = false; 19 2704 mProcessCpuThread = null; 20 2705 mProcessStats = null; 21 2706 mProviderMap = null; 22 2707 mRecentTasks = null; 23 2708 mServices = null; 24 2709 mStackSupervisor = null; 25 2710 mSystemThread = null; 26 2711 mTaskChangeNotificationController = null; 27 2712 mUiHandler = injector.getUiHandler(null); 28 2713 mUserController = null; 29 2714 mVrController = null; 30 2715 } 31 2716 32 2717 // Note: This method is invoked on the main thread but may need to attach various 33 2718 // handlers to other threads. So take care to be explicit about the looper. 34 2719 public ActivityManagerService(Context systemContext) { 35 2720 LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY); 36 2721 mInjector = new Injector(); 37 2722 mContext = systemContext; 38 2723 39 2724 mFactoryTest = FactoryTest.getMode(); 40 2725 mSystemThread = ActivityThread.currentActivityThread(); 41 2726 mUiContext = mSystemThread.getSystemUiContext(); 42 2727 43 2728 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass()); 44 2729 45 2730 mPermissionReviewRequired = mContext.getResources().getBoolean( 46 2731 com.android.internal.R.bool.config_permissionReviewRequired); 47 2732 48 2733 mHandlerThread = new ServiceThread(TAG, 49 2734 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); 50 2735 mHandlerThread.start(); 51 2736 mHandler = new MainHandler(mHandlerThread.getLooper()); 52 2737 mUiHandler = mInjector.getUiHandler(this); 53 2738 54 2739 mConstants = new ActivityManagerConstants(this, mHandler); 55 2740 56 2741 /* static; one-time init here */ 57 2742 if (sKillHandler == null) { 58 2743 sKillThread = new ServiceThread(TAG + ":kill", 59 2744 THREAD_PRIORITY_BACKGROUND, true /* allowIo */); 60 2745 sKillThread.start(); 61 2746 sKillHandler = new KillHandler(sKillThread.getLooper()); 62 2747 } 63 2748 64 2749 mFgBroadcastQueue = new BroadcastQueue(this, mHandler, 65 2750 "foreground", BROADCAST_FG_TIMEOUT, false); 66 2751 mBgBroadcastQueue = new BroadcastQueue(this, mHandler, 67 2752 "background", BROADCAST_BG_TIMEOUT, true); 68 2753 mBroadcastQueues[0] = mFgBroadcastQueue; 69 2754 mBroadcastQueues[1] = mBgBroadcastQueue; 70 2755 71 2756 mServices = new ActiveServices(this); 72 2757 mProviderMap = new ProviderMap(this); 73 2758 mAppErrors = new AppErrors(mUiContext, this); 74 2759 75 2760 // TODO: Move creation of battery stats service outside of activity manager service. 76 2761 File dataDir = Environment.getDataDirectory(); 77 2762 File systemDir = new File(dataDir, "system"); 78 2763 systemDir.mkdirs(); 79 2764 mBatteryStatsService = new BatteryStatsService(systemDir, mHandler); 80 2765 mBatteryStatsService.getActiveStatistics().readLocked(); 81 2766 mBatteryStatsService.scheduleWriteToDisk(); 82 2767 mOnBattery = DEBUG_POWER ? true 83 2768 : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); 84 2769 mBatteryStatsService.getActiveStatistics().setCallback(this); 85 2770 86 2771 mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats")); 87 2772 88 2773 mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler); 89 2774 mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null, 90 2775 new IAppOpsCallback.Stub() { 91 2776 @Override public void opChanged(int op, int uid, String packageName) { 92 2777 if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) { 93 2778 if (mAppOpsService.checkOperation(op, uid, packageName) 94 2779 != AppOpsManager.MODE_ALLOWED) { 95 2780 runInBackgroundDisabled(uid); 96 2781 } 97 2782 } 98 2783 } 99 2784 }); 100 2785 101 2786 mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml")); 102 2787 103 2788 mUserController = new UserController(this); 104 2789 105 2790 mVrController = new VrController(this); 106 2791 107 2792 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", 108 2793 ConfigurationInfo.GL_ES_VERSION_UNDEFINED); 109 2794 110 2795 if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) { 111 2796 mUseFifoUiScheduling = true; 112 2797 } 113 2798 114 2799 mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations")); 115 2800 mTempConfig.setToDefaults(); 116 2801 mTempConfig.setLocales(LocaleList.getDefault()); 117 2802 mConfigurationSeq = mTempConfig.seq = 1; 118 2803 mStackSupervisor = createStackSupervisor(); 119 2804 mStackSupervisor.onConfigurationChanged(mTempConfig); 120 2805 mKeyguardController = mStackSupervisor.mKeyguardController; 121 2806 mCompatModePackages = new CompatModePackages(this, systemDir, mHandler); 122 2807 mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler); 123 2808 mTaskChangeNotificationController = 124 2809 new TaskChangeNotificationController(this, mStackSupervisor, mHandler); 125 2810 mActivityStarter = new ActivityStarter(this, mStackSupervisor); 126 2811 mRecentTasks = new RecentTasks(this, mStackSupervisor); 127 2812 128 2813 mProcessCpuThread = new Thread("CpuTracker") { 129 2814 @Override 130 2815 public void run() { 131 2816 synchronized (mProcessCpuTracker) { 132 2817 mProcessCpuInitLatch.countDown(); 133 2818 mProcessCpuTracker.init(); 134 2819 } 135 2820 while (true) { 136 2821 try { 137 2822 try { 138 2823 synchronized(this) { 139 2824 final long now = SystemClock.uptimeMillis(); 140 2825 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now; 141 2826 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now; 142 2827 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay 143 2828 // + ", write delay=" + nextWriteDelay); 144 2829 if (nextWriteDelay < nextCpuDelay) { 145 2830 nextCpuDelay = nextWriteDelay; 146 2831 } 147 2832 if (nextCpuDelay > 0) { 148 2833 mProcessCpuMutexFree.set(true); 149 2834 this.wait(nextCpuDelay); 150 2835 } 151 2836 } 152 2837 } catch (InterruptedException e) { 153 2838 } 154 2839 updateCpuStatsNow(); 155 2840 } catch (Exception e) { 156 2841 Slog.e(TAG, "Unexpected exception collecting process stats", e); 157 2842 } 158 2843 } 159 2844 } 160 2845 }; 161 2846 162 2847 Watchdog.getInstance().addMonitor(this); 163 2848 Watchdog.getInstance().addThread(mHandler); 164 2849 } 165 2850
创建stack supervisior
1 2851 protected ActivityStackSupervisor createStackSupervisor() { 2 2852 return new ActivityStackSupervisor(this, mHandler.getLooper()); 3 2853 }
设置System Service Manager
1 2855 public void setSystemServiceManager(SystemServiceManager mgr) { 2 2856 mSystemServiceManager = mgr; 3 2857 }
设置installer
1 2859 public void setInstaller(Installer installer) { 2 2860 mInstaller = installer; 3 2861 }
start方法
1 2863 private void start() { 2 2864 removeAllProcessGroups(); 3 2865 mProcessCpuThread.start(); 4 2866 5 2867 mBatteryStatsService.publish(mContext); 6 2868 mAppOpsService.publish(mContext); 7 2869 Slog.d("AppOps", "AppOpsService published"); 8 2870 LocalServices.addService(ActivityManagerInternal.class, new LocalService()); 9 2871 // Wait for the synchronized block started in mProcessCpuThread, 10 2872 // so that any other acccess to mProcessCpuTracker from main thread 11 2873 // will be blocked during mProcessCpuTracker initialization. 12 2874 try { 13 2875 mProcessCpuInitLatch.await(); 14 2876 } catch (InterruptedException e) { 15 2877 Slog.wtf(TAG, "Interrupted wait during start", e); 16 2878 Thread.currentThread().interrupt(); 17 2879 throw new IllegalStateException("Interrupted wait during start"); 18 2880 } 19 2881 }
用户stop回调
1 2883 void onUserStoppedLocked(int userId) { 2 2884 mRecentTasks.unloadUserDataFromMemoryLocked(userId); 3 2885 }
初始化power manager
1 2887 public void initPowerManagement() { 2 2888 mStackSupervisor.initPowerManagement(); 3 2889 mBatteryStatsService.initPowerManagement(); 4 2890 mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class); 5 2891 PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE); 6 2892 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*"); 7 2893 mVoiceWakeLock.setReferenceCounted(false); 8 2894 }
获取后台启动广播
1 2896 private ArraySet<String> getBackgroundLaunchBroadcasts() { 2 2897 if (mBackgroundLaunchBroadcasts == null) { 3 2898 mBackgroundLaunchBroadcasts = SystemConfig.getInstance().getAllowImplicitBroadcasts(); 4 2899 } 5 2900 return mBackgroundLaunchBroadcasts; 6 2901 }
onTransact
1 2903 @Override 2 2904 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3 2905 throws RemoteException { 4 2906 if (code == SYSPROPS_TRANSACTION) { 5 2907 // We need to tell all apps about the system property change. 6 2908 ArrayList<IBinder> procs = new ArrayList<IBinder>(); 7 2909 synchronized(this) { 8 2910 final int NP = mProcessNames.getMap().size(); 9 2911 for (int ip=0; ip<NP; ip++) { 10 2912 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 11 2913 final int NA = apps.size(); 12 2914 for (int ia=0; ia<NA; ia++) { 13 2915 ProcessRecord app = apps.valueAt(ia); 14 2916 if (app.thread != null) { 15 2917 procs.add(app.thread.asBinder()); 16 2918 } 17 2919 } 18 2920 } 19 2921 } 20 2922 21 2923 int N = procs.size(); 22 2924 for (int i=0; i<N; i++) { 23 2925 Parcel data2 = Parcel.obtain(); 24 2926 try { 25 2927 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 26 2928 Binder.FLAG_ONEWAY); 27 2929 } catch (RemoteException e) { 28 2930 } 29 2931 data2.recycle(); 30 2932 } 31 2933 } 32 2934 try { 33 2935 return super.onTransact(code, data, reply, flags); 34 2936 } catch (RuntimeException e) { 35 2937 // The activity manager only throws security exceptions, so let's 36 2938 // log all others. 37 2939 if (!(e instanceof SecurityException)) { 38 2940 Slog.wtf(TAG, "Activity Manager Crash." 39 2941 + " UID:" + Binder.getCallingUid() 40 2942 + " PID:" + Binder.getCallingPid() 41 2943 + " TRANS:" + code, e); 42 2944 } 43 2945 throw e; 44 2946 } 45 2947 } 46 2948
更新cpu状态
1 2949 void updateCpuStats() { 2 2950 final long now = SystemClock.uptimeMillis(); 3 2951 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) { 4 2952 return; 5 2953 } 6 2954 if (mProcessCpuMutexFree.compareAndSet(true, false)) { 7 2955 synchronized (mProcessCpuThread) { 8 2956 mProcessCpuThread.notify(); 9 2957 } 10 2958 } 11 2959 } 12 2960 13 2961 void updateCpuStatsNow() { 14 2962 synchronized (mProcessCpuTracker) { 15 2963 mProcessCpuMutexFree.set(false); 16 2964 final long now = SystemClock.uptimeMillis(); 17 2965 boolean haveNewCpuStats = false; 18 2966 19 2967 if (MONITOR_CPU_USAGE && 20 2968 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) { 21 2969 mLastCpuTime.set(now); 22 2970 mProcessCpuTracker.update(); 23 2971 if (mProcessCpuTracker.hasGoodLastStats()) { 24 2972 haveNewCpuStats = true; 25 2973 //Slog.i(TAG, mProcessCpu.printCurrentState()); 26 2974 //Slog.i(TAG, "Total CPU usage: " 27 2975 // + mProcessCpu.getTotalCpuPercent() + "%"); 28 2976 29 2977 // Slog the cpu usage if the property is set. 30 2978 if ("true".equals(SystemProperties.get("events.cpu"))) { 31 2979 int user = mProcessCpuTracker.getLastUserTime(); 32 2980 int system = mProcessCpuTracker.getLastSystemTime(); 33 2981 int iowait = mProcessCpuTracker.getLastIoWaitTime(); 34 2982 int irq = mProcessCpuTracker.getLastIrqTime(); 35 2983 int softIrq = mProcessCpuTracker.getLastSoftIrqTime(); 36 2984 int idle = mProcessCpuTracker.getLastIdleTime(); 37 2985 38 2986 int total = user + system + iowait + irq + softIrq + idle; 39 2987 if (total == 0) total = 1; 40 2988 41 2989 EventLog.writeEvent(EventLogTags.CPU, 42 2990 ((user+system+iowait+irq+softIrq) * 100) / total, 43 2991 (user * 100) / total, 44 2992 (system * 100) / total, 45 2993 (iowait * 100) / total, 46 2994 (irq * 100) / total, 47 2995 (softIrq * 100) / total); 48 2996 } 49 2997 } 50 2998 } 51 2999 52 3000 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics(); 53 3001 synchronized(bstats) { 54 3002 synchronized(mPidsSelfLocked) { 55 3003 if (haveNewCpuStats) { 56 3004 if (bstats.startAddingCpuLocked()) { 57 3005 int totalUTime = 0; 58 3006 int totalSTime = 0; 59 3007 final int N = mProcessCpuTracker.countStats(); 60 3008 for (int i=0; i<N; i++) { 61 3009 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 62 3010 if (!st.working) { 63 3011 continue; 64 3012 } 65 3013 ProcessRecord pr = mPidsSelfLocked.get(st.pid); 66 3014 totalUTime += st.rel_utime; 67 3015 totalSTime += st.rel_stime; 68 3016 if (pr != null) { 69 3017 BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats; 70 3018 if (ps == null || !ps.isActive()) { 71 3019 pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked( 72 3020 pr.info.uid, pr.processName); 73 3021 } 74 3022 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime); 75 3023 pr.curCpuTime += st.rel_utime + st.rel_stime; 76 3024 } else { 77 3025 BatteryStatsImpl.Uid.Proc ps = st.batteryStats; 78 3026 if (ps == null || !ps.isActive()) { 79 3027 st.batteryStats = ps = bstats.getProcessStatsLocked( 80 3028 bstats.mapUid(st.uid), st.name); 81 3029 } 82 3030 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime); 83 3031 } 84 3032 } 85 3033 final int userTime = mProcessCpuTracker.getLastUserTime(); 86 3034 final int systemTime = mProcessCpuTracker.getLastSystemTime(); 87 3035 final int iowaitTime = mProcessCpuTracker.getLastIoWaitTime(); 88 3036 final int irqTime = mProcessCpuTracker.getLastIrqTime(); 89 3037 final int softIrqTime = mProcessCpuTracker.getLastSoftIrqTime(); 90 3038 final int idleTime = mProcessCpuTracker.getLastIdleTime(); 91 3039 bstats.finishAddingCpuLocked(totalUTime, totalSTime, userTime, 92 3040 systemTime, iowaitTime, irqTime, softIrqTime, idleTime); 93 3041 } 94 3042 } 95 3043 } 96 3044 97 3045 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) { 98 3046 mLastWriteTime = now; 99 3047 mBatteryStatsService.scheduleWriteToDisk(); 100 3048 } 101 3049 } 102 3050 } 103 3051 } 104 3052
battery相关
1 3053 @Override 2 3054 public void batteryNeedsCpuUpdate() { 3 3055 updateCpuStatsNow(); 4 3056 } 5 3057 6 3058 @Override 7 3059 public void batteryPowerChanged(boolean onBattery) { 8 3060 // When plugging in, update the CPU stats first before changing 9 3061 // the plug state. 10 3062 updateCpuStatsNow(); 11 3063 synchronized (this) { 12 3064 synchronized(mPidsSelfLocked) { 13 3065 mOnBattery = DEBUG_POWER ? true : onBattery; 14 3066 } 15 3067 } 16 3068 } 17 3069 18 3070 @Override 19 3071 public void batterySendBroadcast(Intent intent) { 20 3072 synchronized (this) { 21 3073 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null, 22 3074 AppOpsManager.OP_NONE, null, false, false, 23 3075 -1, SYSTEM_UID, UserHandle.USER_ALL); 24 3076 } 25 3077 }
获取common service
1 3079 /** 2 3080 * Initialize the application bind args. These are passed to each 3 3081 * process when the bindApplication() IPC is sent to the process. They're 4 3082 * lazily setup to make sure the services are running when they're asked for. 5 3083 */ 6 3084 private HashMap<String, IBinder> getCommonServicesLocked(boolean isolated) { 7 3085 // Isolated processes won't get this optimization, so that we don't 8 3086 // violate the rules about which services they have access to. 9 3087 if (isolated) { 10 3088 if (mIsolatedAppBindArgs == null) { 11 3089 mIsolatedAppBindArgs = new HashMap<>(); 12 3090 mIsolatedAppBindArgs.put("package", ServiceManager.getService("package")); 13 3091 } 14 3092 return mIsolatedAppBindArgs; 15 3093 } 16 3094 17 3095 if (mAppBindArgs == null) { 18 3096 mAppBindArgs = new HashMap<>(); 19 3097 20 3098 // Setup the application init args 21 3099 mAppBindArgs.put("package", ServiceManager.getService("package")); 22 3100 mAppBindArgs.put("window", ServiceManager.getService("window")); 23 3101 mAppBindArgs.put(Context.ALARM_SERVICE, 24 3102 ServiceManager.getService(Context.ALARM_SERVICE)); 25 3103 } 26 3104 return mAppBindArgs; 27 3105 }
设置resumed activity,焦点stack,焦点task
1 3107 /** 2 3108 * Update AMS states when an activity is resumed. This should only be called by 3 3109 * {@link ActivityStack#setResumedActivityLocked} when an activity is resumed. 4 3110 */ 5 3111 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) { 6 3112 final TaskRecord task = r.getTask(); 7 3113 if (task.isApplicationTask()) { 8 3114 if (mCurAppTimeTracker != r.appTimeTracker) { 9 3115 // We are switching app tracking. Complete the current one. 10 3116 if (mCurAppTimeTracker != null) { 11 3117 mCurAppTimeTracker.stop(); 12 3118 mHandler.obtainMessage( 13 3119 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget(); 14 3120 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker); 15 3121 mCurAppTimeTracker = null; 16 3122 } 17 3123 if (r.appTimeTracker != null) { 18 3124 mCurAppTimeTracker = r.appTimeTracker; 19 3125 startTimeTrackingFocusedActivityLocked(); 20 3126 } 21 3127 } else { 22 3128 startTimeTrackingFocusedActivityLocked(); 23 3129 } 24 3130 } else { 25 3131 r.appTimeTracker = null; 26 3132 } 27 3133 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null 28 3134 // TODO: Probably not, because we don't want to resume voice on switching 29 3135 // back to this activity 30 3136 if (task.voiceInteractor != null) { 31 3137 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid); 32 3138 } else { 33 3139 finishRunningVoiceLocked(); 34 3140 35 3141 if (mLastResumedActivity != null) { 36 3142 final IVoiceInteractionSession session; 37 3143 38 3144 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask(); 39 3145 if (lastResumedActivityTask != null 40 3146 && lastResumedActivityTask.voiceSession != null) { 41 3147 session = lastResumedActivityTask.voiceSession; 42 3148 } else { 43 3149 session = mLastResumedActivity.voiceSession; 44 3150 } 45 3151 46 3152 if (session != null) { 47 3153 // We had been in a voice interaction session, but now focused has 48 3154 // move to something different. Just finish the session, we can't 49 3155 // return to it and retain the proper state and synchronization with 50 3156 // the voice interaction service. 51 3157 finishVoiceTask(session); 52 3158 } 53 3159 } 54 3160 } 55 3161 56 3162 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) { 57 3163 mHandler.removeMessages(FOREGROUND_PROFILE_CHANGED_MSG); 58 3164 mHandler.obtainMessage( 59 3165 FOREGROUND_PROFILE_CHANGED_MSG, r.userId, 0).sendToTarget(); 60 3166 } 61 3167 mLastResumedActivity = r; 62 3168 63 3169 mWindowManager.setFocusedApp(r.appToken, true); 64 3170 65 3171 applyUpdateLockStateLocked(r); 66 3172 applyUpdateVrModeLocked(r); 67 3173 68 3174 EventLogTags.writeAmSetResumedActivity( 69 3175 r == null ? -1 : r.userId, 70 3176 r == null ? "NULL" : r.shortComponentName, 71 3177 reason); 72 3178 } 73 3179 74 3180 @Override 75 3181 public void setFocusedStack(int stackId) { 76 3182 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()"); 77 3183 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId); 78 3184 final long callingId = Binder.clearCallingIdentity(); 79 3185 try { 80 3186 synchronized (this) { 81 3187 final ActivityStack stack = mStackSupervisor.getStack(stackId); 82 3188 if (stack == null) { 83 3189 return; 84 3190 } 85 3191 final ActivityRecord r = stack.topRunningActivityLocked(); 86 3192 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(r, "setFocusedStack")) { 87 3193 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 88 3194 } 89 3195 } 90 3196 } finally { 91 3197 Binder.restoreCallingIdentity(callingId); 92 3198 } 93 3199 } 94 3200 95 3201 @Override 96 3202 public void setFocusedTask(int taskId) { 97 3203 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()"); 98 3204 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId); 99 3205 final long callingId = Binder.clearCallingIdentity(); 100 3206 try { 101 3207 synchronized (this) { 102 3208 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 103 3209 if (task == null) { 104 3210 return; 105 3211 } 106 3212 final ActivityRecord r = task.topRunningActivityLocked(); 107 3213 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(r, "setFocusedTask")) { 108 3214 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 109 3215 } 110 3216 } 111 3217 } finally { 112 3218 Binder.restoreCallingIdentity(callingId); 113 3219 } 114 3220 } 115 3221
注册、取消注册task stack listener
1 3222 /** Sets the task stack listener that gets callbacks when a task stack changes. */ 2 3223 @Override 3 3224 public void registerTaskStackListener(ITaskStackListener listener) throws RemoteException { 4 3225 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "registerTaskStackListener()"); 5 3226 mTaskChangeNotificationController.registerTaskStackListener(listener); 6 3227 } 7 3228 8 3229 /** 9 3230 * Unregister a task stack listener so that it stops receiving callbacks. 10 3231 */ 11 3232 @Override 12 3233 public void unregisterTaskStackListener(ITaskStackListener listener) throws RemoteException { 13 3234 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "unregisterTaskStackListener()"); 14 3235 mTaskChangeNotificationController.unregisterTaskStackListener(listener); 15 3236 }
通知activity被drawn了
1 3238 @Override 2 3239 public void notifyActivityDrawn(IBinder token) { 3 3240 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token); 4 3241 synchronized (this) { 5 3242 ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token); 6 3243 if (r != null) { 7 3244 r.getStack().notifyActivityDrawnLocked(r); 8 3245 } 9 3246 } 10 3247 }
显示询问兼容模式和不支持zoom对话框
1 3277 final void showAskCompatModeDialogLocked(ActivityRecord r) { 2 3278 Message msg = Message.obtain(); 3 3279 msg.what = SHOW_COMPAT_MODE_DIALOG_UI_MSG; 4 3280 msg.obj = r.getTask().askedCompatMode ? null : r; 5 3281 mUiHandler.sendMessage(msg); 6 3282 } 7 3283 8 3284 final void showUnsupportedZoomDialogIfNeededLocked(ActivityRecord r) { 9 3285 final Configuration globalConfig = getGlobalConfiguration(); 10 3286 if (globalConfig.densityDpi != DisplayMetrics.DENSITY_DEVICE_STABLE 11 3287 && r.appInfo.requiresSmallestWidthDp > globalConfig.smallestScreenWidthDp) { 12 3288 final Message msg = Message.obtain(); 13 3289 msg.what = SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG; 14 3290 msg.obj = r; 15 3291 mUiHandler.sendMessage(msg); 16 3292 } 17 3293 }
更新内部lru进程
1 3295 private int updateLruProcessInternalLocked(ProcessRecord app, long now, int index, 2 3296 String what, Object obj, ProcessRecord srcApp) { 3 3297 app.lastActivityTime = now; 4 3298 5 3299 if (app.activities.size() > 0) { 6 3300 // Don't want to touch dependent processes that are hosting activities. 7 3301 return index; 8 3302 } 9 3303 10 3304 int lrui = mLruProcesses.lastIndexOf(app); 11 3305 if (lrui < 0) { 12 3306 Slog.wtf(TAG, "Adding dependent process " + app + " not on LRU list: " 13 3307 + what + " " + obj + " from " + srcApp); 14 3308 return index; 15 3309 } 16 3310 17 3311 if (lrui >= index) { 18 3312 // Don't want to cause this to move dependent processes *back* in the 19 3313 // list as if they were less frequently used. 20 3314 return index; 21 3315 } 22 3316 23 3317 if (lrui >= mLruProcessActivityStart) { 24 3318 // Don't want to touch dependent processes that are hosting activities. 25 3319 return index; 26 3320 } 27 3321 28 3322 mLruProcesses.remove(lrui); 29 3323 if (index > 0) { 30 3324 index--; 31 3325 } 32 3326 if (DEBUG_LRU) Slog.d(TAG_LRU, "Moving dep from " + lrui + " to " + index 33 3327 + " in LRU list: " + app); 34 3328 mLruProcesses.add(index, app); 35 3329 return index; 36 3330 }
杀掉进程组
1 3332 static void killProcessGroup(int uid, int pid) { 2 3333 if (sKillHandler != null) { 3 3334 sKillHandler.sendMessage( 4 3335 sKillHandler.obtainMessage(KillHandler.KILL_PROCESS_GROUP_MSG, uid, pid)); 5 3336 } else { 6 3337 Slog.w(TAG, "Asked to kill process group before system bringup!"); 7 3338 Process.killProcessGroup(uid, pid); 8 3339 } 9 3340 }
移除lru进程
1 3342 final void removeLruProcessLocked(ProcessRecord app) { 2 3343 int lrui = mLruProcesses.lastIndexOf(app); 3 3344 if (lrui >= 0) { 4 3345 if (!app.killed) { 5 3346 Slog.wtfStack(TAG, "Removing process that hasn't been killed: " + app); 6 3347 killProcessQuiet(app.pid); 7 3348 killProcessGroup(app.uid, app.pid); 8 3349 } 9 3350 if (lrui <= mLruProcessActivityStart) { 10 3351 mLruProcessActivityStart--; 11 3352 } 12 3353 if (lrui <= mLruProcessServiceStart) { 13 3354 mLruProcessServiceStart--; 14 3355 } 15 3356 mLruProcesses.remove(lrui); 16 3357 } 17 3358 }
更新lru进程
1 3360 final void updateLruProcessLocked(ProcessRecord app, boolean activityChange, 2 3361 ProcessRecord client) { 3 3362 final boolean hasActivity = app.activities.size() > 0 || app.hasClientActivities 4 3363 || app.treatLikeActivity; 5 3364 final boolean hasService = false; // not impl yet. app.services.size() > 0; 6 3365 if (!activityChange && hasActivity) { 7 3366 // The process has activities, so we are only allowing activity-based adjustments 8 3367 // to move it. It should be kept in the front of the list with other 9 3368 // processes that have activities, and we don't want those to change their 10 3369 // order except due to activity operations. 11 3370 return; 12 3371 } 13 3372 14 3373 mLruSeq++; 15 3374 final long now = SystemClock.uptimeMillis(); 16 3375 app.lastActivityTime = now; 17 3376 18 3377 // First a quick reject: if the app is already at the position we will 19 3378 // put it, then there is nothing to do. 20 3379 if (hasActivity) { 21 3380 final int N = mLruProcesses.size(); 22 3381 if (N > 0 && mLruProcesses.get(N-1) == app) { 23 3382 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, already top activity: " + app); 24 3383 return; 25 3384 } 26 3385 } else { 27 3386 if (mLruProcessServiceStart > 0 28 3387 && mLruProcesses.get(mLruProcessServiceStart-1) == app) { 29 3388 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, already top other: " + app); 30 3389 return; 31 3390 } 32 3391 } 33 3392 34 3393 int lrui = mLruProcesses.lastIndexOf(app); 35 3394 36 3395 if (app.persistent && lrui >= 0) { 37 3396 // We don't care about the position of persistent processes, as long as 38 3397 // they are in the list. 39 3398 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, persistent: " + app); 40 3399 return; 41 3400 } 42 3401 43 3402 /* In progress: compute new position first, so we can avoid doing work 44 3403 if the process is not actually going to move. Not yet working. 45 3404 int addIndex; 46 3405 int nextIndex; 47 3406 boolean inActivity = false, inService = false; 48 3407 if (hasActivity) { 49 3408 // Process has activities, put it at the very tipsy-top. 50 3409 addIndex = mLruProcesses.size(); 51 3410 nextIndex = mLruProcessServiceStart; 52 3411 inActivity = true; 53 3412 } else if (hasService) { 54 3413 // Process has services, put it at the top of the service list. 55 3414 addIndex = mLruProcessActivityStart; 56 3415 nextIndex = mLruProcessServiceStart; 57 3416 inActivity = true; 58 3417 inService = true; 59 3418 } else { 60 3419 // Process not otherwise of interest, it goes to the top of the non-service area. 61 3420 addIndex = mLruProcessServiceStart; 62 3421 if (client != null) { 63 3422 int clientIndex = mLruProcesses.lastIndexOf(client); 64 3423 if (clientIndex < 0) Slog.d(TAG, "Unknown client " + client + " when updating " 65 3424 + app); 66 3425 if (clientIndex >= 0 && addIndex > clientIndex) { 67 3426 addIndex = clientIndex; 68 3427 } 69 3428 } 70 3429 nextIndex = addIndex > 0 ? addIndex-1 : addIndex; 71 3430 } 72 3431 73 3432 Slog.d(TAG, "Update LRU at " + lrui + " to " + addIndex + " (act=" 74 3433 + mLruProcessActivityStart + "): " + app); 75 3434 */ 76 3435 77 3436 if (lrui >= 0) { 78 3437 if (lrui < mLruProcessActivityStart) { 79 3438 mLruProcessActivityStart--; 80 3439 } 81 3440 if (lrui < mLruProcessServiceStart) { 82 3441 mLruProcessServiceStart--; 83 3442 } 84 3443 /* 85 3444 if (addIndex > lrui) { 86 3445 addIndex--; 87 3446 } 88 3447 if (nextIndex > lrui) { 89 3448 nextIndex--; 90 3449 } 91 3450 */ 92 3451 mLruProcesses.remove(lrui); 93 3452 } 94 3453 95 3454 /* 96 3455 mLruProcesses.add(addIndex, app); 97 3456 if (inActivity) { 98 3457 mLruProcessActivityStart++; 99 3458 } 100 3459 if (inService) { 101 3460 mLruProcessActivityStart++; 102 3461 } 103 3462 */ 104 3463 105 3464 int nextIndex; 106 3465 if (hasActivity) { 107 3466 final int N = mLruProcesses.size(); 108 3467 if (app.activities.size() == 0 && mLruProcessActivityStart < (N - 1)) { 109 3468 // Process doesn't have activities, but has clients with 110 3469 // activities... move it up, but one below the top (the top 111 3470 // should always have a real activity). 112 3471 if (DEBUG_LRU) Slog.d(TAG_LRU, 113 3472 "Adding to second-top of LRU activity list: " + app); 114 3473 mLruProcesses.add(N - 1, app); 115 3474 // To keep it from spamming the LRU list (by making a bunch of clients), 116 3475 // we will push down any other entries owned by the app. 117 3476 final int uid = app.info.uid; 118 3477 for (int i = N - 2; i > mLruProcessActivityStart; i--) { 119 3478 ProcessRecord subProc = mLruProcesses.get(i); 120 3479 if (subProc.info.uid == uid) { 121 3480 // We want to push this one down the list. If the process after 122 3481 // it is for the same uid, however, don't do so, because we don't 123 3482 // want them internally to be re-ordered. 124 3483 if (mLruProcesses.get(i - 1).info.uid != uid) { 125 3484 if (DEBUG_LRU) Slog.d(TAG_LRU, 126 3485 "Pushing uid " + uid + " swapping at " + i + ": " 127 3486 + mLruProcesses.get(i) + " : " + mLruProcesses.get(i - 1)); 128 3487 ProcessRecord tmp = mLruProcesses.get(i); 129 3488 mLruProcesses.set(i, mLruProcesses.get(i - 1)); 130 3489 mLruProcesses.set(i - 1, tmp); 131 3490 i--; 132 3491 } 133 3492 } else { 134 3493 // A gap, we can stop here. 135 3494 break; 136 3495 } 137 3496 } 138 3497 } else { 139 3498 // Process has activities, put it at the very tipsy-top. 140 3499 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding to top of LRU activity list: " + app); 141 3500 mLruProcesses.add(app); 142 3501 } 143 3502 nextIndex = mLruProcessServiceStart; 144 3503 } else if (hasService) { 145 3504 // Process has services, put it at the top of the service list. 146 3505 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding to top of LRU service list: " + app); 147 3506 mLruProcesses.add(mLruProcessActivityStart, app); 148 3507 nextIndex = mLruProcessServiceStart; 149 3508 mLruProcessActivityStart++; 150 3509 } else { 151 3510 // Process not otherwise of interest, it goes to the top of the non-service area. 152 3511 int index = mLruProcessServiceStart; 153 3512 if (client != null) { 154 3513 // If there is a client, don't allow the process to be moved up higher 155 3514 // in the list than that client. 156 3515 int clientIndex = mLruProcesses.lastIndexOf(client); 157 3516 if (DEBUG_LRU && clientIndex < 0) Slog.d(TAG_LRU, "Unknown client " + client 158 3517 + " when updating " + app); 159 3518 if (clientIndex <= lrui) { 160 3519 // Don't allow the client index restriction to push it down farther in the 161 3520 // list than it already is. 162 3521 clientIndex = lrui; 163 3522 } 164 3523 if (clientIndex >= 0 && index > clientIndex) { 165 3524 index = clientIndex; 166 3525 } 167 3526 } 168 3527 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding at " + index + " of LRU list: " + app); 169 3528 mLruProcesses.add(index, app); 170 3529 nextIndex = index-1; 171 3530 mLruProcessActivityStart++; 172 3531 mLruProcessServiceStart++; 173 3532 } 174 3533 175 3534 // If the app is currently using a content provider or service, 176 3535 // bump those processes as well. 177 3536 for (int j=app.connections.size()-1; j>=0; j--) { 178 3537 ConnectionRecord cr = app.connections.valueAt(j); 179 3538 if (cr.binding != null && !cr.serviceDead && cr.binding.service != null 180 3539 && cr.binding.service.app != null 181 3540 && cr.binding.service.app.lruSeq != mLruSeq 182 3541 && !cr.binding.service.app.persistent) { 183 3542 nextIndex = updateLruProcessInternalLocked(cr.binding.service.app, now, nextIndex, 184 3543 "service connection", cr, app); 185 3544 } 186 3545 } 187 3546 for (int j=app.conProviders.size()-1; j>=0; j--) { 188 3547 ContentProviderRecord cpr = app.conProviders.get(j).provider; 189 3548 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq && !cpr.proc.persistent) { 190 3549 nextIndex = updateLruProcessInternalLocked(cpr.proc, now, nextIndex, 191 3550 "provider reference", cpr, app); 192 3551 } 193 3552 } 194 3553 }
获取进程record
1 3555 final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean keepIfLarge) { 2 3556 if (uid == SYSTEM_UID) { 3 3557 // The system gets to run in any process. If there are multiple 4 3558 // processes with the same uid, just pick the first (this 5 3559 // should never happen). 6 3560 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(processName); 7 3561 if (procs == null) return null; 8 3562 final int procCount = procs.size(); 9 3563 for (int i = 0; i < procCount; i++) { 10 3564 final int procUid = procs.keyAt(i); 11 3565 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) { 12 3566 // Don't use an app process or different user process for system component. 13 3567 continue; 14 3568 } 15 3569 return procs.valueAt(i); 16 3570 } 17 3571 } 18 3572 ProcessRecord proc = mProcessNames.get(processName, uid); 19 3573 if (false && proc != null && !keepIfLarge 20 3574 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY 21 3575 && proc.lastCachedPss >= 4000) { 22 3576 // Turn this condition on to cause killing to happen regularly, for testing. 23 3577 if (proc.baseProcessTracker != null) { 24 3578 proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss); 25 3579 } 26 3580 proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true); 27 3581 } else if (proc != null && !keepIfLarge 28 3582 && mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL 29 3583 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) { 30 3584 if (DEBUG_PSS) Slog.d(TAG_PSS, "May not keep " + proc + ": pss=" + proc.lastCachedPss); 31 3585 if (proc.lastCachedPss >= mProcessList.getCachedRestoreThresholdKb()) { 32 3586 if (proc.baseProcessTracker != null) { 33 3587 proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss); 34 3588 } 35 3589 proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true); 36 3590 } 37 3591 } 38 3592 return proc; 39 3593 } 40 3594
通知pkms package被使用
1 3595 void notifyPackageUse(String packageName, int reason) { 2 3596 IPackageManager pm = AppGlobals.getPackageManager(); 3 3597 try { 4 3598 pm.notifyPackageUse(packageName, reason); 5 3599 } catch (RemoteException e) { 6 3600 } 7 3601 }
是否下一个window变迁被提前
1 3603 boolean isNextTransitionForward() { 2 3604 int transit = mWindowManager.getPendingAppTransition(); 3 3605 return transit == TRANSIT_ACTIVITY_OPEN 4 3606 || transit == TRANSIT_TASK_OPEN 5 3607 || transit == TRANSIT_TASK_TO_FRONT; 6 3608 }
启动isolate进程
1 610 int startIsolatedProcess(String entryPoint, String[] entryPointArgs, 2 3611 String processName, String abiOverride, int uid, Runnable crashHandler) { 3 3612 synchronized(this) { 4 3613 ApplicationInfo info = new ApplicationInfo(); 5 3614 // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid. 6 3615 // For isolated processes, the former contains the parent's uid and the latter the 7 3616 // actual uid of the isolated process. 8 3617 // In the special case introduced by this method (which is, starting an isolated 9 3618 // process directly from the SystemServer without an actual parent app process) the 10 3619 // closest thing to a parent's uid is SYSTEM_UID. 11 3620 // The only important thing here is to keep AI.uid != PR.uid, in order to trigger 12 3621 // the |isolated| logic in the ProcessRecord constructor. 13 3622 info.uid = SYSTEM_UID; 14 3623 info.processName = processName; 15 3624 info.className = entryPoint; 16 3625 info.packageName = "android"; 17 3626 info.seInfoUser = SELinuxUtil.COMPLETE_STR; 18 3627 ProcessRecord proc = startProcessLocked(processName, info /* info */, 19 3628 false /* knownToBeDead */, 0 /* intentFlags */, "" /* hostingType */, 20 3629 null /* hostingName */, true /* allowWhileBooting */, true /* isolated */, 21 3630 uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs, 22 3631 crashHandler); 23 3632 return proc != null ? proc.pid : 0; 24 3633 } 25 3634 } 26 3635
启动进程
1 3636 final ProcessRecord startProcessLocked(String processName, 2 3637 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 3 3638 String hostingType, ComponentName hostingName, boolean allowWhileBooting, 4 3639 boolean isolated, boolean keepIfLarge) { 5 3640 return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType, 6 3641 hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge, 7 3642 null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */, 8 3643 null /* crashHandler */); 9 3644 } 10 3645 11 3646 final ProcessRecord startProcessLocked(String processName, ApplicationInfo info, 12 3647 boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName, 13 3648 boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge, 14 3649 String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) { 15 3650 long startTime = SystemClock.elapsedRealtime(); 16 3651 ProcessRecord app; 17 3652 if (!isolated) { 18 3653 app = getProcessRecordLocked(processName, info.uid, keepIfLarge); 19 3654 checkTime(startTime, "startProcess: after getProcessRecord"); 20 3655 21 3656 if ((intentFlags & Intent.FLAG_FROM_BACKGROUND) != 0) { 22 3657 // If we are in the background, then check to see if this process 23 3658 // is bad. If so, we will just silently fail. 24 3659 if (mAppErrors.isBadProcessLocked(info)) { 25 3660 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid 26 3661 + "/" + info.processName); 27 3662 return null; 28 3663 } 29 3664 } else { 30 3665 // When the user is explicitly starting a process, then clear its 31 3666 // crash count so that we won't make it bad until they see at 32 3667 // least one crash dialog again, and make the process good again 33 3668 // if it had been bad. 34 3669 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid 35 3670 + "/" + info.processName); 36 3671 mAppErrors.resetProcessCrashTimeLocked(info); 37 3672 if (mAppErrors.isBadProcessLocked(info)) { 38 3673 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, 39 3674 UserHandle.getUserId(info.uid), info.uid, 40 3675 info.processName); 41 3676 mAppErrors.clearBadProcessLocked(info); 42 3677 if (app != null) { 43 3678 app.bad = false; 44 3679 } 45 3680 } 46 3681 } 47 3682 } else { 48 3683 // If this is an isolated process, it can't re-use an existing process. 49 3684 app = null; 50 3685 } 51 3686 52 3687 // We don't have to do anything more if: 53 3688 // (1) There is an existing application record; and 54 3689 // (2) The caller doesn't think it is dead, OR there is no thread 55 3690 // object attached to it so we know it couldn't have crashed; and 56 3691 // (3) There is a pid assigned to it, so it is either starting or 57 3692 // already running. 58 3693 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "startProcess: name=" + processName 59 3694 + " app=" + app + " knownToBeDead=" + knownToBeDead 60 3695 + " thread=" + (app != null ? app.thread : null) 61 3696 + " pid=" + (app != null ? app.pid : -1)); 62 3697 if (app != null && app.pid > 0) { 63 3698 if ((!knownToBeDead && !app.killed) || app.thread == null) { 64 3699 // We already have the app running, or are waiting for it to 65 3700 // come up (we have a pid but not yet its thread), so keep it. 66 3701 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "App already running: " + app); 67 3702 // If this is a new package in the process, add the package to the list 68 3703 app.addPackage(info.packageName, info.versionCode, mProcessStats); 69 3704 checkTime(startTime, "startProcess: done, added package to proc"); 70 3705 return app; 71 3706 } 72 3707 73 3708 // An application record is attached to a previous process, 74 3709 // clean it up now. 75 3710 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_PROCESSES, "App died: " + app); 76 3711 checkTime(startTime, "startProcess: bad proc running, killing"); 77 3712 killProcessGroup(app.uid, app.pid); 78 3713 handleAppDiedLocked(app, true, true); 79 3714 checkTime(startTime, "startProcess: done killing old proc"); 80 3715 } 81 3716 82 3717 String hostingNameStr = hostingName != null 83 3718 ? hostingName.flattenToShortString() : null; 84 3719 85 3720 if (app == null) { 86 3721 checkTime(startTime, "startProcess: creating new process record"); 87 3722 app = newProcessRecordLocked(info, processName, isolated, isolatedUid); 88 3723 if (app == null) { 89 3724 Slog.w(TAG, "Failed making new process record for " 90 3725 + processName + "/" + info.uid + " isolated=" + isolated); 91 3726 return null; 92 3727 } 93 3728 app.crashHandler = crashHandler; 94 3729 checkTime(startTime, "startProcess: done creating new process record"); 95 3730 } else { 96 3731 // If this is a new package in the process, add the package to the list 97 3732 app.addPackage(info.packageName, info.versionCode, mProcessStats); 98 3733 checkTime(startTime, "startProcess: added package to existing proc"); 99 3734 } 100 3735 101 3736 // If the system is not ready yet, then hold off on starting this 102 3737 // process until it is. 103 3738 if (!mProcessesReady 104 3739 && !isAllowedWhileBooting(info) 105 3740 && !allowWhileBooting) { 106 3741 if (!mProcessesOnHold.contains(app)) { 107 3742 mProcessesOnHold.add(app); 108 3743 } 109 3744 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, 110 3745 "System not ready, putting on hold: " + app); 111 3746 checkTime(startTime, "startProcess: returning with proc on hold"); 112 3747 return app; 113 3748 } 114 3749 115 3750 checkTime(startTime, "startProcess: stepping in to startProcess"); 116 3751 startProcessLocked( 117 3752 app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs); 118 3753 checkTime(startTime, "startProcess: done starting proc!"); 119 3754 return (app.pid != 0) ? app : null; 120 3755 } 121 3756
是否是persist进程
1 3757 boolean isAllowedWhileBooting(ApplicationInfo ai) { 2 3758 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0; 3 3759 }
lock下启动进程
1 3761 private final void startProcessLocked(ProcessRecord app, 2 3762 String hostingType, String hostingNameStr) { 3 3763 startProcessLocked(app, hostingType, hostingNameStr, null /* abiOverride */, 4 3764 null /* entryPoint */, null /* entryPointArgs */); 5 3765 } 6 3766 7 3767 private final void startProcessLocked(ProcessRecord app, String hostingType, 8 3768 String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) { 9 3769 long startTime = SystemClock.elapsedRealtime(); 10 3770 if (app.pid > 0 && app.pid != MY_PID) { 11 3771 checkTime(startTime, "startProcess: removing from pids map"); 12 3772 synchronized (mPidsSelfLocked) { 13 3773 mPidsSelfLocked.remove(app.pid); 14 3774 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 15 3775 } 16 3776 checkTime(startTime, "startProcess: done removing from pids map"); 17 3777 app.setPid(0); 18 3778 } 19 3779 20 3780 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES, 21 3781 "startProcessLocked removing on hold: " + app); 22 3782 mProcessesOnHold.remove(app); 23 3783 24 3784 checkTime(startTime, "startProcess: starting to update cpu stats"); 25 3785 updateCpuStats(); 26 3786 checkTime(startTime, "startProcess: done updating cpu stats"); 27 3787 28 3788 try { 29 3789 try { 30 3790 final int userId = UserHandle.getUserId(app.uid); 31 3791 AppGlobals.getPackageManager().checkPackageStartable(app.info.packageName, userId); 32 3792 } catch (RemoteException e) { 33 3793 throw e.rethrowAsRuntimeException(); 34 3794 } 35 3795 36 3796 int uid = app.uid; 37 3797 int[] gids = null; 38 3798 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE; 39 3799 if (!app.isolated) { 40 3800 int[] permGids = null; 41 3801 try { 42 3802 checkTime(startTime, "startProcess: getting gids from package manager"); 43 3803 final IPackageManager pm = AppGlobals.getPackageManager(); 44 3804 permGids = pm.getPackageGids(app.info.packageName, 45 3805 MATCH_DEBUG_TRIAGED_MISSING, app.userId); 46 3806 StorageManagerInternal storageManagerInternal = LocalServices.getService( 47 3807 StorageManagerInternal.class); 48 3808 mountExternal = storageManagerInternal.getExternalStorageMountMode(uid, 49 3809 app.info.packageName); 50 3810 } catch (RemoteException e) { 51 3811 throw e.rethrowAsRuntimeException(); 52 3812 } 53 3813 54 3814 /* 55 3815 * Add shared application and profile GIDs so applications can share some 56 3816 * resources like shared libraries and access user-wide resources 57 3817 */ 58 3818 if (ArrayUtils.isEmpty(permGids)) { 59 3819 gids = new int[3]; 60 3820 } else { 61 3821 gids = new int[permGids.length + 3]; 62 3822 System.arraycopy(permGids, 0, gids, 3, permGids.length); 63 3823 } 64 3824 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid)); 65 3825 gids[1] = UserHandle.getCacheAppGid(UserHandle.getAppId(uid)); 66 3826 gids[2] = UserHandle.getUserGid(UserHandle.getUserId(uid)); 67 3827 } 68 3828 checkTime(startTime, "startProcess: building args"); 69 3829 if (mFactoryTest != FactoryTest.FACTORY_TEST_OFF) { 70 3830 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL 71 3831 && mTopComponent != null 72 3832 && app.processName.equals(mTopComponent.getPackageName())) { 73 3833 uid = 0; 74 3834 } 75 3835 if (mFactoryTest == FactoryTest.FACTORY_TEST_HIGH_LEVEL 76 3836 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) { 77 3837 uid = 0; 78 3838 } 79 3839 } 80 3840 int debugFlags = 0; 81 3841 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 82 3842 debugFlags |= Zygote.DEBUG_ENABLE_JDWP; 83 3843 debugFlags |= Zygote.DEBUG_JAVA_DEBUGGABLE; 84 3844 // Also turn on CheckJNI for debuggable apps. It's quite 85 3845 // awkward to turn on otherwise. 86 3846 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 87 3847 } 88 3848 // Run the app in safe mode if its manifest requests so or the 89 3849 // system is booted in safe mode. 90 3850 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 || 91 3851 mSafeMode == true) { 92 3852 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE; 93 3853 } 94 3854 if ("1".equals(SystemProperties.get("debug.checkjni"))) { 95 3855 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 96 3856 } 97 3857 String genDebugInfoProperty = SystemProperties.get("debug.generate-debug-info"); 98 3858 if ("true".equals(genDebugInfoProperty)) { 99 3859 debugFlags |= Zygote.DEBUG_GENERATE_DEBUG_INFO; 100 3860 } 101 3861 if ("1".equals(SystemProperties.get("debug.jni.logging"))) { 102 3862 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING; 103 3863 } 104 3864 if ("1".equals(SystemProperties.get("debug.assert"))) { 105 3865 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT; 106 3866 } 107 3867 if (mNativeDebuggingApp != null && mNativeDebuggingApp.equals(app.processName)) { 108 3868 // Enable all debug flags required by the native debugger. 109 3869 debugFlags |= Zygote.DEBUG_ALWAYS_JIT; // Don't interpret anything 110 3870 debugFlags |= Zygote.DEBUG_GENERATE_DEBUG_INFO; // Generate debug info 111 3871 debugFlags |= Zygote.DEBUG_NATIVE_DEBUGGABLE; // Disbale optimizations 112 3872 mNativeDebuggingApp = null; 113 3873 } 114 3874 115 3875 String invokeWith = null; 116 3876 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 117 3877 // Debuggable apps may include a wrapper script with their library directory. 118 3878 String wrapperFileName = app.info.nativeLibraryDir + "/wrap.sh"; 119 3879 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); 120 3880 try { 121 3881 if (new File(wrapperFileName).exists()) { 122 3882 invokeWith = "/system/bin/logwrapper " + wrapperFileName; 123 3883 } 124 3884 } finally { 125 3885 StrictMode.setThreadPolicy(oldPolicy); 126 3886 } 127 3887 } 128 3888 129 3889 String requiredAbi = (abiOverride != null) ? abiOverride : app.info.primaryCpuAbi; 130 3890 if (requiredAbi == null) { 131 3891 requiredAbi = Build.SUPPORTED_ABIS[0]; 132 3892 } 133 3893 134 3894 String instructionSet = null; 135 3895 if (app.info.primaryCpuAbi != null) { 136 3896 instructionSet = VMRuntime.getInstructionSet(app.info.primaryCpuAbi); 137 3897 } 138 3898 139 3899 app.gids = gids; 140 3900 app.requiredAbi = requiredAbi; 141 3901 app.instructionSet = instructionSet; 142 3902 143 3903 // the per-user SELinux context must be set 144 3904 if (TextUtils.isEmpty(app.info.seInfoUser)) { 145 3905 Slog.wtf(TAG, "SELinux tag not defined", 146 3906 new IllegalStateException("SELinux tag not defined for " 147 3907 + app.info.packageName + " (uid " + app.uid + ")")); 148 3908 } 149 3909 final String seInfo = app.info.seInfo 150 3910 + (TextUtils.isEmpty(app.info.seInfoUser) ? "" : app.info.seInfoUser); 151 3911 // Start the process. It will either succeed and return a result containing 152 3912 // the PID of the new process, or else throw a RuntimeException. 153 3913 boolean isActivityProcess = (entryPoint == null); 154 3914 if (entryPoint == null) entryPoint = "android.app.ActivityThread"; 155 3915 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " + 156 3916 app.processName); 157 3917 checkTime(startTime, "startProcess: asking zygote to start proc"); 158 3918 ProcessStartResult startResult; 159 3919 if (hostingType.equals("webview_service")) { 160 3920 startResult = startWebView(entryPoint, 161 3921 app.processName, uid, uid, gids, debugFlags, mountExternal, 162 3922 app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, 163 3923 app.info.dataDir, null, entryPointArgs); 164 3924 } else { 165 3925 startResult = Process.start(entryPoint, 166 3926 app.processName, uid, uid, gids, debugFlags, mountExternal, 167 3927 app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, 168 3928 app.info.dataDir, invokeWith, entryPointArgs); 169 3929 } 170 3930 checkTime(startTime, "startProcess: returned from zygote!"); 171 3931 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 172 3932 173 3933 mBatteryStatsService.noteProcessStart(app.processName, app.info.uid); 174 3934 checkTime(startTime, "startProcess: done updating battery stats"); 175 3935 176 3936 EventLog.writeEvent(EventLogTags.AM_PROC_START, 177 3937 UserHandle.getUserId(uid), startResult.pid, uid, 178 3938 app.processName, hostingType, 179 3939 hostingNameStr != null ? hostingNameStr : ""); 180 3940 181 3941 try { 182 3942 AppGlobals.getPackageManager().logAppProcessStartIfNeeded(app.processName, app.uid, 183 3943 seInfo, app.info.sourceDir, startResult.pid); 184 3944 } catch (RemoteException ex) { 185 3945 // Ignore 186 3946 } 187 3947 188 3948 if (app.persistent) { 189 3949 Watchdog.getInstance().processStarted(app.processName, startResult.pid); 190 3950 } 191 3951 192 3952 checkTime(startTime, "startProcess: building log message"); 193 3953 StringBuilder buf = mStringBuilder; 194 3954 buf.setLength(0); 195 3955 buf.append("Start proc "); 196 3956 buf.append(startResult.pid); 197 3957 buf.append(':'); 198 3958 buf.append(app.processName); 199 3959 buf.append('/'); 200 3960 UserHandle.formatUid(buf, uid); 201 3961 if (!isActivityProcess) { 202 3962 buf.append(" ["); 203 3963 buf.append(entryPoint); 204 3964 buf.append("]"); 205 3965 } 206 3966 buf.append(" for "); 207 3967 buf.append(hostingType); 208 3968 if (hostingNameStr != null) { 209 3969 buf.append(" "); 210 3970 buf.append(hostingNameStr); 211 3971 } 212 3972 Slog.i(TAG, buf.toString()); 213 3973 app.setPid(startResult.pid); 214 3974 app.usingWrapper = startResult.usingWrapper; 215 3975 app.removed = false; 216 3976 app.killed = false; 217 3977 app.killedByAm = false; 218 3978 checkTime(startTime, "startProcess: starting to update pids map"); 219 3979 ProcessRecord oldApp; 220 3980 synchronized (mPidsSelfLocked) { 221 3981 oldApp = mPidsSelfLocked.get(startResult.pid); 222 3982 } 223 3983 // If there is already an app occupying that pid that hasn't been cleaned up 224 3984 if (oldApp != null && !app.isolated) { 225 3985 // Clean up anything relating to this pid first 226 3986 Slog.w(TAG, "Reusing pid " + startResult.pid 227 3987 + " while app is still mapped to it"); 228 3988 cleanUpApplicationRecordLocked(oldApp, false, false, -1, 229 3989 true /*replacingPid*/); 230 3990 } 231 3991 synchronized (mPidsSelfLocked) { 232 3992 this.mPidsSelfLocked.put(startResult.pid, app); 233 3993 if (isActivityProcess) { 234 3994 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 235 3995 msg.obj = app; 236 3996 mHandler.sendMessageDelayed(msg, startResult.usingWrapper 237 3997 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT); 238 3998 } 239 3999 } 240 4000 checkTime(startTime, "startProcess: done updating pids map"); 241 4001 } catch (RuntimeException e) { 242 4002 Slog.e(TAG, "Failure starting process " + app.processName, e); 243 4003 244 4004 // Something went very wrong while trying to start this process; one 245 4005 // common case is when the package is frozen due to an active 246 4006 // upgrade. To recover, clean up any active bookkeeping related to 247 4007 // starting this process. (We already invoked this method once when 248 4008 // the package was initially frozen through KILL_APPLICATION_MSG, so 249 4009 // it doesn't hurt to use it again.) 250 4010 forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid), false, 251 4011 false, true, false, false, UserHandle.getUserId(app.userId), "start failure"); 252 4012 } 253 4013 } 254 4014
更新使用状态
1 4015 void updateUsageStats(ActivityRecord component, boolean resumed) { 2 4016 if (DEBUG_SWITCH) Slog.d(TAG_SWITCH, 3 4017 "updateUsageStats: comp=" + component + "res=" + resumed); 4 4018 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 5 4019 if (resumed) { 6 4020 if (mUsageStatsService != null) { 7 4021 mUsageStatsService.reportEvent(component.realActivity, component.userId, 8 4022 UsageEvents.Event.MOVE_TO_FOREGROUND); 9 4023 } 10 4024 synchronized (stats) { 11 4025 stats.noteActivityResumedLocked(component.app.uid); 12 4026 } 13 4027 } else { 14 4028 if (mUsageStatsService != null) { 15 4029 mUsageStatsService.reportEvent(component.realActivity, component.userId, 16 4030 UsageEvents.Event.MOVE_TO_BACKGROUND); 17 4031 } 18 4032 synchronized (stats) { 19 4033 stats.noteActivityPausedLocked(component.app.uid); 20 4034 } 21 4035 } 22 4036 }
获取home intent
1 4038 Intent getHomeIntent() { 2 4039 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null); 3 4040 intent.setComponent(mTopComponent); 4 4041 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING); 5 4042 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) { 6 4043 intent.addCategory(Intent.CATEGORY_HOME); 7 4044 } 8 4045 return intent; 9 4046 } 10 4047
启动home activity
1 4048 boolean startHomeActivityLocked(int userId, String reason) { 2 4049 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL 3 4050 && mTopAction == null) { 4 4051 // We are running in factory test mode, but unable to find 5 4052 // the factory test app, so just sit around displaying the 6 4053 // error message and don't try to start anything. 7 4054 return false; 8 4055 } 9 4056 Intent intent = getHomeIntent(); 10 4057 ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId); 11 4058 if (aInfo != null) { 12 4059 intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name)); 13 4060 // Don't do this if the home app is currently being 14 4061 // instrumented. 15 4062 aInfo = new ActivityInfo(aInfo); 16 4063 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId); 17 4064 ProcessRecord app = getProcessRecordLocked(aInfo.processName, 18 4065 aInfo.applicationInfo.uid, true); 19 4066 if (app == null || app.instr == null) { 20 4067 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); 21 4068 final int resolvedUserId = UserHandle.getUserId(aInfo.applicationInfo.uid); 22 4069 // For ANR debugging to verify if the user activity is the one that actually 23 4070 // launched. 24 4071 final String myReason = reason + ":" + userId + ":" + resolvedUserId; 25 4072 mActivityStarter.startHomeActivityLocked(intent, aInfo, myReason); 26 4073 } 27 4074 } else { 28 4075 Slog.wtf(TAG, "No home screen found for " + intent, new Throwable()); 29 4076 } 30 4077 31 4078 return true; 32 4079 }
解析ActivityInfo
1 4081 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) { 2 4082 ActivityInfo ai = null; 3 4083 ComponentName comp = intent.getComponent(); 4 4084 try { 5 4085 if (comp != null) { 6 4086 // Factory test. 7 4087 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId); 8 4088 } else { 9 4089 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent( 10 4090 intent, 11 4091 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12 4092 flags, userId); 13 4093 14 4094 if (info != null) { 15 4095 ai = info.activityInfo; 16 4096 } 17 4097 } 18 4098 } catch (RemoteException e) { 19 4099 // ignore 20 4100 } 21 4101 22 4102 return ai; 23 4103 }
启动设置activity
1 4105 /** 2 4106 * Starts the "new version setup screen" if appropriate. 3 4107 */ 4 4108 void startSetupActivityLocked() { 5 4109 // Only do this once per boot. 6 4110 if (mCheckedForSetup) { 7 4111 return; 8 4112 } 9 4113 10 4114 // We will show this screen if the current one is a different 11 4115 // version than the last one shown, and we are not running in 12 4116 // low-level factory test mode. 13 4117 final ContentResolver resolver = mContext.getContentResolver(); 14 4118 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL && 15 4119 Settings.Global.getInt(resolver, 16 4120 Settings.Global.DEVICE_PROVISIONED, 0) != 0) { 17 4121 mCheckedForSetup = true; 18 4122 19 4123 // See if we should be showing the platform update setup UI. 20 4124 final Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP); 21 4125 final List<ResolveInfo> ris = mContext.getPackageManager().queryIntentActivities(intent, 22 4126 PackageManager.MATCH_SYSTEM_ONLY | PackageManager.GET_META_DATA); 23 4127 if (!ris.isEmpty()) { 24 4128 final ResolveInfo ri = ris.get(0); 25 4129 String vers = ri.activityInfo.metaData != null 26 4130 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION) 27 4131 : null; 28 4132 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) { 29 4133 vers = ri.activityInfo.applicationInfo.metaData.getString( 30 4134 Intent.METADATA_SETUP_VERSION); 31 4135 } 32 4136 String lastVers = Settings.Secure.getString( 33 4137 resolver, Settings.Secure.LAST_SETUP_SHOWN); 34 4138 if (vers != null && !vers.equals(lastVers)) { 35 4139 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 36 4140 intent.setComponent(new ComponentName( 37 4141 ri.activityInfo.packageName, ri.activityInfo.name)); 38 4142 mActivityStarter.startActivityLocked(null, intent, null /*ephemeralIntent*/, 39 4143 null, ri.activityInfo, null /*rInfo*/, null, null, null, null, 0, 0, 0, 40 4144 null, 0, 0, 0, null, false, false, null, null, null, 41 4145 "startSetupActivity"); 42 4146 } 43 4147 } 44 4148 } 45 4149 }
获取兼容信息
1 4151 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) { 2 4152 return mCompatModePackages.compatibilityInfoForPackageLocked(ai); 3 4153 }
强制不要是isolated调用者
1 4155 void enforceNotIsolatedCaller(String caller) { 2 4156 if (UserHandle.isIsolated(Binder.getCallingUid())) { 3 4157 throw new SecurityException("Isolated process not allowed to call " + caller); 4 4158 } 5 4159 }
获取、设置前台activity、package屏幕兼容模式,package询问屏幕兼容模式,是否有使用使用统计信息权限,获取进程状态
1 4170 @Override 2 4171 public int getFrontActivityScreenCompatMode() { 3 4172 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode"); 4 4173 synchronized (this) { 5 4174 return mCompatModePackages.getFrontActivityScreenCompatModeLocked(); 6 4175 } 7 4176 } 8 4177 9 4178 @Override 10 4179 public void setFrontActivityScreenCompatMode(int mode) { 11 4180 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 12 4181 "setFrontActivityScreenCompatMode"); 13 4182 synchronized (this) { 14 4183 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode); 15 4184 } 16 4185 } 17 4186 18 4187 @Override 19 4188 public int getPackageScreenCompatMode(String packageName) { 20 4189 enforceNotIsolatedCaller("getPackageScreenCompatMode"); 21 4190 synchronized (this) { 22 4191 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName); 23 4192 } 24 4193 } 25 4194 26 4195 @Override 27 4196 public void setPackageScreenCompatMode(String packageName, int mode) { 28 4197 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 29 4198 "setPackageScreenCompatMode"); 30 4199 synchronized (this) { 31 4200 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode); 32 4201 } 33 4202 } 34 4203 35 4204 @Override 36 4205 public boolean getPackageAskScreenCompat(String packageName) { 37 4206 enforceNotIsolatedCaller("getPackageAskScreenCompat"); 38 4207 synchronized (this) { 39 4208 return mCompatModePackages.getPackageAskCompatModeLocked(packageName); 40 4209 } 41 4210 } 42 4211 43 4212 @Override 44 4213 public void setPackageAskScreenCompat(String packageName, boolean ask) { 45 4214 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 46 4215 "setPackageAskScreenCompat"); 47 4216 synchronized (this) { 48 4217 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask); 49 4218 } 50 4219 } 51 4220 52 4221 private boolean hasUsageStatsPermission(String callingPackage) { 53 4222 final int mode = mAppOpsService.checkOperation(AppOpsManager.OP_GET_USAGE_STATS, 54 4223 Binder.getCallingUid(), callingPackage); 55 4224 if (mode == AppOpsManager.MODE_DEFAULT) { 56 4225 return checkCallingPermission(Manifest.permission.PACKAGE_USAGE_STATS) 57 4226 == PackageManager.PERMISSION_GRANTED; 58 4227 } 59 4228 return mode == AppOpsManager.MODE_ALLOWED; 60 4229 } 61 4230 62 4231 @Override 63 4232 public int getPackageProcessState(String packageName, String callingPackage) { 64 4233 if (!hasUsageStatsPermission(callingPackage)) { 65 4234 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 66 4235 "getPackageProcessState"); 67 4236 } 68 4237 69 4238 int procState = ActivityManager.PROCESS_STATE_NONEXISTENT; 70 4239 synchronized (this) { 71 4240 for (int i=mLruProcesses.size()-1; i>=0; i--) { 72 4241 final ProcessRecord proc = mLruProcesses.get(i); 73 4242 if (procState > proc.setProcState) { 74 4243 if (proc.pkgList.containsKey(packageName) || 75 4244 (proc.pkgDeps != null && proc.pkgDeps.contains(packageName))) { 76 4245 procState = proc.setProcState; 77 4246 } 78 4247 } 79 4248 } 80 4249 } 81 4250 return procState; 82 4251 }
设置进程trim level
1 4253 @Override 2 4254 public boolean setProcessMemoryTrimLevel(String process, int userId, int level) 3 4255 throws RemoteException { 4 4256 synchronized (this) { 5 4257 final ProcessRecord app = findProcessLocked(process, userId, "setProcessMemoryTrimLevel"); 6 4258 if (app == null) { 7 4259 throw new IllegalArgumentException("Unknown process: " + process); 8 4260 } 9 4261 if (app.thread == null) { 10 4262 throw new IllegalArgumentException("Process has no app thread"); 11 4263 } 12 4264 if (app.trimMemoryLevel >= level) { 13 4265 throw new IllegalArgumentException( 14 4266 "Unable to set a higher trim level than current level"); 15 4267 } 16 4268 if (!(level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN || 17 4269 app.curProcState > ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND)) { 18 4270 throw new IllegalArgumentException("Unable to set a background trim level " 19 4271 + "on a foreground process"); 20 4272 } 21 4273 app.thread.scheduleTrimMemory(level); 22 4274 app.trimMemoryLevel = level; 23 4275 return true; 24 4276 } 25 4277 }
分发进程状态改变,进程死亡,进程Uid改变,进程Uid为观察者改变,
1 4279 private void dispatchProcessesChanged() { 2 4280 int N; 3 4281 synchronized (this) { 4 4282 N = mPendingProcessChanges.size(); 5 4283 if (mActiveProcessChanges.length < N) { 6 4284 mActiveProcessChanges = new ProcessChangeItem[N]; 7 4285 } 8 4286 mPendingProcessChanges.toArray(mActiveProcessChanges); 9 4287 mPendingProcessChanges.clear(); 10 4288 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 11 4289 "*** Delivering " + N + " process changes"); 12 4290 } 13 4291 14 4292 int i = mProcessObservers.beginBroadcast(); 15 4293 while (i > 0) { 16 4294 i--; 17 4295 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 18 4296 if (observer != null) { 19 4297 try { 20 4298 for (int j=0; j<N; j++) { 21 4299 ProcessChangeItem item = mActiveProcessChanges[j]; 22 4300 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) { 23 4301 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 24 4302 "ACTIVITIES CHANGED pid=" + item.pid + " uid=" 25 4303 + item.uid + ": " + item.foregroundActivities); 26 4304 observer.onForegroundActivitiesChanged(item.pid, item.uid, 27 4305 item.foregroundActivities); 28 4306 } 29 4307 } 30 4308 } catch (RemoteException e) { 31 4309 } 32 4310 } 33 4311 } 34 4312 mProcessObservers.finishBroadcast(); 35 4313 36 4314 synchronized (this) { 37 4315 for (int j=0; j<N; j++) { 38 4316 mAvailProcessChanges.add(mActiveProcessChanges[j]); 39 4317 } 40 4318 } 41 4319 } 42 4320 43 4321 private void dispatchProcessDied(int pid, int uid) { 44 4322 int i = mProcessObservers.beginBroadcast(); 45 4323 while (i > 0) { 46 4324 i--; 47 4325 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 48 4326 if (observer != null) { 49 4327 try { 50 4328 observer.onProcessDied(pid, uid); 51 4329 } catch (RemoteException e) { 52 4330 } 53 4331 } 54 4332 } 55 4333 mProcessObservers.finishBroadcast(); 56 4334 } 57 4335 58 4336 @VisibleForTesting 59 4337 void dispatchUidsChanged() { 60 4338 int N; 61 4339 synchronized (this) { 62 4340 N = mPendingUidChanges.size(); 63 4341 if (mActiveUidChanges.length < N) { 64 4342 mActiveUidChanges = new UidRecord.ChangeItem[N]; 65 4343 } 66 4344 for (int i=0; i<N; i++) { 67 4345 final UidRecord.ChangeItem change = mPendingUidChanges.get(i); 68 4346 mActiveUidChanges[i] = change; 69 4347 if (change.uidRecord != null) { 70 4348 change.uidRecord.pendingChange = null; 71 4349 change.uidRecord = null; 72 4350 } 73 4351 } 74 4352 mPendingUidChanges.clear(); 75 4353 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 76 4354 "*** Delivering " + N + " uid changes"); 77 4355 } 78 4356 79 4357 int i = mUidObservers.beginBroadcast(); 80 4358 while (i > 0) { 81 4359 i--; 82 4360 dispatchUidsChangedForObserver(mUidObservers.getBroadcastItem(i), 83 4361 (UidObserverRegistration) mUidObservers.getBroadcastCookie(i), N); 84 4362 } 85 4363 mUidObservers.finishBroadcast(); 86 4364 87 4365 if (VALIDATE_UID_STATES && mUidObservers.getRegisteredCallbackCount() > 0) { 88 4366 for (int j = 0; j < N; ++j) { 89 4367 final UidRecord.ChangeItem item = mActiveUidChanges[j]; 90 4368 if (item.change == UidRecord.CHANGE_GONE 91 4369 || item.change == UidRecord.CHANGE_GONE_IDLE) { 92 4370 mValidateUids.remove(item.uid); 93 4371 } else { 94 4372 UidRecord validateUid = mValidateUids.get(item.uid); 95 4373 if (validateUid == null) { 96 4374 validateUid = new UidRecord(item.uid); 97 4375 mValidateUids.put(item.uid, validateUid); 98 4376 } 99 4377 if (item.change == UidRecord.CHANGE_IDLE) { 100 4378 validateUid.idle = true; 101 4379 } else if (item.change == UidRecord.CHANGE_ACTIVE) { 102 4380 validateUid.idle = false; 103 4381 } 104 4382 validateUid.curProcState = validateUid.setProcState = item.processState; 105 4383 validateUid.lastDispatchedProcStateSeq = item.procStateSeq; 106 4384 } 107 4385 } 108 4386 } 109 4387 110 4388 synchronized (this) { 111 4389 for (int j = 0; j < N; j++) { 112 4390 mAvailUidChanges.add(mActiveUidChanges[j]); 113 4391 } 114 4392 } 115 4393 } 116 4394 117 4395 private void dispatchUidsChangedForObserver(IUidObserver observer, 118 4396 UidObserverRegistration reg, int changesSize) { 119 4397 if (observer == null) { 120 4398 return; 121 4399 } 122 4400 try { 123 4401 for (int j = 0; j < changesSize; j++) { 124 4402 UidRecord.ChangeItem item = mActiveUidChanges[j]; 125 4403 final int change = item.change; 126 4404 if (change == UidRecord.CHANGE_IDLE 127 4405 || change == UidRecord.CHANGE_GONE_IDLE) { 128 4406 if ((reg.which & ActivityManager.UID_OBSERVER_IDLE) != 0) { 129 4407 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 130 4408 "UID idle uid=" + item.uid); 131 4409 observer.onUidIdle(item.uid, item.ephemeral); 132 4410 } 133 4411 } else if (change == UidRecord.CHANGE_ACTIVE) { 134 4412 if ((reg.which & ActivityManager.UID_OBSERVER_ACTIVE) != 0) { 135 4413 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 136 4414 "UID active uid=" + item.uid); 137 4415 observer.onUidActive(item.uid); 138 4416 } 139 4417 } 140 4418 if (change == UidRecord.CHANGE_GONE 141 4419 || change == UidRecord.CHANGE_GONE_IDLE) { 142 4420 if ((reg.which & ActivityManager.UID_OBSERVER_GONE) != 0) { 143 4421 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 144 4422 "UID gone uid=" + item.uid); 145 4423 observer.onUidGone(item.uid, item.ephemeral); 146 4424 } 147 4425 if (reg.lastProcStates != null) { 148 4426 reg.lastProcStates.delete(item.uid); 149 4427 } 150 4428 } else { 151 4429 if ((reg.which & ActivityManager.UID_OBSERVER_PROCSTATE) != 0) { 152 4430 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 153 4431 "UID CHANGED uid=" + item.uid 154 4432 + ": " + item.processState); 155 4433 boolean doReport = true; 156 4434 if (reg.cutpoint >= ActivityManager.MIN_PROCESS_STATE) { 157 4435 final int lastState = reg.lastProcStates.get(item.uid, 158 4436 ActivityManager.PROCESS_STATE_UNKNOWN); 159 4437 if (lastState != ActivityManager.PROCESS_STATE_UNKNOWN) { 160 4438 final boolean lastAboveCut = lastState <= reg.cutpoint; 161 4439 final boolean newAboveCut = item.processState <= reg.cutpoint; 162 4440 doReport = lastAboveCut != newAboveCut; 163 4441 } else { 164 4442 doReport = item.processState 165 4443 != ActivityManager.PROCESS_STATE_NONEXISTENT; 166 4444 } 167 4445 } 168 4446 if (doReport) { 169 4447 if (reg.lastProcStates != null) { 170 4448 reg.lastProcStates.put(item.uid, item.processState); 171 4449 } 172 4450 observer.onUidStateChanged(item.uid, item.processState, 173 4451 item.procStateSeq); 174 4452 } 175 4453 } 176 4454 } 177 4455 } 178 4456 } catch (RemoteException e) { 179 4457 } 180 4458 } 181 4459
启动Activity相关
1 4459 2 4460 @Override 3 4461 public final int startActivity(IApplicationThread caller, String callingPackage, 4 4462 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 5 4463 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) { 6 4464 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, 7 4465 resultWho, requestCode, startFlags, profilerInfo, bOptions, 8 4466 UserHandle.getCallingUserId()); 9 4467 } 10 4468 11 4469 final int startActivity(Intent intent, ActivityStackSupervisor.ActivityContainer container) { 12 4470 enforceNotIsolatedCaller("ActivityContainer.startActivity"); 13 4471 final int userId = mUserController.handleIncomingUser(Binder.getCallingPid(), 14 4472 Binder.getCallingUid(), mStackSupervisor.mCurrentUser, false, 15 4473 ActivityManagerService.ALLOW_FULL_ONLY, "ActivityContainer", null); 16 4474 17 4475 // TODO: Switch to user app stacks here. 18 4476 String mimeType = intent.getType(); 19 4477 final Uri data = intent.getData(); 20 4478 if (mimeType == null && data != null && "content".equals(data.getScheme())) { 21 4479 mimeType = getProviderMimeType(data, userId); 22 4480 } 23 4481 container.checkEmbeddedAllowedInner(userId, intent, mimeType); 24 4482 25 4483 intent.addFlags(FORCE_NEW_TASK_FLAGS); 26 4484 return mActivityStarter.startActivityMayWait(null, -1, null, intent, mimeType, null, null, 27 4485 null, null, 0, 0, null, null, null, null, false, userId, container, null, 28 4486 "startActivity"); 29 4487 } 30 4488 31 4489 @Override 32 4490 public final int startActivityAsUser(IApplicationThread caller, String callingPackage, 33 4491 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 34 4492 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) { 35 4493 enforceNotIsolatedCaller("startActivity"); 36 4494 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 37 4495 userId, false, ALLOW_FULL_ONLY, "startActivity", null); 38 4496 // TODO: Switch to user app stacks here. 39 4497 return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent, 40 4498 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, 41 4499 profilerInfo, null, null, bOptions, false, userId, null, null, 42 4500 "startActivityAsUser"); 43 4501 } 44 4502 45 4503 @Override 46 4504 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage, 47 4505 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 48 4506 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, boolean ignoreTargetSecurity, 49 4507 int userId) { 50 4508 51 4509 // This is very dangerous -- it allows you to perform a start activity (including 52 4510 // permission grants) as any app that may launch one of your own activities. So 53 4511 // we will only allow this to be done from activities that are part of the core framework, 54 4512 // and then only when they are running as the system. 55 4513 final ActivityRecord sourceRecord; 56 4514 final int targetUid; 57 4515 final String targetPackage; 58 4516 synchronized (this) { 59 4517 if (resultTo == null) { 60 4518 throw new SecurityException("Must be called from an activity"); 61 4519 } 62 4520 sourceRecord = mStackSupervisor.isInAnyStackLocked(resultTo); 63 4521 if (sourceRecord == null) { 64 4522 throw new SecurityException("Called with bad activity token: " + resultTo); 65 4523 } 66 4524 if (!sourceRecord.info.packageName.equals("android")) { 67 4525 throw new SecurityException( 68 4526 "Must be called from an activity that is declared in the android package"); 69 4527 } 70 4528 if (sourceRecord.app == null) { 71 4529 throw new SecurityException("Called without a process attached to activity"); 72 4530 } 73 4531 if (UserHandle.getAppId(sourceRecord.app.uid) != SYSTEM_UID) { 74 4532 // This is still okay, as long as this activity is running under the 75 4533 // uid of the original calling activity. 76 4534 if (sourceRecord.app.uid != sourceRecord.launchedFromUid) { 77 4535 throw new SecurityException( 78 4536 "Calling activity in uid " + sourceRecord.app.uid 79 4537 + " must be system uid or original calling uid " 80 4538 + sourceRecord.launchedFromUid); 81 4539 } 82 4540 } 83 4541 if (ignoreTargetSecurity) { 84 4542 if (intent.getComponent() == null) { 85 4543 throw new SecurityException( 86 4544 "Component must be specified with ignoreTargetSecurity"); 87 4545 } 88 4546 if (intent.getSelector() != null) { 89 4547 throw new SecurityException( 90 4548 "Selector not allowed with ignoreTargetSecurity"); 91 4549 } 92 4550 } 93 4551 targetUid = sourceRecord.launchedFromUid; 94 4552 targetPackage = sourceRecord.launchedFromPackage; 95 4553 } 96 4554 97 4555 if (userId == UserHandle.USER_NULL) { 98 4556 userId = UserHandle.getUserId(sourceRecord.app.uid); 99 4557 } 100 4558 101 4559 // TODO: Switch to user app stacks here. 102 4560 try { 103 4561 int ret = mActivityStarter.startActivityMayWait(null, targetUid, targetPackage, intent, 104 4562 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, null, 105 4563 null, null, bOptions, ignoreTargetSecurity, userId, null, null, 106 4564 "startActivityAsCaller"); 107 4565 return ret; 108 4566 } catch (SecurityException e) { 109 4567 // XXX need to figure out how to propagate to original app. 110 4568 // A SecurityException here is generally actually a fault of the original 111 4569 // calling activity (such as a fairly granting permissions), so propagate it 112 4570 // back to them. 113 4571 /* 114 4572 StringBuilder msg = new StringBuilder(); 115 4573 msg.append("While launching"); 116 4574 msg.append(intent.toString()); 117 4575 msg.append(": "); 118 4576 msg.append(e.getMessage()); 119 4577 */ 120 4578 throw e; 121 4579 } 122 4580 } 123 4581 124 4582 @Override 125 4583 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage, 126 4584 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 127 4585 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) { 128 4586 enforceNotIsolatedCaller("startActivityAndWait"); 129 4587 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 130 4588 userId, false, ALLOW_FULL_ONLY, "startActivityAndWait", null); 131 4589 WaitResult res = new WaitResult(); 132 4590 // TODO: Switch to user app stacks here. 133 4591 mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, 134 4592 null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, res, null, 135 4593 bOptions, false, userId, null, null, "startActivityAndWait"); 136 4594 return res; 137 4595 } 138 4596 139 4597 @Override 140 4598 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage, 141 4599 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 142 4600 int startFlags, Configuration config, Bundle bOptions, int userId) { 143 4601 enforceNotIsolatedCaller("startActivityWithConfig"); 144 4602 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 145 4603 userId, false, ALLOW_FULL_ONLY, "startActivityWithConfig", null); 146 4604 // TODO: Switch to user app stacks here. 147 4605 int ret = mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent, 148 4606 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, 149 4607 null, null, config, bOptions, false, userId, null, null, "startActivityWithConfig"); 150 4608 return ret; 151 4609 } 152 4610 153 4611 @Override 154 4612 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target, 155 4613 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo, 156 4614 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) 157 4615 throws TransactionTooLargeException { 158 4616 enforceNotIsolatedCaller("startActivityIntentSender"); 159 4617 // Refuse possible leaked file descriptors 160 4618 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) { 161 4619 throw new IllegalArgumentException("File descriptors passed in Intent"); 162 4620 } 163 4621 164 4622 if (!(target instanceof PendingIntentRecord)) { 165 4623 throw new IllegalArgumentException("Bad PendingIntent object"); 166 4624 } 167 4625 168 4626 PendingIntentRecord pir = (PendingIntentRecord)target; 169 4627 170 4628 synchronized (this) { 171 4629 // If this is coming from the currently resumed activity, it is 172 4630 // effectively saying that app switches are allowed at this point. 173 4631 final ActivityStack stack = getFocusedStack(); 174 4632 if (stack.mResumedActivity != null && 175 4633 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) { 176 4634 mAppSwitchesAllowedTime = 0; 177 4635 } 178 4636 } 179 4637 int ret = pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null, 180 4638 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions, null); 181 4639 return ret; 182 4640 } 183 4641 184 4642 @Override 185 4643 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid, 186 4644 Intent intent, String resolvedType, IVoiceInteractionSession session, 187 4645 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo, 188 4646 Bundle bOptions, int userId) { 189 4647 if (checkCallingPermission(Manifest.permission.BIND_VOICE_INTERACTION) 190 4648 != PackageManager.PERMISSION_GRANTED) { 191 4649 String msg = "Permission Denial: startVoiceActivity() from pid=" 192 4650 + Binder.getCallingPid() 193 4651 + ", uid=" + Binder.getCallingUid() 194 4652 + " requires " + android.Manifest.permission.BIND_VOICE_INTERACTION; 195 4653 Slog.w(TAG, msg); 196 4654 throw new SecurityException(msg); 197 4655 } 198 4656 if (session == null || interactor == null) { 199 4657 throw new NullPointerException("null session or interactor"); 200 4658 } 201 4659 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, false, 202 4660 ALLOW_FULL_ONLY, "startVoiceActivity", null); 203 4661 // TODO: Switch to user app stacks here. 204 4662 return mActivityStarter.startActivityMayWait(null, callingUid, callingPackage, intent, 205 4663 resolvedType, session, interactor, null, null, 0, startFlags, profilerInfo, null, 206 4664 null, bOptions, false, userId, null, null, "startVoiceActivity"); 207 4665 } 208 4666 209 4667 @Override 210 4668 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid, 211 4669 Intent intent, String resolvedType, Bundle bOptions, int userId) { 212 4670 if (checkCallingPermission(Manifest.permission.BIND_VOICE_INTERACTION) 213 4671 != PackageManager.PERMISSION_GRANTED) { 214 4672 final String msg = "Permission Denial: startAssistantActivity() from pid=" 215 4673 + Binder.getCallingPid() 216 4674 + ", uid=" + Binder.getCallingUid() 217 4675 + " requires " + Manifest.permission.BIND_VOICE_INTERACTION; 218 4676 Slog.w(TAG, msg); 219 4677 throw new SecurityException(msg); 220 4678 } 221 4679 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, false, 222 4680 ALLOW_FULL_ONLY, "startAssistantActivity", null); 223 4681 return mActivityStarter.startActivityMayWait(null, callingUid, callingPackage, intent, 224 4682 resolvedType, null, null, null, null, 0, 0, null, null, null, bOptions, false, 225 4683 userId, null, null, "startAssistantActivity"); 226 4684 } 227 4685
start,stop本地音频交互
1 4686 @Override 2 4687 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) 3 4688 throws RemoteException { 4 4689 Slog.i(TAG, "Activity tried to startVoiceInteraction"); 5 4690 synchronized (this) { 6 4691 ActivityRecord activity = getFocusedStack().topActivity(); 7 4692 if (ActivityRecord.forTokenLocked(callingActivity) != activity) { 8 4693 throw new SecurityException("Only focused activity can call startVoiceInteraction"); 9 4694 } 10 4695 if (mRunningVoice != null || activity.getTask().voiceSession != null 11 4696 || activity.voiceSession != null) { 12 4697 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction"); 13 4698 return; 14 4699 } 15 4700 if (activity.pendingVoiceInteractionStart) { 16 4701 Slog.w(TAG, "Pending start of voice interaction already."); 17 4702 return; 18 4703 } 19 4704 activity.pendingVoiceInteractionStart = true; 20 4705 } 21 4706 LocalServices.getService(VoiceInteractionManagerInternal.class) 22 4707 .startLocalVoiceInteraction(callingActivity, options); 23 4708 } 24 4709 25 4710 @Override 26 4711 public void stopLocalVoiceInteraction(IBinder callingActivity) throws RemoteException { 27 4712 LocalServices.getService(VoiceInteractionManagerInternal.class) 28 4713 .stopLocalVoiceInteraction(callingActivity); 29 4714 } 30 4715
语音相关
1 4716 @Override 2 4717 public boolean supportsLocalVoiceInteraction() throws RemoteException { 3 4718 return LocalServices.getService(VoiceInteractionManagerInternal.class) 4 4719 .supportsLocalVoiceInteraction(); 5 4720 } 6 4721 7 4722 void onLocalVoiceInteractionStartedLocked(IBinder activity, 8 4723 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) { 9 4724 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity); 10 4725 if (activityToCallback == null) return; 11 4726 activityToCallback.setVoiceSessionLocked(voiceSession); 12 4727 13 4728 // Inform the activity 14 4729 try { 15 4730 activityToCallback.app.thread.scheduleLocalVoiceInteractionStarted(activity, 16 4731 voiceInteractor); 17 4732 long token = Binder.clearCallingIdentity(); 18 4733 try { 19 4734 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid); 20 4735 } finally { 21 4736 Binder.restoreCallingIdentity(token); 22 4737 } 23 4738 // TODO: VI Should we cache the activity so that it's easier to find later 24 4739 // rather than scan through all the stacks and activities? 25 4740 } catch (RemoteException re) { 26 4741 activityToCallback.clearVoiceSessionLocked(); 27 4742 // TODO: VI Should this terminate the voice session? 28 4743 } 29 4744 } 30 4745 31 4746 @Override 32 4747 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) { 33 4748 synchronized (this) { 34 4749 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) { 35 4750 if (keepAwake) { 36 4751 mVoiceWakeLock.acquire(); 37 4752 } else { 38 4753 mVoiceWakeLock.release(); 39 4754 } 40 4755 } 41 4756 } 42 4757 }
start activity相关
1 4759 @Override 2 4760 public boolean startNextMatchingActivity(IBinder callingActivity, 3 4761 Intent intent, Bundle bOptions) { 4 4762 // Refuse possible leaked file descriptors 5 4763 if (intent != null && intent.hasFileDescriptors() == true) { 6 4764 throw new IllegalArgumentException("File descriptors passed in Intent"); 7 4765 } 8 4766 ActivityOptions options = ActivityOptions.fromBundle(bOptions); 9 4767 10 4768 synchronized (this) { 11 4769 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity); 12 4770 if (r == null) { 13 4771 ActivityOptions.abort(options); 14 4772 return false; 15 4773 } 16 4774 if (r.app == null || r.app.thread == null) { 17 4775 // The caller is not running... d'oh! 18 4776 ActivityOptions.abort(options); 19 4777 return false; 20 4778 } 21 4779 intent = new Intent(intent); 22 4780 // The caller is not allowed to change the data. 23 4781 intent.setDataAndType(r.intent.getData(), r.intent.getType()); 24 4782 // And we are resetting to find the next component... 25 4783 intent.setComponent(null); 26 4784 27 4785 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 28 4786 29 4787 ActivityInfo aInfo = null; 30 4788 try { 31 4789 List<ResolveInfo> resolves = 32 4790 AppGlobals.getPackageManager().queryIntentActivities( 33 4791 intent, r.resolvedType, 34 4792 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS, 35 4793 UserHandle.getCallingUserId()).getList(); 36 4794 37 4795 // Look for the original activity in the list... 38 4796 final int N = resolves != null ? resolves.size() : 0; 39 4797 for (int i=0; i<N; i++) { 40 4798 ResolveInfo rInfo = resolves.get(i); 41 4799 if (rInfo.activityInfo.packageName.equals(r.packageName) 42 4800 && rInfo.activityInfo.name.equals(r.info.name)) { 43 4801 // We found the current one... the next matching is 44 4802 // after it. 45 4803 i++; 46 4804 if (i<N) { 47 4805 aInfo = resolves.get(i).activityInfo; 48 4806 } 49 4807 if (debug) { 50 4808 Slog.v(TAG, "Next matching activity: found current " + r.packageName 51 4809 + "/" + r.info.name); 52 4810 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null) 53 4811 ? "null" : aInfo.packageName + "/" + aInfo.name)); 54 4812 } 55 4813 break; 56 4814 } 57 4815 } 58 4816 } catch (RemoteException e) { 59 4817 } 60 4818 61 4819 if (aInfo == null) { 62 4820 // Nobody who is next! 63 4821 ActivityOptions.abort(options); 64 4822 if (debug) Slog.d(TAG, "Next matching activity: nothing found"); 65 4823 return false; 66 4824 } 67 4825 68 4826 intent.setComponent(new ComponentName( 69 4827 aInfo.applicationInfo.packageName, aInfo.name)); 70 4828 intent.setFlags(intent.getFlags()&~( 71 4829 Intent.FLAG_ACTIVITY_FORWARD_RESULT| 72 4830 Intent.FLAG_ACTIVITY_CLEAR_TOP| 73 4831 Intent.FLAG_ACTIVITY_MULTIPLE_TASK| 74 4832 Intent.FLAG_ACTIVITY_NEW_TASK)); 75 4833 76 4834 // Okay now we need to start the new activity, replacing the 77 4835 // currently running activity. This is a little tricky because 78 4836 // we want to start the new one as if the current one is finished, 79 4837 // but not finish the current one first so that there is no flicker. 80 4838 // And thus... 81 4839 final boolean wasFinishing = r.finishing; 82 4840 r.finishing = true; 83 4841 84 4842 // Propagate reply information over to the new activity. 85 4843 final ActivityRecord resultTo = r.resultTo; 86 4844 final String resultWho = r.resultWho; 87 4845 final int requestCode = r.requestCode; 88 4846 r.resultTo = null; 89 4847 if (resultTo != null) { 90 4848 resultTo.removeResultsLocked(r, resultWho, requestCode); 91 4849 } 92 4850 93 4851 final long origId = Binder.clearCallingIdentity(); 94 4852 int res = mActivityStarter.startActivityLocked(r.app.thread, intent, 95 4853 null /*ephemeralIntent*/, r.resolvedType, aInfo, null /*rInfo*/, null, 96 4854 null, resultTo != null ? resultTo.appToken : null, resultWho, requestCode, -1, 97 4855 r.launchedFromUid, r.launchedFromPackage, -1, r.launchedFromUid, 0, options, 98 4856 false, false, null, null, null, "startNextMatchingActivity"); 99 4857 Binder.restoreCallingIdentity(origId); 100 4858 101 4859 r.finishing = wasFinishing; 102 4860 if (res != ActivityManager.START_SUCCESS) { 103 4861 return false; 104 4862 } 105 4863 return true; 106 4864 } 107 4865 } 108 4866 109 4867 @Override 110 4868 public final int startActivityFromRecents(int taskId, Bundle bOptions) { 111 4869 if (checkCallingPermission(START_TASKS_FROM_RECENTS) != PackageManager.PERMISSION_GRANTED) { 112 4870 String msg = "Permission Denial: startActivityFromRecents called without " + 113 4871 START_TASKS_FROM_RECENTS; 114 4872 Slog.w(TAG, msg); 115 4873 throw new SecurityException(msg); 116 4874 } 117 4875 final long origId = Binder.clearCallingIdentity(); 118 4876 try { 119 4877 synchronized (this) { 120 4878 return mStackSupervisor.startActivityFromRecentsInner(taskId, bOptions); 121 4879 } 122 4880 } finally { 123 4881 Binder.restoreCallingIdentity(origId); 124 4882 } 125 4883 } 126 4884 127 4885 final int startActivityInPackage(int uid, String callingPackage, 128 4886 Intent intent, String resolvedType, IBinder resultTo, 129 4887 String resultWho, int requestCode, int startFlags, Bundle bOptions, int userId, 130 4888 IActivityContainer container, TaskRecord inTask, String reason) { 131 4889 132 4890 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 133 4891 userId, false, ALLOW_FULL_ONLY, "startActivityInPackage", null); 134 4892 135 4893 // TODO: Switch to user app stacks here. 136 4894 int ret = mActivityStarter.startActivityMayWait(null, uid, callingPackage, intent, 137 4895 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, 138 4896 null, null, null, bOptions, false, userId, container, inTask, reason); 139 4897 return ret; 140 4898 } 141 4899 142 4900 @Override 143 4901 public final int startActivities(IApplicationThread caller, String callingPackage, 144 4902 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions, 145 4903 int userId) { 146 4904 final String reason = "startActivities"; 147 4905 enforceNotIsolatedCaller(reason); 148 4906 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 149 4907 userId, false, ALLOW_FULL_ONLY, reason, null); 150 4908 // TODO: Switch to user app stacks here. 151 4909 int ret = mActivityStarter.startActivities(caller, -1, callingPackage, intents, 152 4910 resolvedTypes, resultTo, bOptions, userId, reason); 153 4911 return ret; 154 4912 } 155 4913 156 4914 final int startActivitiesInPackage(int uid, String callingPackage, 157 4915 Intent[] intents, String[] resolvedTypes, IBinder resultTo, 158 4916 Bundle bOptions, int userId) { 159 4917 160 4918 final String reason = "startActivityInPackage"; 161 4919 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 162 4920 userId, false, ALLOW_FULL_ONLY, reason, null); 163 4921 // TODO: Switch to user app stacks here. 164 4922 int ret = mActivityStarter.startActivities(null, uid, callingPackage, intents, resolvedTypes, 165 4923 resultTo, bOptions, userId, reason); 166 4924 return ret; 167 4925 }
报告activity完全被绘制
1 4927 @Override 2 4928 public void reportActivityFullyDrawn(IBinder token) { 3 4929 synchronized (this) { 4 4930 ActivityRecord r = ActivityRecord.isInStackLocked(token); 5 4931 if (r == null) { 6 4932 return; 7 4933 } 8 4934 r.reportFullyDrawnLocked(); 9 4935 } 10 4936 }
设置、获取请求的方向
1 4938 @Override 2 4939 public void setRequestedOrientation(IBinder token, int requestedOrientation) { 3 4940 synchronized (this) { 4 4941 ActivityRecord r = ActivityRecord.isInStackLocked(token); 5 4942 if (r == null) { 6 4943 return; 7 4944 } 8 4945 final long origId = Binder.clearCallingIdentity(); 9 4946 try { 10 4947 r.setRequestedOrientation(requestedOrientation); 11 4948 } finally { 12 4949 Binder.restoreCallingIdentity(origId); 13 4950 } 14 4951 } 15 4952 } 16 4953 17 4954 @Override 18 4955 public int getRequestedOrientation(IBinder token) { 19 4956 synchronized (this) { 20 4957 ActivityRecord r = ActivityRecord.isInStackLocked(token); 21 4958 if (r == null) { 22 4959 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; 23 4960 } 24 4961 return r.getRequestedOrientation(); 25 4962 } 26 4963 }
请求activity重新启动
1 4965 @Override 2 4966 public final void requestActivityRelaunch(IBinder token) { 3 4967 synchronized(this) { 4 4968 ActivityRecord r = ActivityRecord.isInStackLocked(token); 5 4969 if (r == null) { 6 4970 return; 7 4971 } 8 4972 final long origId = Binder.clearCallingIdentity(); 9 4973 try { 10 4974 r.forceNewConfig = true; 11 4975 r.ensureActivityConfigurationLocked(0 /* globalChanges */, 12 4976 true /* preserveWindow */); 13 4977 } finally { 14 4978 Binder.restoreCallingIdentity(origId); 15 4979 } 16 4980 } 17 4981 }
结束activity
1 4983 /** 2 4984 * This is the internal entry point for handling Activity.finish(). 3 4985 * 4 4986 * @param token The Binder token referencing the Activity we want to finish. 5 4987 * @param resultCode Result code, if any, from this Activity. 6 4988 * @param resultData Result data (Intent), if any, from this Activity. 7 4989 * @param finishTask Whether to finish the task associated with this Activity. 8 4990 * 9 4991 * @return Returns true if the activity successfully finished, or false if it is still running. 10 4992 */ 11 4993 @Override 12 4994 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData, 13 4995 int finishTask) { 14 4996 // Refuse possible leaked file descriptors 15 4997 if (resultData != null && resultData.hasFileDescriptors() == true) { 16 4998 throw new IllegalArgumentException("File descriptors passed in Intent"); 17 4999 } 18 5000 19 5001 synchronized(this) { 20 5002 ActivityRecord r = ActivityRecord.isInStackLocked(token); 21 5003 if (r == null) { 22 5004 return true; 23 5005 } 24 5006 // Keep track of the root activity of the task before we finish it 25 5007 TaskRecord tr = r.getTask(); 26 5008 ActivityRecord rootR = tr.getRootActivity(); 27 5009 if (rootR == null) { 28 5010 Slog.w(TAG, "Finishing task with all activities already finished"); 29 5011 } 30 5012 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can 31 5013 // finish. 32 5014 if (tr.mLockTaskAuth != LOCK_TASK_AUTH_LAUNCHABLE_PRIV && rootR == r && 33 5015 mStackSupervisor.isLastLockedTask(tr)) { 34 5016 Slog.i(TAG, "Not finishing task in lock task mode"); 35 5017 mStackSupervisor.showLockTaskToast(); 36 5018 return false; 37 5019 } 38 5020 if (mController != null) { 39 5021 // Find the first activity that is not finishing. 40 5022 ActivityRecord next = r.getStack().topRunningActivityLocked(token, 0); 41 5023 if (next != null) { 42 5024 // ask watcher if this is allowed 43 5025 boolean resumeOK = true; 44 5026 try { 45 5027 resumeOK = mController.activityResuming(next.packageName); 46 5028 } catch (RemoteException e) { 47 5029 mController = null; 48 5030 Watchdog.getInstance().setActivityController(null); 49 5031 } 50 5032 51 5033 if (!resumeOK) { 52 5034 Slog.i(TAG, "Not finishing activity because controller resumed"); 53 5035 return false; 54 5036 } 55 5037 } 56 5038 } 57 5039 final long origId = Binder.clearCallingIdentity(); 58 5040 try { 59 5041 boolean res; 60 5042 final boolean finishWithRootActivity = 61 5043 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY; 62 5044 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY 63 5045 || (finishWithRootActivity && r == rootR)) { 64 5046 // If requested, remove the task that is associated to this activity only if it 65 5047 // was the root activity in the task. The result code and data is ignored 66 5048 // because we don't support returning them across task boundaries. Also, to 67 5049 // keep backwards compatibility we remove the task from recents when finishing 68 5050 // task with root activity. 69 5051 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false, finishWithRootActivity); 70 5052 if (!res) { 71 5053 Slog.i(TAG, "Removing task failed to finish activity"); 72 5054 } 73 5055 } else { 74 5056 res = tr.getStack().requestFinishActivityLocked(token, resultCode, 75 5057 resultData, "app-request", true); 76 5058 if (!res) { 77 5059 Slog.i(TAG, "Failed to finish by app-request"); 78 5060 } 79 5061 } 80 5062 return res; 81 5063 } finally { 82 5064 Binder.restoreCallingIdentity(origId); 83 5065 } 84 5066 } 85 5067 }
结束高权重程序
1 5069 @Override 2 5070 public final void finishHeavyWeightApp() { 3 5071 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 4 5072 != PackageManager.PERMISSION_GRANTED) { 5 5073 String msg = "Permission Denial: finishHeavyWeightApp() from pid=" 6 5074 + Binder.getCallingPid() 7 5075 + ", uid=" + Binder.getCallingUid() 8 5076 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 9 5077 Slog.w(TAG, msg); 10 5078 throw new SecurityException(msg); 11 5079 } 12 5080 13 5081 synchronized(this) { 14 5082 if (mHeavyWeightProcess == null) { 15 5083 return; 16 5084 } 17 5085 18 5086 ArrayList<ActivityRecord> activities = new ArrayList<>(mHeavyWeightProcess.activities); 19 5087 for (int i = 0; i < activities.size(); i++) { 20 5088 ActivityRecord r = activities.get(i); 21 5089 if (!r.finishing && r.isInStackLocked()) { 22 5090 r.getStack().finishActivityLocked(r, Activity.RESULT_CANCELED, 23 5091 null, "finish-heavy", true); 24 5092 } 25 5093 } 26 5094 27 5095 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 28 5096 mHeavyWeightProcess.userId, 0)); 29 5097 mHeavyWeightProcess = null; 30 5098 } 31 5099 }
崩溃应用程序
1 5101 @Override 2 5102 public void crashApplication(int uid, int initialPid, String packageName, int userId, 3 5103 String message) { 4 5104 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 5 5105 != PackageManager.PERMISSION_GRANTED) { 6 5106 String msg = "Permission Denial: crashApplication() from pid=" 7 5107 + Binder.getCallingPid() 8 5108 + ", uid=" + Binder.getCallingUid() 9 5109 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 10 5110 Slog.w(TAG, msg); 11 5111 throw new SecurityException(msg); 12 5112 } 13 5113 14 5114 synchronized(this) { 15 5115 mAppErrors.scheduleAppCrashLocked(uid, initialPid, packageName, userId, message); 16 5116 } 17 5117 }
结束、释放Activity、task
1 5119 @Override 2 5120 public final void finishSubActivity(IBinder token, String resultWho, 3 5121 int requestCode) { 4 5122 synchronized(this) { 5 5123 final long origId = Binder.clearCallingIdentity(); 6 5124 ActivityRecord r = ActivityRecord.isInStackLocked(token); 7 5125 if (r != null) { 8 5126 r.getStack().finishSubActivityLocked(r, resultWho, requestCode); 9 5127 } 10 5128 Binder.restoreCallingIdentity(origId); 11 5129 } 12 5130 } 13 5131 14 5132 @Override 15 5133 public boolean finishActivityAffinity(IBinder token) { 16 5134 synchronized(this) { 17 5135 final long origId = Binder.clearCallingIdentity(); 18 5136 try { 19 5137 ActivityRecord r = ActivityRecord.isInStackLocked(token); 20 5138 if (r == null) { 21 5139 return false; 22 5140 } 23 5141 24 5142 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps 25 5143 // can finish. 26 5144 final TaskRecord task = r.getTask(); 27 5145 if (task.mLockTaskAuth != LOCK_TASK_AUTH_LAUNCHABLE_PRIV && 28 5146 mStackSupervisor.isLastLockedTask(task) && task.getRootActivity() == r) { 29 5147 mStackSupervisor.showLockTaskToast(); 30 5148 return false; 31 5149 } 32 5150 return task.getStack().finishActivityAffinityLocked(r); 33 5151 } finally { 34 5152 Binder.restoreCallingIdentity(origId); 35 5153 } 36 5154 } 37 5155 } 38 5156 39 5157 @Override 40 5158 public void finishVoiceTask(IVoiceInteractionSession session) { 41 5159 synchronized (this) { 42 5160 final long origId = Binder.clearCallingIdentity(); 43 5161 try { 44 5162 // TODO: VI Consider treating local voice interactions and voice tasks 45 5163 // differently here 46 5164 mStackSupervisor.finishVoiceTask(session); 47 5165 } finally { 48 5166 Binder.restoreCallingIdentity(origId); 49 5167 } 50 5168 } 51 5169 52 5170 } 53 5171 54 5172 @Override 55 5173 public boolean releaseActivityInstance(IBinder token) { 56 5174 synchronized(this) { 57 5175 final long origId = Binder.clearCallingIdentity(); 58 5176 try { 59 5177 ActivityRecord r = ActivityRecord.isInStackLocked(token); 60 5178 if (r == null) { 61 5179 return false; 62 5180 } 63 5181 return r.getStack().safelyDestroyActivityLocked(r, "app-req"); 64 5182 } finally { 65 5183 Binder.restoreCallingIdentity(origId); 66 5184 } 67 5185 } 68 5186 } 69 5187 70 5188 @Override 71 5189 public void releaseSomeActivities(IApplicationThread appInt) { 72 5190 synchronized(this) { 73 5191 final long origId = Binder.clearCallingIdentity(); 74 5192 try { 75 5193 ProcessRecord app = getRecordForAppLocked(appInt); 76 5194 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem"); 77 5195 } finally { 78 5196 Binder.restoreCallingIdentity(origId); 79 5197 } 80 5198 } 81 5199 }
是否Activity可见
1 5201 @Override 2 5202 public boolean willActivityBeVisible(IBinder token) { 3 5203 synchronized(this) { 4 5204 ActivityStack stack = ActivityRecord.getStackLocked(token); 5 5205 if (stack != null) { 6 5206 return stack.willActivityBeVisibleLocked(token); 7 5207 } 8 5208 return false; 9 5209 } 10 5210 }
覆盖延迟的窗口过渡
1 5212 @Override 2 5213 public void overridePendingTransition(IBinder token, String packageName, 3 5214 int enterAnim, int exitAnim) { 4 5215 synchronized(this) { 5 5216 ActivityRecord self = ActivityRecord.isInStackLocked(token); 6 5217 if (self == null) { 7 5218 return; 8 5219 } 9 5220 10 5221 final long origId = Binder.clearCallingIdentity(); 11 5222 12 5223 if (self.state == ActivityState.RESUMED 13 5224 || self.state == ActivityState.PAUSING) { 14 5225 mWindowManager.overridePendingAppTransition(packageName, 15 5226 enterAnim, exitAnim, null); 16 5227 } 17 5228 18 5229 Binder.restoreCallingIdentity(origId); 19 5230 } 20 5231 }
处理app死亡
1 5233 /** 2 5234 * Main function for removing an existing process from the activity manager 3 5235 * as a result of that process going away. Clears out all connections 4 5236 * to the process. 5 5237 */ 6 5238 private final void handleAppDiedLocked(ProcessRecord app, 7 5239 boolean restarting, boolean allowRestart) { 8 5240 int pid = app.pid; 9 5241 boolean kept = cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1, 10 5242 false /*replacingPid*/); 11 5243 if (!kept && !restarting) { 12 5244 removeLruProcessLocked(app); 13 5245 if (pid > 0) { 14 5246 ProcessList.remove(pid); 15 5247 } 16 5248 } 17 5249 18 5250 if (mProfileProc == app) { 19 5251 clearProfilerLocked(); 20 5252 } 21 5253 22 5254 // Remove this application's activities from active lists. 23 5255 boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(app); 24 5256 25 5257 app.activities.clear(); 26 5258 27 5259 if (app.instr != null) { 28 5260 Slog.w(TAG, "Crash of app " + app.processName 29 5261 + " running instrumentation " + app.instr.mClass); 30 5262 Bundle info = new Bundle(); 31 5263 info.putString("shortMsg", "Process crashed."); 32 5264 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 33 5265 } 34 5266 35 5267 mWindowManager.deferSurfaceLayout(); 36 5268 try { 37 5269 if (!restarting && hasVisibleActivities 38 5270 && !mStackSupervisor.resumeFocusedStackTopActivityLocked()) { 39 5271 // If there was nothing to resume, and we are not already restarting this process, but 40 5272 // there is a visible activity that is hosted by the process... then make sure all 41 5273 // visible activities are running, taking care of restarting this process. 42 5274 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS); 43 5275 } 44 5276 } finally { 45 5277 mWindowManager.continueSurfaceLayout(); 46 5278 } 47 5279 }
获取app lru record和record
1 5281 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) { 2 5282 final IBinder threadBinder = thread.asBinder(); 3 5283 // Find the application record. 4 5284 for (int i=mLruProcesses.size()-1; i>=0; i--) { 5 5285 final ProcessRecord rec = mLruProcesses.get(i); 6 5286 if (rec.thread != null && rec.thread.asBinder() == threadBinder) { 7 5287 return i; 8 5288 } 9 5289 } 10 5290 return -1; 11 5291 } 12 5292 13 5293 final ProcessRecord getRecordForAppLocked( 14 5294 IApplicationThread thread) { 15 5295 if (thread == null) { 16 5296 return null; 17 5297 } 18 5298 19 5299 int appIndex = getLRURecordIndexForAppLocked(thread); 20 5300 if (appIndex >= 0) { 21 5301 return mLruProcesses.get(appIndex); 22 5302 } 23 5303 24 5304 // Validation: if it isn't in the LRU list, it shouldn't exist, but let's 25 5305 // double-check that. 26 5306 final IBinder threadBinder = thread.asBinder(); 27 5307 final ArrayMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap(); 28 5308 for (int i = pmap.size()-1; i >= 0; i--) { 29 5309 final SparseArray<ProcessRecord> procs = pmap.valueAt(i); 30 5310 for (int j = procs.size()-1; j >= 0; j--) { 31 5311 final ProcessRecord proc = procs.valueAt(j); 32 5312 if (proc.thread != null && proc.thread.asBinder() == threadBinder) { 33 5313 Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: " 34 5314 + proc); 35 5315 return proc; 36 5316 } 37 5317 } 38 5318 } 39 5319 40 5320 return null; 41 5321 }
做低内存report
1 5323 final void doLowMemReportIfNeededLocked(ProcessRecord dyingProc) { 2 5324 // If there are no longer any background processes running, 3 5325 // and the app that died was not running instrumentation, 4 5326 // then tell everyone we are now low on memory. 5 5327 boolean haveBg = false; 6 5328 for (int i=mLruProcesses.size()-1; i>=0; i--) { 7 5329 ProcessRecord rec = mLruProcesses.get(i); 8 5330 if (rec.thread != null 9 5331 && rec.setProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 10 5332 haveBg = true; 11 5333 break; 12 5334 } 13 5335 } 14 5336 15 5337 if (!haveBg) { 16 5338 boolean doReport = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 17 5339 if (doReport) { 18 5340 long now = SystemClock.uptimeMillis(); 19 5341 if (now < (mLastMemUsageReportTime+5*60*1000)) { 20 5342 doReport = false; 21 5343 } else { 22 5344 mLastMemUsageReportTime = now; 23 5345 } 24 5346 } 25 5347 final ArrayList<ProcessMemInfo> memInfos 26 5348 = doReport ? new ArrayList<ProcessMemInfo>(mLruProcesses.size()) : null; 27 5349 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size()); 28 5350 long now = SystemClock.uptimeMillis(); 29 5351 for (int i=mLruProcesses.size()-1; i>=0; i--) { 30 5352 ProcessRecord rec = mLruProcesses.get(i); 31 5353 if (rec == dyingProc || rec.thread == null) { 32 5354 continue; 33 5355 } 34 5356 if (doReport) { 35 5357 memInfos.add(new ProcessMemInfo(rec.processName, rec.pid, rec.setAdj, 36 5358 rec.setProcState, rec.adjType, rec.makeAdjReason())); 37 5359 } 38 5360 if ((rec.lastLowMemory+mConstants.GC_MIN_INTERVAL) <= now) { 39 5361 // The low memory report is overriding any current 40 5362 // state for a GC request. Make sure to do 41 5363 // heavy/important/visible/foreground processes first. 42 5364 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) { 43 5365 rec.lastRequestedGc = 0; 44 5366 } else { 45 5367 rec.lastRequestedGc = rec.lastLowMemory; 46 5368 } 47 5369 rec.reportLowMemory = true; 48 5370 rec.lastLowMemory = now; 49 5371 mProcessesToGc.remove(rec); 50 5372 addProcessToGcListLocked(rec); 51 5373 } 52 5374 } 53 5375 if (doReport) { 54 5376 Message msg = mHandler.obtainMessage(REPORT_MEM_USAGE_MSG, memInfos); 55 5377 mHandler.sendMessage(msg); 56 5378 } 57 5379 scheduleAppGcsLocked(); 58 5380 } 59 5381 }
app死亡处理
1 5383 final void appDiedLocked(ProcessRecord app) { 2 5384 appDiedLocked(app, app.pid, app.thread, false); 3 5385 } 4 5386 5 5387 final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, 6 5388 boolean fromBinderDied) { 7 5389 // First check if this ProcessRecord is actually active for the pid. 8 5390 synchronized (mPidsSelfLocked) { 9 5391 ProcessRecord curProc = mPidsSelfLocked.get(pid); 10 5392 if (curProc != app) { 11 5393 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc); 12 5394 return; 13 5395 } 14 5396 } 15 5397 16 5398 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 17 5399 synchronized (stats) { 18 5400 stats.noteProcessDiedLocked(app.info.uid, pid); 19 5401 } 20 5402 21 5403 if (!app.killed) { 22 5404 if (!fromBinderDied) { 23 5405 killProcessQuiet(pid); 24 5406 } 25 5407 killProcessGroup(app.uid, pid); 26 5408 app.killed = true; 27 5409 } 28 5410 29 5411 // Clean up already done if the process has been re-started. 30 5412 if (app.pid == pid && app.thread != null && 31 5413 app.thread.asBinder() == thread.asBinder()) { 32 5414 boolean doLowMem = app.instr == null; 33 5415 boolean doOomAdj = doLowMem; 34 5416 if (!app.killedByAm) { 35 5417 Slog.i(TAG, "Process " + app.processName + " (pid " + pid + ") has died: " 36 5418 + ProcessList.makeOomAdjString(app.setAdj) 37 5419 + ProcessList.makeProcStateString(app.setProcState)); 38 5420 mAllowLowerMemLevel = true; 39 5421 } else { 40 5422 // Note that we always want to do oom adj to update our state with the 41 5423 // new number of procs. 42 5424 mAllowLowerMemLevel = false; 43 5425 doLowMem = false; 44 5426 } 45 5427 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName, 46 5428 app.setAdj, app.setProcState); 47 5429 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 48 5430 "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder()); 49 5431 handleAppDiedLocked(app, false, true); 50 5432 51 5433 if (doOomAdj) { 52 5434 updateOomAdjLocked(); 53 5435 } 54 5436 if (doLowMem) { 55 5437 doLowMemReportIfNeededLocked(app); 56 5438 } 57 5439 } else if (app.pid != pid) { 58 5440 // A new process has already been started. 59 5441 Slog.i(TAG, "Process " + app.processName + " (pid " + pid 60 5442 + ") has died and restarted (pid " + app.pid + ")."); 61 5443 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName); 62 5444 } else if (DEBUG_PROCESSES) { 63 5445 Slog.d(TAG_PROCESSES, "Received spurious death notification for thread " 64 5446 + thread.asBinder()); 65 5447 } 66 5448 }
dump state
1 5450 /** 2 5451 * If a stack trace dump file is configured, dump process stack traces. 3 5452 * @param clearTraces causes the dump file to be erased prior to the new 4 5453 * traces being written, if true; when false, the new traces will be 5 5454 * appended to any existing file content. 6 5455 * @param firstPids of dalvik VM processes to dump stack traces for first 7 5456 * @param lastPids of dalvik VM processes to dump stack traces for last 8 5457 * @param nativePids optional list of native pids to dump stack crawls 9 5458 * @return file containing stack traces, or null if no dump file is configured 10 5459 */ 11 5460 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids, 12 5461 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, 13 5462 ArrayList<Integer> nativePids) { 14 5463 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null); 15 5464 if (tracesPath == null || tracesPath.length() == 0) { 16 5465 return null; 17 5466 } 18 5467 19 5468 File tracesFile = new File(tracesPath); 20 5469 try { 21 5470 if (clearTraces && tracesFile.exists()) tracesFile.delete(); 22 5471 tracesFile.createNewFile(); 23 5472 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw- 24 5473 } catch (IOException e) { 25 5474 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e); 26 5475 return null; 27 5476 } 28 5477 29 5478 dumpStackTraces(tracesPath, firstPids, processCpuTracker, lastPids, nativePids); 30 5479 return tracesFile; 31 5480 } 32 5481 33 5482 public static class DumpStackFileObserver extends FileObserver { 34 5483 // Keep in sync with frameworks/native/cmds/dumpstate/utils.cpp 35 5484 private static final int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds 36 5485 static final int NATIVE_DUMP_TIMEOUT_MS = 2000; // 2 seconds; 37 5486 38 5487 private final String mTracesPath; 39 5488 private boolean mClosed; 40 5489 41 5490 public DumpStackFileObserver(String tracesPath) { 42 5491 super(tracesPath, FileObserver.CLOSE_WRITE); 43 5492 mTracesPath = tracesPath; 44 5493 } 45 5494 46 5495 @Override 47 5496 public synchronized void onEvent(int event, String path) { 48 5497 mClosed = true; 49 5498 notify(); 50 5499 } 51 5500 52 5501 public long dumpWithTimeout(int pid, long timeout) { 53 5502 sendSignal(pid, SIGNAL_QUIT); 54 5503 final long start = SystemClock.elapsedRealtime(); 55 5504 56 5505 final long waitTime = Math.min(timeout, TRACE_DUMP_TIMEOUT_MS); 57 5506 synchronized (this) { 58 5507 try { 59 5508 wait(waitTime); // Wait for traces file to be closed. 60 5509 } catch (InterruptedException e) { 61 5510 Slog.wtf(TAG, e); 62 5511 } 63 5512 } 64 5513 65 5514 // This avoids a corner case of passing a negative time to the native 66 5515 // trace in case we've already hit the overall timeout. 67 5516 final long timeWaited = SystemClock.elapsedRealtime() - start; 68 5517 if (timeWaited >= timeout) { 69 5518 return timeWaited; 70 5519 } 71 5520 72 5521 if (!mClosed) { 73 5522 Slog.w(TAG, "Didn't see close of " + mTracesPath + " for pid " + pid + 74 5523 ". Attempting native stack collection."); 75 5524 76 5525 final long nativeDumpTimeoutMs = Math.min( 77 5526 NATIVE_DUMP_TIMEOUT_MS, timeout - timeWaited); 78 5527 79 5528 Debug.dumpNativeBacktraceToFileTimeout(pid, mTracesPath, 80 5529 (int) (nativeDumpTimeoutMs / 1000)); 81 5530 } 82 5531 83 5532 final long end = SystemClock.elapsedRealtime(); 84 5533 mClosed = false; 85 5534 86 5535 return (end - start); 87 5536 } 88 5537 } 89 5538 90 5539 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids, 91 5540 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, 92 5541 ArrayList<Integer> nativePids) { 93 5542 // Use a FileObserver to detect when traces finish writing. 94 5543 // The order of traces is considered important to maintain for legibility. 95 5544 DumpStackFileObserver observer = new DumpStackFileObserver(tracesPath); 96 5545 97 5546 // We must complete all stack dumps within 20 seconds. 98 5547 long remainingTime = 20 * 1000; 99 5548 try { 100 5549 observer.startWatching(); 101 5550 102 5551 // First collect all of the stacks of the most important pids. 103 5552 if (firstPids != null) { 104 5553 int num = firstPids.size(); 105 5554 for (int i = 0; i < num; i++) { 106 5555 if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for pid " 107 5556 + firstPids.get(i)); 108 5557 final long timeTaken = observer.dumpWithTimeout(firstPids.get(i), remainingTime); 109 5558 110 5559 remainingTime -= timeTaken; 111 5560 if (remainingTime <= 0) { 112 5561 Slog.e(TAG, "Aborting stack trace dump (current firstPid=" + firstPids.get(i) + 113 5562 "); deadline exceeded."); 114 5563 return; 115 5564 } 116 5565 117 5566 if (DEBUG_ANR) { 118 5567 Slog.d(TAG, "Done with pid " + firstPids.get(i) + " in " + timeTaken + "ms"); 119 5568 } 120 5569 } 121 5570 } 122 5571 123 5572 // Next collect the stacks of the native pids 124 5573 if (nativePids != null) { 125 5574 for (int pid : nativePids) { 126 5575 if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for native pid " + pid); 127 5576 final long nativeDumpTimeoutMs = Math.min( 128 5577 DumpStackFileObserver.NATIVE_DUMP_TIMEOUT_MS, remainingTime); 129 5578 130 5579 final long start = SystemClock.elapsedRealtime(); 131 5580 Debug.dumpNativeBacktraceToFileTimeout( 132 5581 pid, tracesPath, (int) (nativeDumpTimeoutMs / 1000)); 133 5582 final long timeTaken = SystemClock.elapsedRealtime() - start; 134 5583 135 5584 remainingTime -= timeTaken; 136 5585 if (remainingTime <= 0) { 137 5586 Slog.e(TAG, "Aborting stack trace dump (current native pid=" + pid + 138 5587 "); deadline exceeded."); 139 5588 return; 140 5589 } 141 5590 142 5591 if (DEBUG_ANR) { 143 5592 Slog.d(TAG, "Done with native pid " + pid + " in " + timeTaken + "ms"); 144 5593 } 145 5594 } 146 5595 } 147 5596 148 5597 // Lastly, measure CPU usage. 149 5598 if (processCpuTracker != null) { 150 5599 processCpuTracker.init(); 151 5600 System.gc(); 152 5601 processCpuTracker.update(); 153 5602 try { 154 5603 synchronized (processCpuTracker) { 155 5604 processCpuTracker.wait(500); // measure over 1/2 second. 156 5605 } 157 5606 } catch (InterruptedException e) { 158 5607 } 159 5608 processCpuTracker.update(); 160 5609 161 5610 // We'll take the stack crawls of just the top apps using CPU. 162 5611 final int N = processCpuTracker.countWorkingStats(); 163 5612 int numProcs = 0; 164 5613 for (int i=0; i<N && numProcs<5; i++) { 165 5614 ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i); 166 5615 if (lastPids.indexOfKey(stats.pid) >= 0) { 167 5616 numProcs++; 168 5617 169 5618 if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for extra pid " + stats.pid); 170 5619 171 5620 final long timeTaken = observer.dumpWithTimeout(stats.pid, remainingTime); 172 5621 remainingTime -= timeTaken; 173 5622 if (remainingTime <= 0) { 174 5623 Slog.e(TAG, "Aborting stack trace dump (current extra pid=" + stats.pid + 175 5624 "); deadline exceeded."); 176 5625 return; 177 5626 } 178 5627 179 5628 if (DEBUG_ANR) { 180 5629 Slog.d(TAG, "Done with extra pid " + stats.pid + " in " + timeTaken + "ms"); 181 5630 } 182 5631 } else if (DEBUG_ANR) { 183 5632 Slog.d(TAG, "Skipping next CPU consuming process, not a java proc: " 184 5633 + stats.pid); 185 5634 } 186 5635 } 187 5636 } 188 5637 } finally { 189 5638 observer.stopWatching(); 190 5639 } 191 5640 }
记录app太慢
1 5642 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) { 2 5643 if (true || IS_USER_BUILD) { 3 5644 return; 4 5645 } 5 5646 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null); 6 5647 if (tracesPath == null || tracesPath.length() == 0) { 7 5648 return; 8 5649 } 9 5650 10 5651 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); 11 5652 StrictMode.allowThreadDiskWrites(); 12 5653 try { 13 5654 final File tracesFile = new File(tracesPath); 14 5655 final File tracesDir = tracesFile.getParentFile(); 15 5656 final File tracesTmp = new File(tracesDir, "__tmp__"); 16 5657 try { 17 5658 if (tracesFile.exists()) { 18 5659 tracesTmp.delete(); 19 5660 tracesFile.renameTo(tracesTmp); 20 5661 } 21 5662 StringBuilder sb = new StringBuilder(); 22 5663 Time tobj = new Time(); 23 5664 tobj.set(System.currentTimeMillis()); 24 5665 sb.append(tobj.format("%Y-%m-%d %H:%M:%S")); 25 5666 sb.append(": "); 26 5667 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb); 27 5668 sb.append(" since "); 28 5669 sb.append(msg); 29 5670 FileOutputStream fos = new FileOutputStream(tracesFile); 30 5671 fos.write(sb.toString().getBytes()); 31 5672 if (app == null) { 32 5673 fos.write("\n*** No application process!".getBytes()); 33 5674 } 34 5675 fos.close(); 35 5676 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw- 36 5677 } catch (IOException e) { 37 5678 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e); 38 5679 return; 39 5680 } 40 5681 41 5682 if (app != null) { 42 5683 ArrayList<Integer> firstPids = new ArrayList<Integer>(); 43 5684 firstPids.add(app.pid); 44 5685 dumpStackTraces(tracesPath, firstPids, null, null, null); 45 5686 } 46 5687 47 5688 File lastTracesFile = null; 48 5689 File curTracesFile = null; 49 5690 for (int i=9; i>=0; i--) { 50 5691 String name = String.format(Locale.US, "slow%02d.txt", i); 51 5692 curTracesFile = new File(tracesDir, name); 52 5693 if (curTracesFile.exists()) { 53 5694 if (lastTracesFile != null) { 54 5695 curTracesFile.renameTo(lastTracesFile); 55 5696 } else { 56 5697 curTracesFile.delete(); 57 5698 } 58 5699 } 59 5700 lastTracesFile = curTracesFile; 60 5701 } 61 5702 tracesFile.renameTo(curTracesFile); 62 5703 if (tracesTmp.exists()) { 63 5704 tracesTmp.renameTo(tracesFile); 64 5705 } 65 5706 } finally { 66 5707 StrictMode.setThreadPolicy(oldPolicy); 67 5708 } 68 5709 }
显示启动警告
1 5711 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) { 2 5712 if (!mLaunchWarningShown) { 3 5713 mLaunchWarningShown = true; 4 5714 mUiHandler.post(new Runnable() { 5 5715 @Override 6 5716 public void run() { 7 5717 synchronized (ActivityManagerService.this) { 8 5718 final Dialog d = new LaunchWarningWindow(mContext, cur, next); 9 5719 d.show(); 10 5720 mUiHandler.postDelayed(new Runnable() { 11 5721 @Override 12 5722 public void run() { 13 5723 synchronized (ActivityManagerService.this) { 14 5724 d.dismiss(); 15 5725 mLaunchWarningShown = false; 16 5726 } 17 5727 } 18 5728 }, 4000); 19 5729 } 20 5730 } 21 5731 }); 22 5732 } 23 5733 }
清除app用户数据
1 5735 @Override 2 5736 public boolean clearApplicationUserData(final String packageName, 3 5737 final IPackageDataObserver observer, int userId) { 4 5738 enforceNotIsolatedCaller("clearApplicationUserData"); 5 5739 int uid = Binder.getCallingUid(); 6 5740 int pid = Binder.getCallingPid(); 7 5741 userId = mUserController.handleIncomingUser(pid, uid, userId, false, 8 5742 ALLOW_FULL_ONLY, "clearApplicationUserData", null); 9 5743 10 5744 11 5745 long callingId = Binder.clearCallingIdentity(); 12 5746 try { 13 5747 IPackageManager pm = AppGlobals.getPackageManager(); 14 5748 int pkgUid = -1; 15 5749 synchronized(this) { 16 5750 if (getPackageManagerInternalLocked().isPackageDataProtected( 17 5751 userId, packageName)) { 18 5752 throw new SecurityException( 19 5753 "Cannot clear data for a protected package: " + packageName); 20 5754 } 21 5755 22 5756 try { 23 5757 pkgUid = pm.getPackageUid(packageName, MATCH_UNINSTALLED_PACKAGES, userId); 24 5758 } catch (RemoteException e) { 25 5759 } 26 5760 if (pkgUid == -1) { 27 5761 Slog.w(TAG, "Invalid packageName: " + packageName); 28 5762 if (observer != null) { 29 5763 try { 30 5764 observer.onRemoveCompleted(packageName, false); 31 5765 } catch (RemoteException e) { 32 5766 Slog.i(TAG, "Observer no longer exists."); 33 5767 } 34 5768 } 35 5769 return false; 36 5770 } 37 5771 if (uid == pkgUid || checkComponentPermission( 38 5772 android.Manifest.permission.CLEAR_APP_USER_DATA, 39 5773 pid, uid, -1, true) 40 5774 == PackageManager.PERMISSION_GRANTED) { 41 5775 forceStopPackageLocked(packageName, pkgUid, "clear data"); 42 5776 } else { 43 5777 throw new SecurityException("PID " + pid + " does not have permission " 44 5778 + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data" 45 5779 + " of package " + packageName); 46 5780 } 47 5781 48 5782 // Remove all tasks match the cleared application package and user 49 5783 for (int i = mRecentTasks.size() - 1; i >= 0; i--) { 50 5784 final TaskRecord tr = mRecentTasks.get(i); 51 5785 final String taskPackageName = 52 5786 tr.getBaseIntent().getComponent().getPackageName(); 53 5787 if (tr.userId != userId) continue; 54 5788 if (!taskPackageName.equals(packageName)) continue; 55 5789 mStackSupervisor.removeTaskByIdLocked(tr.taskId, false, REMOVE_FROM_RECENTS); 56 5790 } 57 5791 } 58 5792 59 5793 final int pkgUidF = pkgUid; 60 5794 final int userIdF = userId; 61 5795 final IPackageDataObserver localObserver = new IPackageDataObserver.Stub() { 62 5796 @Override 63 5797 public void onRemoveCompleted(String packageName, boolean succeeded) 64 5798 throws RemoteException { 65 5799 synchronized (ActivityManagerService.this) { 66 5800 finishForceStopPackageLocked(packageName, pkgUidF); 67 5801 } 68 5802 69 5803 final Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED, 70 5804 Uri.fromParts("package", packageName, null)); 71 5805 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 72 5806 intent.putExtra(Intent.EXTRA_UID, pkgUidF); 73 5807 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(pkgUidF)); 74 5808 broadcastIntentInPackage("android", SYSTEM_UID, intent, 75 5809 null, null, 0, null, null, null, null, false, false, userIdF); 76 5810 77 5811 if (observer != null) { 78 5812 observer.onRemoveCompleted(packageName, succeeded); 79 5813 } 80 5814 } 81 5815 }; 82 5816 83 5817 try { 84 5818 // Clear application user data 85 5819 pm.clearApplicationUserData(packageName, localObserver, userId); 86 5820 87 5821 synchronized(this) { 88 5822 // Remove all permissions granted from/to this package 89 5823 removeUriPermissionsForPackageLocked(packageName, userId, true); 90 5824 } 91 5825 92 5826 // Reset notification settings. 93 5827 INotificationManager inm = NotificationManager.getService(); 94 5828 inm.clearData(packageName, pkgUidF, uid == pkgUidF); 95 5829 } catch (RemoteException e) { 96 5830 } 97 5831 } finally { 98 5832 Binder.restoreCallingIdentity(callingId); 99 5833 } 100 5834 return true; 101 5835 } 102 5836
后台杀掉app
1 5837 @Override 2 5838 public void killBackgroundProcesses(final String packageName, int userId) { 3 5839 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 4 5840 != PackageManager.PERMISSION_GRANTED && 5 5841 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES) 6 5842 != PackageManager.PERMISSION_GRANTED) { 7 5843 String msg = "Permission Denial: killBackgroundProcesses() from pid=" 8 5844 + Binder.getCallingPid() 9 5845 + ", uid=" + Binder.getCallingUid() 10 5846 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 11 5847 Slog.w(TAG, msg); 12 5848 throw new SecurityException(msg); 13 5849 } 14 5850 15 5851 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 16 5852 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null); 17 5853 long callingId = Binder.clearCallingIdentity(); 18 5854 try { 19 5855 IPackageManager pm = AppGlobals.getPackageManager(); 20 5856 synchronized(this) { 21 5857 int appId = -1; 22 5858 try { 23 5859 appId = UserHandle.getAppId( 24 5860 pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId)); 25 5861 } catch (RemoteException e) { 26 5862 } 27 5863 if (appId == -1) { 28 5864 Slog.w(TAG, "Invalid packageName: " + packageName); 29 5865 return; 30 5866 } 31 5867 killPackageProcessesLocked(packageName, appId, userId, 32 5868 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background"); 33 5869 } 34 5870 } finally { 35 5871 Binder.restoreCallingIdentity(callingId); 36 5872 } 37 5873 } 38 5874 39 5875 @Override 40 5876 public void killAllBackgroundProcesses() { 41 5877 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 42 5878 != PackageManager.PERMISSION_GRANTED) { 43 5879 final String msg = "Permission Denial: killAllBackgroundProcesses() from pid=" 44 5880 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 45 5881 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 46 5882 Slog.w(TAG, msg); 47 5883 throw new SecurityException(msg); 48 5884 } 49 5885 50 5886 final long callingId = Binder.clearCallingIdentity(); 51 5887 try { 52 5888 synchronized (this) { 53 5889 final ArrayList<ProcessRecord> procs = new ArrayList<>(); 54 5890 final int NP = mProcessNames.getMap().size(); 55 5891 for (int ip = 0; ip < NP; ip++) { 56 5892 final SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 57 5893 final int NA = apps.size(); 58 5894 for (int ia = 0; ia < NA; ia++) { 59 5895 final ProcessRecord app = apps.valueAt(ia); 60 5896 if (app.persistent) { 61 5897 // We don't kill persistent processes. 62 5898 continue; 63 5899 } 64 5900 if (app.removed) { 65 5901 procs.add(app); 66 5902 } else if (app.setAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 67 5903 app.removed = true; 68 5904 procs.add(app); 69 5905 } 70 5906 } 71 5907 } 72 5908 73 5909 final int N = procs.size(); 74 5910 for (int i = 0; i < N; i++) { 75 5911 removeProcessLocked(procs.get(i), false, true, "kill all background"); 76 5912 } 77 5913 78 5914 mAllowLowerMemLevel = true; 79 5915 80 5916 updateOomAdjLocked(); 81 5917 doLowMemReportIfNeededLocked(null); 82 5918 } 83 5919 } finally { 84 5920 Binder.restoreCallingIdentity(callingId); 85 5921 } 86 5922 } 87 5923 88 5924 /** 89 5925 * Kills all background processes, except those matching any of the 90 5926 * specified properties. 91 5927 * 92 5928 * @param minTargetSdk the target SDK version at or above which to preserve 93 5929 * processes, or {@code -1} to ignore the target SDK 94 5930 * @param maxProcState the process state at or below which to preserve 95 5931 * processes, or {@code -1} to ignore the process state 96 5932 */ 97 5933 private void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) { 98 5934 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 99 5935 != PackageManager.PERMISSION_GRANTED) { 100 5936 final String msg = "Permission Denial: killAllBackgroundProcessesExcept() from pid=" 101 5937 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 102 5938 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 103 5939 Slog.w(TAG, msg); 104 5940 throw new SecurityException(msg); 105 5941 } 106 5942 107 5943 final long callingId = Binder.clearCallingIdentity(); 108 5944 try { 109 5945 synchronized (this) { 110 5946 final ArrayList<ProcessRecord> procs = new ArrayList<>(); 111 5947 final int NP = mProcessNames.getMap().size(); 112 5948 for (int ip = 0; ip < NP; ip++) { 113 5949 final SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 114 5950 final int NA = apps.size(); 115 5951 for (int ia = 0; ia < NA; ia++) { 116 5952 final ProcessRecord app = apps.valueAt(ia); 117 5953 if (app.removed) { 118 5954 procs.add(app); 119 5955 } else if ((minTargetSdk < 0 || app.info.targetSdkVersion < minTargetSdk) 120 5956 && (maxProcState < 0 || app.setProcState > maxProcState)) { 121 5957 app.removed = true; 122 5958 procs.add(app); 123 5959 } 124 5960 } 125 5961 } 126 5962 127 5963 final int N = procs.size(); 128 5964 for (int i = 0; i < N; i++) { 129 5965 removeProcessLocked(procs.get(i), false, true, "kill all background except"); 130 5966 } 131 5967 } 132 5968 } finally { 133 5969 Binder.restoreCallingIdentity(callingId); 134 5970 } 135 5971 }
强制停止app
1 5973 @Override 2 5974 public void forceStopPackage(final String packageName, int userId) { 3 5975 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 4 5976 != PackageManager.PERMISSION_GRANTED) { 5 5977 String msg = "Permission Denial: forceStopPackage() from pid=" 6 5978 + Binder.getCallingPid() 7 5979 + ", uid=" + Binder.getCallingUid() 8 5980 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 9 5981 Slog.w(TAG, msg); 10 5982 throw new SecurityException(msg); 11 5983 } 12 5984 final int callingPid = Binder.getCallingPid(); 13 5985 userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(), 14 5986 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null); 15 5987 long callingId = Binder.clearCallingIdentity(); 16 5988 try { 17 5989 IPackageManager pm = AppGlobals.getPackageManager(); 18 5990 synchronized(this) { 19 5991 int[] users = userId == UserHandle.USER_ALL 20 5992 ? mUserController.getUsers() : new int[] { userId }; 21 5993 for (int user : users) { 22 5994 int pkgUid = -1; 23 5995 try { 24 5996 pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 25 5997 user); 26 5998 } catch (RemoteException e) { 27 5999 } 28 6000 if (pkgUid == -1) { 29 6001 Slog.w(TAG, "Invalid packageName: " + packageName); 30 6002 continue; 31 6003 } 32 6004 try { 33 6005 pm.setPackageStoppedState(packageName, true, user); 34 6006 } catch (RemoteException e) { 35 6007 } catch (IllegalArgumentException e) { 36 6008 Slog.w(TAG, "Failed trying to unstop package " 37 6009 + packageName + ": " + e); 38 6010 } 39 6011 if (mUserController.isUserRunningLocked(user, 0)) { 40 6012 forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid); 41 6013 finishForceStopPackageLocked(packageName, pkgUid); 42 6014 } 43 6015 } 44 6016 } 45 6017 } finally { 46 6018 Binder.restoreCallingIdentity(callingId); 47 6019 } 48 6020 }
添加package依赖
1 6023 public void addPackageDependency(String packageName) { 2 6024 synchronized (this) { 3 6025 int callingPid = Binder.getCallingPid(); 4 6026 if (callingPid == myPid()) { 5 6027 // Yeah, um, no. 6 6028 return; 7 6029 } 8 6030 ProcessRecord proc; 9 6031 synchronized (mPidsSelfLocked) { 10 6032 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 11 6033 } 12 6034 if (proc != null) { 13 6035 if (proc.pkgDeps == null) { 14 6036 proc.pkgDeps = new ArraySet<String>(1); 15 6037 } 16 6038 proc.pkgDeps.add(packageName); 17 6039 } 18 6040 } 19 6041 }
kill app
1 6043 /* 2 6044 * The pkg name and app id have to be specified. 3 6045 */ 4 6046 @Override 5 6047 public void killApplication(String pkg, int appId, int userId, String reason) { 6 6048 if (pkg == null) { 7 6049 return; 8 6050 } 9 6051 // Make sure the uid is valid. 10 6052 if (appId < 0) { 11 6053 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg); 12 6054 return; 13 6055 } 14 6056 int callerUid = Binder.getCallingUid(); 15 6057 // Only the system server can kill an application 16 6058 if (UserHandle.getAppId(callerUid) == SYSTEM_UID) { 17 6059 // Post an aysnc message to kill the application 18 6060 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG); 19 6061 msg.arg1 = appId; 20 6062 msg.arg2 = userId; 21 6063 Bundle bundle = new Bundle(); 22 6064 bundle.putString("pkg", pkg); 23 6065 bundle.putString("reason", reason); 24 6066 msg.obj = bundle; 25 6067 mHandler.sendMessage(msg); 26 6068 } else { 27 6069 throw new SecurityException(callerUid + " cannot kill pkg: " + 28 6070 pkg); 29 6071 } 30 6072 }
关闭系统对话框
1 6074 @Override 2 6075 public void closeSystemDialogs(String reason) { 3 6076 enforceNotIsolatedCaller("closeSystemDialogs"); 4 6077 5 6078 final int pid = Binder.getCallingPid(); 6 6079 final int uid = Binder.getCallingUid(); 7 6080 final long origId = Binder.clearCallingIdentity(); 8 6081 try { 9 6082 synchronized (this) { 10 6083 // Only allow this from foreground processes, so that background 11 6084 // applications can't abuse it to prevent system UI from being shown. 12 6085 if (uid >= FIRST_APPLICATION_UID) { 13 6086 ProcessRecord proc; 14 6087 synchronized (mPidsSelfLocked) { 15 6088 proc = mPidsSelfLocked.get(pid); 16 6089 } 17 6090 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) { 18 6091 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason 19 6092 + " from background process " + proc); 20 6093 return; 21 6094 } 22 6095 } 23 6096 closeSystemDialogsLocked(reason); 24 6097 } 25 6098 } finally { 26 6099 Binder.restoreCallingIdentity(origId); 27 6100 } 28 6101 } 29 6102 30 6103 void closeSystemDialogsLocked(String reason) { 31 6104 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 32 6105 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 33 6106 | Intent.FLAG_RECEIVER_FOREGROUND); 34 6107 if (reason != null) { 35 6108 intent.putExtra("reason", reason); 36 6109 } 37 6110 mWindowManager.closeSystemDialogs(reason); 38 6111 39 6112 mStackSupervisor.closeSystemDialogsLocked(); 40 6113 41 6114 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null, 42 6115 AppOpsManager.OP_NONE, null, false, false, 43 6116 -1, SYSTEM_UID, UserHandle.USER_ALL); 44 6117 }
获取进程内存信息,获取进程
1 6119 @Override 2 6120 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) { 3 6121 enforceNotIsolatedCaller("getProcessMemoryInfo"); 4 6122 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length]; 5 6123 for (int i=pids.length-1; i>=0; i--) { 6 6124 ProcessRecord proc; 7 6125 int oomAdj; 8 6126 synchronized (this) { 9 6127 synchronized (mPidsSelfLocked) { 10 6128 proc = mPidsSelfLocked.get(pids[i]); 11 6129 oomAdj = proc != null ? proc.setAdj : 0; 12 6130 } 13 6131 } 14 6132 infos[i] = new Debug.MemoryInfo(); 15 6133 Debug.getMemoryInfo(pids[i], infos[i]); 16 6134 if (proc != null) { 17 6135 synchronized (this) { 18 6136 if (proc.thread != null && proc.setAdj == oomAdj) { 19 6137 // Record this for posterity if the process has been stable. 20 6138 proc.baseProcessTracker.addPss(infos[i].getTotalPss(), 21 6139 infos[i].getTotalUss(), false, proc.pkgList); 22 6140 } 23 6141 } 24 6142 } 25 6143 } 26 6144 return infos; 27 6145 } 28 6146 29 6147 @Override 30 6148 public long[] getProcessPss(int[] pids) { 31 6149 enforceNotIsolatedCaller("getProcessPss"); 32 6150 long[] pss = new long[pids.length]; 33 6151 for (int i=pids.length-1; i>=0; i--) { 34 6152 ProcessRecord proc; 35 6153 int oomAdj; 36 6154 synchronized (this) { 37 6155 synchronized (mPidsSelfLocked) { 38 6156 proc = mPidsSelfLocked.get(pids[i]); 39 6157 oomAdj = proc != null ? proc.setAdj : 0; 40 6158 } 41 6159 } 42 6160 long[] tmpUss = new long[1]; 43 6161 pss[i] = Debug.getPss(pids[i], tmpUss, null); 44 6162 if (proc != null) { 45 6163 synchronized (this) { 46 6164 if (proc.thread != null && proc.setAdj == oomAdj) { 47 6165 // Record this for posterity if the process has been stable. 48 6166 proc.baseProcessTracker.addPss(pss[i], tmpUss[0], false, proc.pkgList); 49 6167 } 50 6168 } 51 6169 } 52 6170 } 53 6171 return pss; 54 6172 }
kill程序进程
1 6174 @Override 2 6175 public void killApplicationProcess(String processName, int uid) { 3 6176 if (processName == null) { 4 6177 return; 5 6178 } 6 6179 7 6180 int callerUid = Binder.getCallingUid(); 8 6181 // Only the system server can kill an application 9 6182 if (callerUid == SYSTEM_UID) { 10 6183 synchronized (this) { 11 6184 ProcessRecord app = getProcessRecordLocked(processName, uid, true); 12 6185 if (app != null && app.thread != null) { 13 6186 try { 14 6187 app.thread.scheduleSuicide(); 15 6188 } catch (RemoteException e) { 16 6189 // If the other end already died, then our work here is done. 17 6190 } 18 6191 } else { 19 6192 Slog.w(TAG, "Process/uid not found attempting kill of " 20 6193 + processName + " / " + uid); 21 6194 } 22 6195 } 23 6196 } else { 24 6197 throw new SecurityException(callerUid + " cannot kill app process: " + 25 6198 processName); 26 6199 } 27 6200 }
forece stop package
1 6202 private void forceStopPackageLocked(final String packageName, int uid, String reason) { 2 6203 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false, 3 6204 false, true, false, false, UserHandle.getUserId(uid), reason); 4 6205 }
完成force stop
1 6207 private void finishForceStopPackageLocked(final String packageName, int uid) { 2 6208 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED, 3 6209 Uri.fromParts("package", packageName, null)); 4 6210 if (!mProcessesReady) { 5 6211 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 6 6212 | Intent.FLAG_RECEIVER_FOREGROUND); 7 6213 } 8 6214 intent.putExtra(Intent.EXTRA_UID, uid); 9 6215 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid)); 10 6216 broadcastIntentLocked(null, null, intent, 11 6217 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 12 6218 null, false, false, MY_PID, SYSTEM_UID, UserHandle.getUserId(uid)); 13 6219 }
杀掉package进程
1 6222 private final boolean killPackageProcessesLocked(String packageName, int appId, 2 6223 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart, 3 6224 boolean doit, boolean evenPersistent, String reason) { 4 6225 ArrayList<ProcessRecord> procs = new ArrayList<>(); 5 6226 6 6227 // Remove all processes this package may have touched: all with the 7 6228 // same UID (except for the system or root user), and all whose name 8 6229 // matches the package name. 9 6230 final int NP = mProcessNames.getMap().size(); 10 6231 for (int ip=0; ip<NP; ip++) { 11 6232 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 12 6233 final int NA = apps.size(); 13 6234 for (int ia=0; ia<NA; ia++) { 14 6235 ProcessRecord app = apps.valueAt(ia); 15 6236 if (app.persistent && !evenPersistent) { 16 6237 // we don't kill persistent processes 17 6238 continue; 18 6239 } 19 6240 if (app.removed) { 20 6241 if (doit) { 21 6242 procs.add(app); 22 6243 } 23 6244 continue; 24 6245 } 25 6246 26 6247 // Skip process if it doesn't meet our oom adj requirement. 27 6248 if (app.setAdj < minOomAdj) { 28 6249 continue; 29 6250 } 30 6251 31 6252 // If no package is specified, we call all processes under the 32 6253 // give user id. 33 6254 if (packageName == null) { 34 6255 if (userId != UserHandle.USER_ALL && app.userId != userId) { 35 6256 continue; 36 6257 } 37 6258 if (appId >= 0 && UserHandle.getAppId(app.uid) != appId) { 38 6259 continue; 39 6260 } 40 6261 // Package has been specified, we want to hit all processes 41 6262 // that match it. We need to qualify this by the processes 42 6263 // that are running under the specified app and user ID. 43 6264 } else { 44 6265 final boolean isDep = app.pkgDeps != null 45 6266 && app.pkgDeps.contains(packageName); 46 6267 if (!isDep && UserHandle.getAppId(app.uid) != appId) { 47 6268 continue; 48 6269 } 49 6270 if (userId != UserHandle.USER_ALL && app.userId != userId) { 50 6271 continue; 51 6272 } 52 6273 if (!app.pkgList.containsKey(packageName) && !isDep) { 53 6274 continue; 54 6275 } 55 6276 } 56 6277 57 6278 // Process has passed all conditions, kill it! 58 6279 if (!doit) { 59 6280 return true; 60 6281 } 61 6282 app.removed = true; 62 6283 procs.add(app); 63 6284 } 64 6285 } 65 6286 66 6287 int N = procs.size(); 67 6288 for (int i=0; i<N; i++) { 68 6289 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason); 69 6290 } 70 6291 updateOomAdjLocked(); 71 6292 return N > 0; 72 6293 }
清除disabled的包组件
1 6295 private void cleanupDisabledPackageComponentsLocked( 2 6296 String packageName, int userId, boolean killProcess, String[] changedClasses) { 3 6297 4 6298 Set<String> disabledClasses = null; 5 6299 boolean packageDisabled = false; 6 6300 IPackageManager pm = AppGlobals.getPackageManager(); 7 6301 8 6302 if (changedClasses == null) { 9 6303 // Nothing changed... 10 6304 return; 11 6305 } 12 6306 13 6307 // Determine enable/disable state of the package and its components. 14 6308 int enabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 15 6309 for (int i = changedClasses.length - 1; i >= 0; i--) { 16 6310 final String changedClass = changedClasses[i]; 17 6311 18 6312 if (changedClass.equals(packageName)) { 19 6313 try { 20 6314 // Entire package setting changed 21 6315 enabled = pm.getApplicationEnabledSetting(packageName, 22 6316 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM); 23 6317 } catch (Exception e) { 24 6318 // No such package/component; probably racing with uninstall. In any 25 6319 // event it means we have nothing further to do here. 26 6320 return; 27 6321 } 28 6322 packageDisabled = enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED 29 6323 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 30 6324 if (packageDisabled) { 31 6325 // Entire package is disabled. 32 6326 // No need to continue to check component states. 33 6327 disabledClasses = null; 34 6328 break; 35 6329 } 36 6330 } else { 37 6331 try { 38 6332 enabled = pm.getComponentEnabledSetting( 39 6333 new ComponentName(packageName, changedClass), 40 6334 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM); 41 6335 } catch (Exception e) { 42 6336 // As above, probably racing with uninstall. 43 6337 return; 44 6338 } 45 6339 if (enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED 46 6340 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) { 47 6341 if (disabledClasses == null) { 48 6342 disabledClasses = new ArraySet<>(changedClasses.length); 49 6343 } 50 6344 disabledClasses.add(changedClass); 51 6345 } 52 6346 } 53 6347 } 54 6348 55 6349 if (!packageDisabled && disabledClasses == null) { 56 6350 // Nothing to do here... 57 6351 return; 58 6352 } 59 6353 60 6354 // Clean-up disabled activities. 61 6355 if (mStackSupervisor.finishDisabledPackageActivitiesLocked( 62 6356 packageName, disabledClasses, true, false, userId) && mBooted) { 63 6357 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 64 6358 mStackSupervisor.scheduleIdleLocked(); 65 6359 } 66 6360 67 6361 // Clean-up disabled tasks 68 6362 cleanupDisabledPackageTasksLocked(packageName, disabledClasses, userId); 69 6363 70 6364 // Clean-up disabled services. 71 6365 mServices.bringDownDisabledPackageServicesLocked( 72 6366 packageName, disabledClasses, userId, false, killProcess, true); 73 6367 74 6368 // Clean-up disabled providers. 75 6369 ArrayList<ContentProviderRecord> providers = new ArrayList<>(); 76 6370 mProviderMap.collectPackageProvidersLocked( 77 6371 packageName, disabledClasses, true, false, userId, providers); 78 6372 for (int i = providers.size() - 1; i >= 0; i--) { 79 6373 removeDyingProviderLocked(null, providers.get(i), true); 80 6374 } 81 6375 82 6376 // Clean-up disabled broadcast receivers. 83 6377 for (int i = mBroadcastQueues.length - 1; i >= 0; i--) { 84 6378 mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked( 85 6379 packageName, disabledClasses, userId, true); 86 6380 } 87 6381 88 6382 }
为用户清除广播队列
1 6384 final boolean clearBroadcastQueueForUserLocked(int userId) { 2 6385 boolean didSomething = false; 3 6386 for (int i = mBroadcastQueues.length - 1; i >= 0; i--) { 4 6387 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked( 5 6388 null, null, userId, true); 6 6389 } 7 6390 return didSomething; 8 6391 }
forcestop package
1 6393 final boolean forceStopPackageLocked(String packageName, int appId, 2 6394 boolean callerWillRestart, boolean purgeCache, boolean doit, 3 6395 boolean evenPersistent, boolean uninstalling, int userId, String reason) { 4 6396 int i; 5 6397 6 6398 if (userId == UserHandle.USER_ALL && packageName == null) { 7 6399 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!"); 8 6400 } 9 6401 10 6402 if (appId < 0 && packageName != null) { 11 6403 try { 12 6404 appId = UserHandle.getAppId(AppGlobals.getPackageManager() 13 6405 .getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 0)); 14 6406 } catch (RemoteException e) { 15 6407 } 16 6408 } 17 6409 18 6410 if (doit) { 19 6411 if (packageName != null) { 20 6412 Slog.i(TAG, "Force stopping " + packageName + " appid=" + appId 21 6413 + " user=" + userId + ": " + reason); 22 6414 } else { 23 6415 Slog.i(TAG, "Force stopping u" + userId + ": " + reason); 24 6416 } 25 6417 26 6418 mAppErrors.resetProcessCrashTimeLocked(packageName == null, appId, userId); 27 6419 } 28 6420 29 6421 boolean didSomething = killPackageProcessesLocked(packageName, appId, userId, 30 6422 ProcessList.INVALID_ADJ, callerWillRestart, true, doit, evenPersistent, 31 6423 packageName == null ? ("stop user " + userId) : ("stop " + packageName)); 32 6424 33 6425 didSomething |= mActivityStarter.clearPendingActivityLaunchesLocked(packageName); 34 6426 35 6427 if (mStackSupervisor.finishDisabledPackageActivitiesLocked( 36 6428 packageName, null, doit, evenPersistent, userId)) { 37 6429 if (!doit) { 38 6430 return true; 39 6431 } 40 6432 didSomething = true; 41 6433 } 42 6434 43 6435 if (mServices.bringDownDisabledPackageServicesLocked( 44 6436 packageName, null, userId, evenPersistent, true, doit)) { 45 6437 if (!doit) { 46 6438 return true; 47 6439 } 48 6440 didSomething = true; 49 6441 } 50 6442 51 6443 if (packageName == null) { 52 6444 // Remove all sticky broadcasts from this user. 53 6445 mStickyBroadcasts.remove(userId); 54 6446 } 55 6447 56 6448 ArrayList<ContentProviderRecord> providers = new ArrayList<>(); 57 6449 if (mProviderMap.collectPackageProvidersLocked(packageName, null, doit, evenPersistent, 58 6450 userId, providers)) { 59 6451 if (!doit) { 60 6452 return true; 61 6453 } 62 6454 didSomething = true; 63 6455 } 64 6456 for (i = providers.size() - 1; i >= 0; i--) { 65 6457 removeDyingProviderLocked(null, providers.get(i), true); 66 6458 } 67 6459 68 6460 // Remove transient permissions granted from/to this package/user 69 6461 removeUriPermissionsForPackageLocked(packageName, userId, false); 70 6462 71 6463 if (doit) { 72 6464 for (i = mBroadcastQueues.length - 1; i >= 0; i--) { 73 6465 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked( 74 6466 packageName, null, userId, doit); 75 6467 } 76 6468 } 77 6469 78 6470 if (packageName == null || uninstalling) { 79 6471 // Remove pending intents. For now we only do this when force 80 6472 // stopping users, because we have some problems when doing this 81 6473 // for packages -- app widgets are not currently cleaned up for 82 6474 // such packages, so they can be left with bad pending intents. 83 6475 if (mIntentSenderRecords.size() > 0) { 84 6476 Iterator<WeakReference<PendingIntentRecord>> it 85 6477 = mIntentSenderRecords.values().iterator(); 86 6478 while (it.hasNext()) { 87 6479 WeakReference<PendingIntentRecord> wpir = it.next(); 88 6480 if (wpir == null) { 89 6481 it.remove(); 90 6482 continue; 91 6483 } 92 6484 PendingIntentRecord pir = wpir.get(); 93 6485 if (pir == null) { 94 6486 it.remove(); 95 6487 continue; 96 6488 } 97 6489 if (packageName == null) { 98 6490 // Stopping user, remove all objects for the user. 99 6491 if (pir.key.userId != userId) { 100 6492 // Not the same user, skip it. 101 6493 continue; 102 6494 } 103 6495 } else { 104 6496 if (UserHandle.getAppId(pir.uid) != appId) { 105 6497 // Different app id, skip it. 106 6498 continue; 107 6499 } 108 6500 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) { 109 6501 // Different user, skip it. 110 6502 continue; 111 6503 } 112 6504 if (!pir.key.packageName.equals(packageName)) { 113 6505 // Different package, skip it. 114 6506 continue; 115 6507 } 116 6508 } 117 6509 if (!doit) { 118 6510 return true; 119 6511 } 120 6512 didSomething = true; 121 6513 it.remove(); 122 6514 makeIntentSenderCanceledLocked(pir); 123 6515 if (pir.key.activity != null && pir.key.activity.pendingResults != null) { 124 6516 pir.key.activity.pendingResults.remove(pir.ref); 125 6517 } 126 6518 } 127 6519 } 128 6520 } 129 6521 130 6522 if (doit) { 131 6523 if (purgeCache && packageName != null) { 132 6524 AttributeCache ac = AttributeCache.instance(); 133 6525 if (ac != null) { 134 6526 ac.removePackage(packageName); 135 6527 } 136 6528 } 137 6529 if (mBooted) { 138 6530 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 139 6531 mStackSupervisor.scheduleIdleLocked(); 140 6532 } 141 6533 } 142 6534 143 6535 return didSomething; 144 6536 }
移除进程name
1 6538 private final ProcessRecord removeProcessNameLocked(final String name, final int uid) { 2 6539 return removeProcessNameLocked(name, uid, null); 3 6540 } 4 6541 5 6542 private final ProcessRecord removeProcessNameLocked(final String name, final int uid, 6 6543 final ProcessRecord expecting) { 7 6544 ProcessRecord old = mProcessNames.get(name, uid); 8 6545 // Only actually remove when the currently recorded value matches the 9 6546 // record that we expected; if it doesn't match then we raced with a 10 6547 // newly created process and we don't want to destroy the new one. 11 6548 if ((expecting == null) || (old == expecting)) { 12 6549 mProcessNames.remove(name, uid); 13 6550 } 14 6551 if (old != null && old.uidRecord != null) { 15 6552 old.uidRecord.numProcs--; 16 6553 if (old.uidRecord.numProcs == 0) { 17 6554 // No more processes using this uid, tell clients it is gone. 18 6555 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 19 6556 "No more processes in " + old.uidRecord); 20 6557 enqueueUidChangeLocked(old.uidRecord, -1, UidRecord.CHANGE_GONE); 21 6558 EventLogTags.writeAmUidStopped(uid); 22 6559 mActiveUids.remove(uid); 23 6560 noteUidProcessState(uid, ActivityManager.PROCESS_STATE_NONEXISTENT); 24 6561 } 25 6562 old.uidRecord = null; 26 6563 } 27 6564 mIsolatedProcesses.remove(uid); 28 6565 return old; 29 6566 }
添加进程name
1 6568 private final void addProcessNameLocked(ProcessRecord proc) { 2 6569 // We shouldn't already have a process under this name, but just in case we 3 6570 // need to clean up whatever may be there now. 4 6571 ProcessRecord old = removeProcessNameLocked(proc.processName, proc.uid); 5 6572 if (old == proc && proc.persistent) { 6 6573 // We are re-adding a persistent process. Whatevs! Just leave it there. 7 6574 Slog.w(TAG, "Re-adding persistent process " + proc); 8 6575 } else if (old != null) { 9 6576 Slog.wtf(TAG, "Already have existing proc " + old + " when adding " + proc); 10 6577 } 11 6578 UidRecord uidRec = mActiveUids.get(proc.uid); 12 6579 if (uidRec == null) { 13 6580 uidRec = new UidRecord(proc.uid); 14 6581 // This is the first appearance of the uid, report it now! 15 6582 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 16 6583 "Creating new process uid: " + uidRec); 17 6584 if (Arrays.binarySearch(mDeviceIdleTempWhitelist, UserHandle.getAppId(proc.uid)) >= 0 18 6585 || mPendingTempWhitelist.indexOfKey(proc.uid) >= 0) { 19 6586 uidRec.setWhitelist = uidRec.curWhitelist = true; 20 6587 } 21 6588 uidRec.updateHasInternetPermission(); 22 6589 mActiveUids.put(proc.uid, uidRec); 23 6590 EventLogTags.writeAmUidRunning(uidRec.uid); 24 6591 noteUidProcessState(uidRec.uid, uidRec.curProcState); 25 6592 enqueueUidChangeLocked(uidRec, -1, UidRecord.CHANGE_ACTIVE); 26 6593 } 27 6594 proc.uidRecord = uidRec; 28 6595 29 6596 // Reset render thread tid if it was already set, so new process can set it again. 30 6597 proc.renderThreadTid = 0; 31 6598 uidRec.numProcs++; 32 6599 mProcessNames.put(proc.processName, proc.uid, proc); 33 6600 if (proc.isolated) { 34 6601 mIsolatedProcesses.put(proc.uid, proc); 35 6602 } 36 6603 } 37 6604
移除进程
1 6604 2 6605 boolean removeProcessLocked(ProcessRecord app, 3 6606 boolean callerWillRestart, boolean allowRestart, String reason) { 4 6607 final String name = app.processName; 5 6608 final int uid = app.uid; 6 6609 if (DEBUG_PROCESSES) Slog.d(TAG_PROCESSES, 7 6610 "Force removing proc " + app.toShortString() + " (" + name + "/" + uid + ")"); 8 6611 9 6612 ProcessRecord old = mProcessNames.get(name, uid); 10 6613 if (old != app) { 11 6614 // This process is no longer active, so nothing to do. 12 6615 Slog.w(TAG, "Ignoring remove of inactive process: " + app); 13 6616 return false; 14 6617 } 15 6618 removeProcessNameLocked(name, uid); 16 6619 if (mHeavyWeightProcess == app) { 17 6620 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 18 6621 mHeavyWeightProcess.userId, 0)); 19 6622 mHeavyWeightProcess = null; 20 6623 } 21 6624 boolean needRestart = false; 22 6625 if (app.pid > 0 && app.pid != MY_PID) { 23 6626 int pid = app.pid; 24 6627 synchronized (mPidsSelfLocked) { 25 6628 mPidsSelfLocked.remove(pid); 26 6629 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 27 6630 } 28 6631 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 29 6632 if (app.isolated) { 30 6633 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 31 6634 getPackageManagerInternalLocked().removeIsolatedUid(app.uid); 32 6635 } 33 6636 boolean willRestart = false; 34 6637 if (app.persistent && !app.isolated) { 35 6638 if (!callerWillRestart) { 36 6639 willRestart = true; 37 6640 } else { 38 6641 needRestart = true; 39 6642 } 40 6643 } 41 6644 app.kill(reason, true); 42 6645 handleAppDiedLocked(app, willRestart, allowRestart); 43 6646 if (willRestart) { 44 6647 removeLruProcessLocked(app); 45 6648 addAppLocked(app.info, null, false, null /* ABI override */); 46 6649 } 47 6650 } else { 48 6651 mRemovedProcesses.add(app); 49 6652 } 50 6653 51 6654 return needRestart; 52 6655 }
进程的content provider发布超时
1 6657 private final void processContentProviderPublishTimedOutLocked(ProcessRecord app) { 2 6658 cleanupAppInLaunchingProvidersLocked(app, true); 3 6659 removeProcessLocked(app, false, true, "timeout publishing content providers"); 4 6660 }
进程启动超时
1 6657 private final void processContentProviderPublishTimedOutLocked(ProcessRecord app) { 2 6658 cleanupAppInLaunchingProvidersLocked(app, true); 3 6659 removeProcessLocked(app, false, true, "timeout publishing content providers"); 4 6660 } 5 6661 6 6662 private final void processStartTimedOutLocked(ProcessRecord app) { 7 6663 final int pid = app.pid; 8 6664 boolean gone = false; 9 6665 synchronized (mPidsSelfLocked) { 10 6666 ProcessRecord knownApp = mPidsSelfLocked.get(pid); 11 6667 if (knownApp != null && knownApp.thread == null) { 12 6668 mPidsSelfLocked.remove(pid); 13 6669 gone = true; 14 6670 } 15 6671 } 16 6672 17 6673 if (gone) { 18 6674 Slog.w(TAG, "Process " + app + " failed to attach"); 19 6675 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId, 20 6676 pid, app.uid, app.processName); 21 6677 removeProcessNameLocked(app.processName, app.uid); 22 6678 if (mHeavyWeightProcess == app) { 23 6679 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 24 6680 mHeavyWeightProcess.userId, 0)); 25 6681 mHeavyWeightProcess = null; 26 6682 } 27 6683 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 28 6684 if (app.isolated) { 29 6685 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 30 6686 } 31 6687 // Take care of any launching providers waiting for this process. 32 6688 cleanupAppInLaunchingProvidersLocked(app, true); 33 6689 // Take care of any services that are waiting for the process. 34 6690 mServices.processStartTimedOutLocked(app); 35 6691 app.kill("start timeout", true); 36 6692 removeLruProcessLocked(app); 37 6693 if (mBackupTarget != null && mBackupTarget.app.pid == pid) { 38 6694 Slog.w(TAG, "Unattached app died before backup, skipping"); 39 6695 mHandler.post(new Runnable() { 40 6696 @Override 41 6697 public void run(){ 42 6698 try { 43 6699 IBackupManager bm = IBackupManager.Stub.asInterface( 44 6700 ServiceManager.getService(Context.BACKUP_SERVICE)); 45 6701 bm.agentDisconnected(app.info.packageName); 46 6702 } catch (RemoteException e) { 47 6703 // Can't happen; the backup manager is local 48 6704 } 49 6705 } 50 6706 }); 51 6707 } 52 6708 if (isPendingBroadcastProcessLocked(pid)) { 53 6709 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 54 6710 skipPendingBroadcastLocked(pid); 55 6711 } 56 6712 } else { 57 6713 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app); 58 6714 } 59 6715 }
attach application
1 6717 private final boolean attachApplicationLocked(IApplicationThread thread, 2 6718 int pid) { 3 6719 4 6720 // Find the application record that is being attached... either via 5 6721 // the pid if we are running in multiple processes, or just pull the 6 6722 // next app record if we are emulating process with anonymous threads. 7 6723 ProcessRecord app; 8 6724 long startTime = SystemClock.uptimeMillis(); 9 6725 if (pid != MY_PID && pid >= 0) { 10 6726 synchronized (mPidsSelfLocked) { 11 6727 app = mPidsSelfLocked.get(pid); 12 6728 } 13 6729 } else { 14 6730 app = null; 15 6731 } 16 6732 17 6733 if (app == null) { 18 6734 Slog.w(TAG, "No pending application record for pid " + pid 19 6735 + " (IApplicationThread " + thread + "); dropping process"); 20 6736 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid); 21 6737 if (pid > 0 && pid != MY_PID) { 22 6738 killProcessQuiet(pid); 23 6739 //TODO: killProcessGroup(app.info.uid, pid); 24 6740 } else { 25 6741 try { 26 6742 thread.scheduleExit(); 27 6743 } catch (Exception e) { 28 6744 // Ignore exceptions. 29 6745 } 30 6746 } 31 6747 return false; 32 6748 } 33 6749 34 6750 // If this application record is still attached to a previous 35 6751 // process, clean it up now. 36 6752 if (app.thread != null) { 37 6753 handleAppDiedLocked(app, true, true); 38 6754 } 39 6755 40 6756 // Tell the process all about itself. 41 6757 42 6758 if (DEBUG_ALL) Slog.v( 43 6759 TAG, "Binding process pid " + pid + " to record " + app); 44 6760 45 6761 final String processName = app.processName; 46 6762 try { 47 6763 AppDeathRecipient adr = new AppDeathRecipient( 48 6764 app, pid, thread); 49 6765 thread.asBinder().linkToDeath(adr, 0); 50 6766 app.deathRecipient = adr; 51 6767 } catch (RemoteException e) { 52 6768 app.resetPackageList(mProcessStats); 53 6769 startProcessLocked(app, "link fail", processName); 54 6770 return false; 55 6771 } 56 6772 57 6773 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName); 58 6774 59 6775 app.makeActive(thread, mProcessStats); 60 6776 app.curAdj = app.setAdj = app.verifiedAdj = ProcessList.INVALID_ADJ; 61 6777 app.curSchedGroup = app.setSchedGroup = ProcessList.SCHED_GROUP_DEFAULT; 62 6778 app.forcingToImportant = null; 63 6779 updateProcessForegroundLocked(app, false, false); 64 6780 app.hasShownUi = false; 65 6781 app.debugging = false; 66 6782 app.cached = false; 67 6783 app.killedByAm = false; 68 6784 app.killed = false; 69 6785 70 6786 71 6787 // We carefully use the same state that PackageManager uses for 72 6788 // filtering, since we use this flag to decide if we need to install 73 6789 // providers when user is unlocked later 74 6790 app.unlocked = StorageManager.isUserKeyUnlocked(app.userId); 75 6791 76 6792 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 77 6793 78 6794 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info); 79 6795 List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null; 80 6796 81 6797 if (providers != null && checkAppInLaunchingProvidersLocked(app)) { 82 6798 Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG); 83 6799 msg.obj = app; 84 6800 mHandler.sendMessageDelayed(msg, CONTENT_PROVIDER_PUBLISH_TIMEOUT); 85 6801 } 86 6802 87 6803 checkTime(startTime, "attachApplicationLocked: before bindApplication"); 88 6804 89 6805 if (!normalMode) { 90 6806 Slog.i(TAG, "Launching preboot mode app: " + app); 91 6807 } 92 6808 93 6809 if (DEBUG_ALL) Slog.v( 94 6810 TAG, "New app record " + app 95 6811 + " thread=" + thread.asBinder() + " pid=" + pid); 96 6812 try { 97 6813 int testMode = ApplicationThreadConstants.DEBUG_OFF; 98 6814 if (mDebugApp != null && mDebugApp.equals(processName)) { 99 6815 testMode = mWaitForDebugger 100 6816 ? ApplicationThreadConstants.DEBUG_WAIT 101 6817 : ApplicationThreadConstants.DEBUG_ON; 102 6818 app.debugging = true; 103 6819 if (mDebugTransient) { 104 6820 mDebugApp = mOrigDebugApp; 105 6821 mWaitForDebugger = mOrigWaitForDebugger; 106 6822 } 107 6823 } 108 6824 String profileFile = app.instr != null ? app.instr.mProfileFile : null; 109 6825 ParcelFileDescriptor profileFd = null; 110 6826 int samplingInterval = 0; 111 6827 boolean profileAutoStop = false; 112 6828 boolean profileStreamingOutput = false; 113 6829 if (mProfileApp != null && mProfileApp.equals(processName)) { 114 6830 mProfileProc = app; 115 6831 profileFile = mProfileFile; 116 6832 profileFd = mProfileFd; 117 6833 samplingInterval = mSamplingInterval; 118 6834 profileAutoStop = mAutoStopProfiler; 119 6835 profileStreamingOutput = mStreamingOutput; 120 6836 } 121 6837 boolean enableTrackAllocation = false; 122 6838 if (mTrackAllocationApp != null && mTrackAllocationApp.equals(processName)) { 123 6839 enableTrackAllocation = true; 124 6840 mTrackAllocationApp = null; 125 6841 } 126 6842 127 6843 // If the app is being launched for restore or full backup, set it up specially 128 6844 boolean isRestrictedBackupMode = false; 129 6845 if (mBackupTarget != null && mBackupAppName.equals(processName)) { 130 6846 isRestrictedBackupMode = mBackupTarget.appInfo.uid >= FIRST_APPLICATION_UID 131 6847 && ((mBackupTarget.backupMode == BackupRecord.RESTORE) 132 6848 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL) 133 6849 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL)); 134 6850 } 135 6851 136 6852 if (app.instr != null) { 137 6853 notifyPackageUse(app.instr.mClass.getPackageName(), 138 6854 PackageManager.NOTIFY_PACKAGE_USE_INSTRUMENTATION); 139 6855 } 140 6856 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Binding proc " 141 6857 + processName + " with config " + getGlobalConfiguration()); 142 6858 ApplicationInfo appInfo = app.instr != null ? app.instr.mTargetInfo : app.info; 143 6859 app.compat = compatibilityInfoForPackageLocked(appInfo); 144 6860 if (profileFd != null) { 145 6861 profileFd = profileFd.dup(); 146 6862 } 147 6863 ProfilerInfo profilerInfo = profileFile == null ? null 148 6864 : new ProfilerInfo(profileFile, profileFd, samplingInterval, profileAutoStop, 149 6865 profileStreamingOutput); 150 6866 151 6867 // We deprecated Build.SERIAL and it is not accessible to 152 6868 // apps that target the v2 security sandbox. Since access to 153 6869 // the serial is now behind a permission we push down the value. 154 6870 String buildSerial = Build.UNKNOWN; 155 6871 if (appInfo.targetSandboxVersion != 2) { 156 6872 buildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface( 157 6873 ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE)) 158 6874 .getSerial(); 159 6875 } 160 6876 161 6877 // Check if this is a secondary process that should be incorporated into some 162 6878 // currently active instrumentation. (Note we do this AFTER all of the profiling 163 6879 // stuff above because profiling can currently happen only in the primary 164 6880 // instrumentation process.) 165 6881 if (mActiveInstrumentation.size() > 0 && app.instr == null) { 166 6882 for (int i = mActiveInstrumentation.size() - 1; i >= 0 && app.instr == null; i--) { 167 6883 ActiveInstrumentation aInstr = mActiveInstrumentation.get(i); 168 6884 if (!aInstr.mFinished && aInstr.mTargetInfo.uid == app.uid) { 169 6885 if (aInstr.mTargetProcesses.length == 0) { 170 6886 // This is the wildcard mode, where every process brought up for 171 6887 // the target instrumentation should be included. 172 6888 if (aInstr.mTargetInfo.packageName.equals(app.info.packageName)) { 173 6889 app.instr = aInstr; 174 6890 aInstr.mRunningProcesses.add(app); 175 6891 } 176 6892 } else { 177 6893 for (String proc : aInstr.mTargetProcesses) { 178 6894 if (proc.equals(app.processName)) { 179 6895 app.instr = aInstr; 180 6896 aInstr.mRunningProcesses.add(app); 181 6897 break; 182 6898 } 183 6899 } 184 6900 } 185 6901 } 186 6902 } 187 6903 } 188 6904 189 6905 checkTime(startTime, "attachApplicationLocked: immediately before bindApplication"); 190 6906 mStackSupervisor.mActivityMetricsLogger.notifyBindApplication(app); 191 6907 if (app.instr != null) { 192 6908 thread.bindApplication(processName, appInfo, providers, 193 6909 app.instr.mClass, 194 6910 profilerInfo, app.instr.mArguments, 195 6911 app.instr.mWatcher, 196 6912 app.instr.mUiAutomationConnection, testMode, 197 6913 mBinderTransactionTrackingEnabled, enableTrackAllocation, 198 6914 isRestrictedBackupMode || !normalMode, app.persistent, 199 6915 new Configuration(getGlobalConfiguration()), app.compat, 200 6916 getCommonServicesLocked(app.isolated), 201 6917 mCoreSettingsObserver.getCoreSettingsLocked(), 202 6918 buildSerial); 203 6919 } else { 204 6920 thread.bindApplication(processName, appInfo, providers, null, profilerInfo, 205 6921 null, null, null, testMode, 206 6922 mBinderTransactionTrackingEnabled, enableTrackAllocation, 207 6923 isRestrictedBackupMode || !normalMode, app.persistent, 208 6924 new Configuration(getGlobalConfiguration()), app.compat, 209 6925 getCommonServicesLocked(app.isolated), 210 6926 mCoreSettingsObserver.getCoreSettingsLocked(), 211 6927 buildSerial); 212 6928 } 213 6929 214 6930 checkTime(startTime, "attachApplicationLocked: immediately after bindApplication"); 215 6931 updateLruProcessLocked(app, false, null); 216 6932 checkTime(startTime, "attachApplicationLocked: after updateLruProcessLocked"); 217 6933 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis(); 218 6934 } catch (Exception e) { 219 6935 // todo: Yikes! What should we do? For now we will try to 220 6936 // start another process, but that could easily get us in 221 6937 // an infinite loop of restarting processes... 222 6938 Slog.wtf(TAG, "Exception thrown during bind of " + app, e); 223 6939 224 6940 app.resetPackageList(mProcessStats); 225 6941 app.unlinkDeathRecipient(); 226 6942 startProcessLocked(app, "bind fail", processName); 227 6943 return false; 228 6944 } 229 6945 230 6946 // Remove this record from the list of starting applications. 231 6947 mPersistentStartingProcesses.remove(app); 232 6948 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES, 233 6949 "Attach application locked removing on hold: " + app); 234 6950 mProcessesOnHold.remove(app); 235 6951 236 6952 boolean badApp = false; 237 6953 boolean didSomething = false; 238 6954 239 6955 // See if the top visible activity is waiting to run in this process... 240 6956 if (normalMode) { 241 6957 try { 242 6958 if (mStackSupervisor.attachApplicationLocked(app)) { 243 6959 didSomething = true; 244 6960 } 245 6961 } catch (Exception e) { 246 6962 Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); 247 6963 badApp = true; 248 6964 } 249 6965 } 250 6966 251 6967 // Find any services that should be running in this process... 252 6968 if (!badApp) { 253 6969 try { 254 6970 didSomething |= mServices.attachApplicationLocked(app, processName); 255 6971 checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked"); 256 6972 } catch (Exception e) { 257 6973 Slog.wtf(TAG, "Exception thrown starting services in " + app, e); 258 6974 badApp = true; 259 6975 } 260 6976 } 261 6977 262 6978 // Check if a next-broadcast receiver is in this process... 263 6979 if (!badApp && isPendingBroadcastProcessLocked(pid)) { 264 6980 try { 265 6981 didSomething |= sendPendingBroadcastsLocked(app); 266 6982 checkTime(startTime, "attachApplicationLocked: after sendPendingBroadcastsLocked"); 267 6983 } catch (Exception e) { 268 6984 // If the app died trying to launch the receiver we declare it 'bad' 269 6985 Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e); 270 6986 badApp = true; 271 6987 } 272 6988 } 273 6989 274 6990 // Check whether the next backup agent is in this process... 275 6991 if (!badApp && mBackupTarget != null && mBackupTarget.app == app) { 276 6992 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, 277 6993 "New app is backup target, launching agent for " + app); 278 6994 notifyPackageUse(mBackupTarget.appInfo.packageName, 279 6995 PackageManager.NOTIFY_PACKAGE_USE_BACKUP); 280 6996 try { 281 6997 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo, 282 6998 compatibilityInfoForPackageLocked(mBackupTarget.appInfo), 283 6999 mBackupTarget.backupMode); 284 7000 } catch (Exception e) { 285 7001 Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e); 286 7002 badApp = true; 287 7003 } 288 7004 } 289 7005 290 7006 if (badApp) { 291 7007 app.kill("error during init", true); 292 7008 handleAppDiedLocked(app, false, true); 293 7009 return false; 294 7010 } 295 7011 296 7012 if (!didSomething) { 297 7013 updateOomAdjLocked(); 298 7014 checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked"); 299 7015 } 300 7016 301 7017 return true; 302 7018 } 303 7019 304 7020 @Override 305 7021 public final void attachApplication(IApplicationThread thread) { 306 7022 synchronized (this) { 307 7023 int callingPid = Binder.getCallingPid(); 308 7024 final long origId = Binder.clearCallingIdentity(); 309 7025 attachApplicationLocked(thread, callingPid); 310 7026 Binder.restoreCallingIdentity(origId); 311 7027 } 312 7028 } 313 7029
Activity idle
1 7030 @Override 2 7031 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) { 3 7032 final long origId = Binder.clearCallingIdentity(); 4 7033 synchronized (this) { 5 7034 ActivityStack stack = ActivityRecord.getStackLocked(token); 6 7035 if (stack != null) { 7 7036 ActivityRecord r = 8 7037 mStackSupervisor.activityIdleInternalLocked(token, false /* fromTimeout */, 9 7038 false /* processPausingActivities */, config); 10 7039 if (stopProfiling) { 11 7040 if ((mProfileProc == r.app) && (mProfileFd != null)) { 12 7041 try { 13 7042 mProfileFd.close(); 14 7043 } catch (IOException e) { 15 7044 } 16 7045 clearProfilerLocked(); 17 7046 } 18 7047 } 19 7048 } 20 7049 } 21 7050 Binder.restoreCallingIdentity(origId); 22 7051 }
发送结束boot消息
1 7053 void postFinishBooting(boolean finishBooting, boolean enableScreen) { 2 7054 mHandler.sendMessage(mHandler.obtainMessage(FINISH_BOOTING_MSG, 3 7055 finishBooting ? 1 : 0, enableScreen ? 1 : 0)); 4 7056 }
启动后使能screen
1 7058 void enableScreenAfterBoot() { 2 7059 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN, 3 7060 SystemClock.uptimeMillis()); 4 7061 mWindowManager.enableScreenAfterBoot(); 5 7062 6 7063 synchronized (this) { 7 7064 updateEventDispatchingLocked(); 8 7065 } 9 7066 }
显示启动信息
1 7068 @Override 2 7069 public void showBootMessage(final CharSequence msg, final boolean always) { 3 7070 if (Binder.getCallingUid() != myUid()) { 4 7071 throw new SecurityException(); 5 7072 } 6 7073 mWindowManager.showBootMessage(msg, always); 7 7074 } 8 7075
锁屏消失
1 7076 @Override 2 7077 public void keyguardGoingAway(int flags) { 3 7078 enforceNotIsolatedCaller("keyguardGoingAway"); 4 7079 final long token = Binder.clearCallingIdentity(); 5 7080 try { 6 7081 synchronized (this) { 7 7082 mKeyguardController.keyguardGoingAway(flags); 8 7083 } 9 7084 } finally { 10 7085 Binder.restoreCallingIdentity(token); 11 7086 } 12 7087 }
是否有锁屏
1 7089 /** 2 7090 * @return whther the keyguard is currently locked. 3 7091 */ 4 7092 boolean isKeyguardLocked() { 5 7093 return mKeyguardController.isKeyguardLocked(); 6 7094 }
结束boot
1 7096 final void finishBooting() { 2 7097 synchronized (this) { 3 7098 if (!mBootAnimationComplete) { 4 7099 mCallFinishBooting = true; 5 7100 return; 6 7101 } 7 7102 mCallFinishBooting = false; 8 7103 } 9 7104 10 7105 ArraySet<String> completedIsas = new ArraySet<String>(); 11 7106 for (String abi : Build.SUPPORTED_ABIS) { 12 7107 zygoteProcess.establishZygoteConnectionForAbi(abi); 13 7108 final String instructionSet = VMRuntime.getInstructionSet(abi); 14 7109 if (!completedIsas.contains(instructionSet)) { 15 7110 try { 16 7111 mInstaller.markBootComplete(VMRuntime.getInstructionSet(abi)); 17 7112 } catch (InstallerException e) { 18 7113 Slog.w(TAG, "Unable to mark boot complete for abi: " + abi + " (" + 19 7114 e.getMessage() +")"); 20 7115 } 21 7116 completedIsas.add(instructionSet); 22 7117 } 23 7118 } 24 7119 25 7120 IntentFilter pkgFilter = new IntentFilter(); 26 7121 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART); 27 7122 pkgFilter.addDataScheme("package"); 28 7123 mContext.registerReceiver(new BroadcastReceiver() { 29 7124 @Override 30 7125 public void onReceive(Context context, Intent intent) { 31 7126 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES); 32 7127 if (pkgs != null) { 33 7128 for (String pkg : pkgs) { 34 7129 synchronized (ActivityManagerService.this) { 35 7130 if (forceStopPackageLocked(pkg, -1, false, false, false, false, false, 36 7131 0, "query restart")) { 37 7132 setResultCode(Activity.RESULT_OK); 38 7133 return; 39 7134 } 40 7135 } 41 7136 } 42 7137 } 43 7138 } 44 7139 }, pkgFilter); 45 7140 46 7141 IntentFilter dumpheapFilter = new IntentFilter(); 47 7142 dumpheapFilter.addAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP); 48 7143 mContext.registerReceiver(new BroadcastReceiver() { 49 7144 @Override 50 7145 public void onReceive(Context context, Intent intent) { 51 7146 if (intent.getBooleanExtra(DumpHeapActivity.EXTRA_DELAY_DELETE, false)) { 52 7147 mHandler.sendEmptyMessageDelayed(POST_DUMP_HEAP_NOTIFICATION_MSG, 5*60*1000); 53 7148 } else { 54 7149 mHandler.sendEmptyMessage(POST_DUMP_HEAP_NOTIFICATION_MSG); 55 7150 } 56 7151 } 57 7152 }, dumpheapFilter); 58 7153 59 7154 // Let system services know. 60 7155 mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED); 61 7156 62 7157 synchronized (this) { 63 7158 // Ensure that any processes we had put on hold are now started 64 7159 // up. 65 7160 final int NP = mProcessesOnHold.size(); 66 7161 if (NP > 0) { 67 7162 ArrayList<ProcessRecord> procs = 68 7163 new ArrayList<ProcessRecord>(mProcessesOnHold); 69 7164 for (int ip=0; ip<NP; ip++) { 70 7165 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "Starting process on hold: " 71 7166 + procs.get(ip)); 72 7167 startProcessLocked(procs.get(ip), "on-hold", null); 73 7168 } 74 7169 } 75 7170 76 7171 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) { 77 7172 // Start looking for apps that are abusing wake locks. 78 7173 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 79 7174 mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_DELAY); 80 7175 // Tell anyone interested that we are done booting! 81 7176 SystemProperties.set("sys.boot_completed", "1"); 82 7177 83 7178 // And trigger dev.bootcomplete if we are not showing encryption progress 84 7179 if (!"trigger_restart_min_framework".equals(SystemProperties.get("vold.decrypt")) 85 7180 || "".equals(SystemProperties.get("vold.encrypt_progress"))) { 86 7181 SystemProperties.set("dev.bootcomplete", "1"); 87 7182 } 88 7183 mUserController.sendBootCompletedLocked( 89 7184 new IIntentReceiver.Stub() { 90 7185 @Override 91 7186 public void performReceive(Intent intent, int resultCode, 92 7187 String data, Bundle extras, boolean ordered, 93 7188 boolean sticky, int sendingUser) { 94 7189 synchronized (ActivityManagerService.this) { 95 7190 requestPssAllProcsLocked(SystemClock.uptimeMillis(), 96 7191 true, false); 97 7192 } 98 7193 } 99 7194 }); 100 7195 scheduleStartProfilesLocked(); 101 7196 } 102 7197 } 103 7198 } 104 7199
boot动画结束
1 7200 @Override 2 7201 public void bootAnimationComplete() { 3 7202 final boolean callFinishBooting; 4 7203 synchronized (this) { 5 7204 callFinishBooting = mCallFinishBooting; 6 7205 mBootAnimationComplete = true; 7 7206 } 8 7207 if (callFinishBooting) { 9 7208 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "FinishBooting"); 10 7209 finishBooting(); 11 7210 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 12 7211 } 13 7212 }
确保boot完成
1 7214 final void ensureBootCompleted() { 2 7215 boolean booting; 3 7216 boolean enableScreen; 4 7217 synchronized (this) { 5 7218 booting = mBooting; 6 7219 mBooting = false; 7 7220 enableScreen = !mBooted; 8 7221 mBooted = true; 9 7222 } 10 7223 11 7224 if (booting) { 12 7225 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "FinishBooting"); 13 7226 finishBooting(); 14 7227 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 15 7228 } 16 7229 17 7230 if (enableScreen) { 18 7231 enableScreenAfterBoot(); 19 7232 } 20 7233 }
Activity resumed,paused,stopped,destroyed,relaunched
1 7235 @Override 2 7236 public final void activityResumed(IBinder token) { 3 7237 final long origId = Binder.clearCallingIdentity(); 4 7238 synchronized(this) { 5 7239 ActivityRecord.activityResumedLocked(token); 6 7240 mWindowManager.notifyAppResumedFinished(token); 7 7241 } 8 7242 Binder.restoreCallingIdentity(origId); 9 7243 } 10 7244 11 7245 @Override 12 7246 public final void activityPaused(IBinder token) { 13 7247 final long origId = Binder.clearCallingIdentity(); 14 7248 synchronized(this) { 15 7249 ActivityStack stack = ActivityRecord.getStackLocked(token); 16 7250 if (stack != null) { 17 7251 stack.activityPausedLocked(token, false); 18 7252 } 19 7253 } 20 7254 Binder.restoreCallingIdentity(origId); 21 7255 } 22 7256 23 7257 @Override 24 7258 public final void activityStopped(IBinder token, Bundle icicle, 25 7259 PersistableBundle persistentState, CharSequence description) { 26 7260 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token); 27 7261 28 7262 // Refuse possible leaked file descriptors 29 7263 if (icicle != null && icicle.hasFileDescriptors()) { 30 7264 throw new IllegalArgumentException("File descriptors passed in Bundle"); 31 7265 } 32 7266 33 7267 final long origId = Binder.clearCallingIdentity(); 34 7268 35 7269 synchronized (this) { 36 7270 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 37 7271 if (r != null) { 38 7272 r.activityStoppedLocked(icicle, persistentState, description); 39 7273 } 40 7274 } 41 7275 42 7276 trimApplications(); 43 7277 44 7278 Binder.restoreCallingIdentity(origId); 45 7279 } 46 7280 47 7281 @Override 48 7282 public final void activityDestroyed(IBinder token) { 49 7283 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token); 50 7284 synchronized (this) { 51 7285 ActivityStack stack = ActivityRecord.getStackLocked(token); 52 7286 if (stack != null) { 53 7287 stack.activityDestroyedLocked(token, "activityDestroyed"); 54 7288 } 55 7289 } 56 7290 } 57 7291 58 7292 @Override 59 7293 public final void activityRelaunched(IBinder token) { 60 7294 final long origId = Binder.clearCallingIdentity(); 61 7295 synchronized (this) { 62 7296 mStackSupervisor.activityRelaunchedLocked(token); 63 7297 } 64 7298 Binder.restoreCallingIdentity(origId); 65 7299 }
后台资源释放
1 7317 @Override 2 7318 public final void backgroundResourcesReleased(IBinder token) { 3 7319 final long origId = Binder.clearCallingIdentity(); 4 7320 try { 5 7321 synchronized (this) { 6 7322 ActivityStack stack = ActivityRecord.getStackLocked(token); 7 7323 if (stack != null) { 8 7324 stack.backgroundResourcesReleased(); 9 7325 } 10 7326 } 11 7327 } finally { 12 7328 Binder.restoreCallingIdentity(origId); 13 7329 } 14 7330 }
通知启动task behind被进入动画完成
1 7332 @Override 2 7333 public final void notifyLaunchTaskBehindComplete(IBinder token) { 3 7334 mStackSupervisor.scheduleLaunchTaskBehindComplete(token); 4 7335 } 5 7336 6 7337 @Override 7 7338 public final void notifyEnterAnimationComplete(IBinder token) { 8 7339 mHandler.sendMessage(mHandler.obtainMessage(ENTER_ANIMATION_COMPLETE_MSG, token)); 9 7340 }
获取调用package,activity,record,token的Activity class,token的package
1 7342 @Override 2 7343 public String getCallingPackage(IBinder token) { 3 7344 synchronized (this) { 4 7345 ActivityRecord r = getCallingRecordLocked(token); 5 7346 return r != null ? r.info.packageName : null; 6 7347 } 7 7348 } 8 7349 9 7350 @Override 10 7351 public ComponentName getCallingActivity(IBinder token) { 11 7352 synchronized (this) { 12 7353 ActivityRecord r = getCallingRecordLocked(token); 13 7354 return r != null ? r.intent.getComponent() : null; 14 7355 } 15 7356 } 16 7357 17 7358 private ActivityRecord getCallingRecordLocked(IBinder token) { 18 7359 ActivityRecord r = ActivityRecord.isInStackLocked(token); 19 7360 if (r == null) { 20 7361 return null; 21 7362 } 22 7363 return r.resultTo; 23 7364 } 24 7365 25 7366 @Override 26 7367 public ComponentName getActivityClassForToken(IBinder token) { 27 7368 synchronized(this) { 28 7369 ActivityRecord r = ActivityRecord.isInStackLocked(token); 29 7370 if (r == null) { 30 7371 return null; 31 7372 } 32 7373 return r.intent.getComponent(); 33 7374 } 34 7375 } 35 7376 36 7377 @Override 37 7378 public String getPackageForToken(IBinder token) { 38 7379 synchronized(this) { 39 7380 ActivityRecord r = ActivityRecord.isInStackLocked(token); 40 7381 if (r == null) { 41 7382 return null; 42 7383 } 43 7384 return r.packageName; 44 7385 } 45 7386 }
是否是root语音交互
1 7388 @Override 2 7389 public boolean isRootVoiceInteraction(IBinder token) { 3 7390 synchronized(this) { 4 7391 ActivityRecord r = ActivityRecord.isInStackLocked(token); 5 7392 if (r == null) { 6 7393 return false; 7 7394 } 8 7395 return r.rootVoiceInteraction; 9 7396 } 10 7397 }
获取Intent sender
1 7399 @Override 2 7400 public IIntentSender getIntentSender(int type, 3 7401 String packageName, IBinder token, String resultWho, 4 7402 int requestCode, Intent[] intents, String[] resolvedTypes, 5 7403 int flags, Bundle bOptions, int userId) { 6 7404 enforceNotIsolatedCaller("getIntentSender"); 7 7405 // Refuse possible leaked file descriptors 8 7406 if (intents != null) { 9 7407 if (intents.length < 1) { 10 7408 throw new IllegalArgumentException("Intents array length must be >= 1"); 11 7409 } 12 7410 for (int i=0; i<intents.length; i++) { 13 7411 Intent intent = intents[i]; 14 7412 if (intent != null) { 15 7413 if (intent.hasFileDescriptors()) { 16 7414 throw new IllegalArgumentException("File descriptors passed in Intent"); 17 7415 } 18 7416 if (type == ActivityManager.INTENT_SENDER_BROADCAST && 19 7417 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 20 7418 throw new IllegalArgumentException( 21 7419 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 22 7420 } 23 7421 intents[i] = new Intent(intent); 24 7422 } 25 7423 } 26 7424 if (resolvedTypes != null && resolvedTypes.length != intents.length) { 27 7425 throw new IllegalArgumentException( 28 7426 "Intent array length does not match resolvedTypes length"); 29 7427 } 30 7428 } 31 7429 if (bOptions != null) { 32 7430 if (bOptions.hasFileDescriptors()) { 33 7431 throw new IllegalArgumentException("File descriptors passed in options"); 34 7432 } 35 7433 } 36 7434 37 7435 synchronized(this) { 38 7436 int callingUid = Binder.getCallingUid(); 39 7437 int origUserId = userId; 40 7438 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, userId, 41 7439 type == ActivityManager.INTENT_SENDER_BROADCAST, 42 7440 ALLOW_NON_FULL, "getIntentSender", null); 43 7441 if (origUserId == UserHandle.USER_CURRENT) { 44 7442 // We don't want to evaluate this until the pending intent is 45 7443 // actually executed. However, we do want to always do the 46 7444 // security checking for it above. 47 7445 userId = UserHandle.USER_CURRENT; 48 7446 } 49 7447 try { 50 7448 if (callingUid != 0 && callingUid != SYSTEM_UID) { 51 7449 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName, 52 7450 MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(callingUid)); 53 7451 if (!UserHandle.isSameApp(callingUid, uid)) { 54 7452 String msg = "Permission Denial: getIntentSender() from pid=" 55 7453 + Binder.getCallingPid() 56 7454 + ", uid=" + Binder.getCallingUid() 57 7455 + ", (need uid=" + uid + ")" 58 7456 + " is not allowed to send as package " + packageName; 59 7457 Slog.w(TAG, msg); 60 7458 throw new SecurityException(msg); 61 7459 } 62 7460 } 63 7461 64 7462 return getIntentSenderLocked(type, packageName, callingUid, userId, 65 7463 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions); 66 7464 67 7465 } catch (RemoteException e) { 68 7466 throw new SecurityException(e); 69 7467 } 70 7468 } 71 7469 } 72 7470 73 7471 IIntentSender getIntentSenderLocked(int type, String packageName, 74 7472 int callingUid, int userId, IBinder token, String resultWho, 75 7473 int requestCode, Intent[] intents, String[] resolvedTypes, int flags, 76 7474 Bundle bOptions) { 77 7475 if (DEBUG_MU) Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid); 78 7476 ActivityRecord activity = null; 79 7477 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 80 7478 activity = ActivityRecord.isInStackLocked(token); 81 7479 if (activity == null) { 82 7480 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack"); 83 7481 return null; 84 7482 } 85 7483 if (activity.finishing) { 86 7484 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing"); 87 7485 return null; 88 7486 } 89 7487 } 90 7488 91 7489 // We're going to be splicing together extras before sending, so we're 92 7490 // okay poking into any contained extras. 93 7491 if (intents != null) { 94 7492 for (int i = 0; i < intents.length; i++) { 95 7493 intents[i].setDefusable(true); 96 7494 } 97 7495 } 98 7496 Bundle.setDefusable(bOptions, true); 99 7497 100 7498 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0; 101 7499 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0; 102 7500 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0; 103 7501 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT 104 7502 |PendingIntent.FLAG_UPDATE_CURRENT); 105 7503 106 7504 PendingIntentRecord.Key key = new PendingIntentRecord.Key( 107 7505 type, packageName, activity, resultWho, 108 7506 requestCode, intents, resolvedTypes, flags, bOptions, userId); 109 7507 WeakReference<PendingIntentRecord> ref; 110 7508 ref = mIntentSenderRecords.get(key); 111 7509 PendingIntentRecord rec = ref != null ? ref.get() : null; 112 7510 if (rec != null) { 113 7511 if (!cancelCurrent) { 114 7512 if (updateCurrent) { 115 7513 if (rec.key.requestIntent != null) { 116 7514 rec.key.requestIntent.replaceExtras(intents != null ? 117 7515 intents[intents.length - 1] : null); 118 7516 } 119 7517 if (intents != null) { 120 7518 intents[intents.length-1] = rec.key.requestIntent; 121 7519 rec.key.allIntents = intents; 122 7520 rec.key.allResolvedTypes = resolvedTypes; 123 7521 } else { 124 7522 rec.key.allIntents = null; 125 7523 rec.key.allResolvedTypes = null; 126 7524 } 127 7525 } 128 7526 return rec; 129 7527 } 130 7528 makeIntentSenderCanceledLocked(rec); 131 7529 mIntentSenderRecords.remove(key); 132 7530 } 133 7531 if (noCreate) { 134 7532 return rec; 135 7533 } 136 7534 rec = new PendingIntentRecord(this, key, callingUid); 137 7535 mIntentSenderRecords.put(key, rec.ref); 138 7536 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 139 7537 if (activity.pendingResults == null) { 140 7538 activity.pendingResults 141 7539 = new HashSet<WeakReference<PendingIntentRecord>>(); 142 7540 } 143 7541 activity.pendingResults.add(rec.ref); 144 7542 } 145 7543 return rec; 146 7544 }
发送Intent Sender
1 7546 @Override 2 7547 public int sendIntentSender(IIntentSender target, IBinder whitelistToken, int code, 3 7548 Intent intent, String resolvedType, 4 7549 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) { 5 7550 if (target instanceof PendingIntentRecord) { 6 7551 return ((PendingIntentRecord)target).sendWithResult(code, intent, resolvedType, 7 7552 whitelistToken, finishedReceiver, requiredPermission, options); 8 7553 } else { 9 7554 if (intent == null) { 10 7555 // Weird case: someone has given us their own custom IIntentSender, and now 11 7556 // they have someone else trying to send to it but of course this isn't 12 7557 // really a PendingIntent, so there is no base Intent, and the caller isn't 13 7558 // supplying an Intent... but we never want to dispatch a null Intent to 14 7559 // a receiver, so um... let's make something up. 15 7560 Slog.wtf(TAG, "Can't use null intent with direct IIntentSender call"); 16 7561 intent = new Intent(Intent.ACTION_MAIN); 17 7562 } 18 7563 try { 19 7564 target.send(code, intent, resolvedType, whitelistToken, null, 20 7565 requiredPermission, options); 21 7566 } catch (RemoteException e) { 22 7567 } 23 7568 // Platform code can rely on getting a result back when the send is done, but if 24 7569 // this intent sender is from outside of the system we can't rely on it doing that. 25 7570 // So instead we don't give it the result receiver, and instead just directly 26 7571 // report the finish immediately. 27 7572 if (finishedReceiver != null) { 28 7573 try { 29 7574 finishedReceiver.performReceive(intent, 0, 30 7575 null, null, false, false, UserHandle.getCallingUserId()); 31 7576 } catch (RemoteException e) { 32 7577 } 33 7578 } 34 7579 return 0; 35 7580 } 36 7581 }
取消Intent Sender
1 7583 @Override 2 7584 public void cancelIntentSender(IIntentSender sender) { 3 7585 if (!(sender instanceof PendingIntentRecord)) { 4 7586 return; 5 7587 } 6 7588 synchronized(this) { 7 7589 PendingIntentRecord rec = (PendingIntentRecord)sender; 8 7590 try { 9 7591 final int uid = AppGlobals.getPackageManager().getPackageUid(rec.key.packageName, 10 7592 MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getCallingUserId()); 11 7593 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) { 12 7594 String msg = "Permission Denial: cancelIntentSender() from pid=" 13 7595 + Binder.getCallingPid() 14 7596 + ", uid=" + Binder.getCallingUid() 15 7597 + " is not allowed to cancel package " 16 7598 + rec.key.packageName; 17 7599 Slog.w(TAG, msg); 18 7600 throw new SecurityException(msg); 19 7601 } 20 7602 } catch (RemoteException e) { 21 7603 throw new SecurityException(e); 22 7604 } 23 7605 cancelIntentSenderLocked(rec, true); 24 7606 } 25 7607 } 26 7608 27 7609 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) { 28 7610 makeIntentSenderCanceledLocked(rec); 29 7611 mIntentSenderRecords.remove(rec.key); 30 7612 if (cleanActivity && rec.key.activity != null) { 31 7613 rec.key.activity.pendingResults.remove(rec.ref); 32 7614 } 33 7615 }
制作Intent Sender cancel
1 7617 void makeIntentSenderCanceledLocked(PendingIntentRecord rec) { 2 7618 rec.canceled = true; 3 7619 RemoteCallbackList<IResultReceiver> callbacks = rec.detachCancelListenersLocked(); 4 7620 if (callbacks != null) { 5 7621 mHandler.obtainMessage(DISPATCH_PENDING_INTENT_CANCEL_MSG, callbacks).sendToTarget(); 6 7622 } 7 7623 } 8 7624
为Intent Sender获取package
1 7625 @Override 2 7626 public String getPackageForIntentSender(IIntentSender pendingResult) { 3 7627 if (!(pendingResult instanceof PendingIntentRecord)) { 4 7628 return null; 5 7629 } 6 7630 try { 7 7631 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 8 7632 return res.key.packageName; 9 7633 } catch (ClassCastException e) { 10 7634 } 11 7635 return null; 12 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
1 7659 @Override 2 7660 public int getUidForIntentSender(IIntentSender sender) { 3 7661 if (sender instanceof PendingIntentRecord) { 4 7662 try { 5 7663 PendingIntentRecord res = (PendingIntentRecord)sender; 6 7664 return res.uid; 7 7665 } catch (ClassCastException e) { 8 7666 } 9 7667 } 10 7668 return -1; 11 7669 } 12 7670
是否Intent Sender目标的目标是相应package
1 7671 @Override 2 7672 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) { 3 7673 if (!(pendingResult instanceof PendingIntentRecord)) { 4 7674 return false; 5 7675 } 6 7676 try { 7 7677 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 8 7678 if (res.key.allIntents == null) { 9 7679 return false; 10 7680 } 11 7681 for (int i=0; i<res.key.allIntents.length; i++) { 12 7682 Intent intent = res.key.allIntents[i]; 13 7683 if (intent.getPackage() != null && intent.getComponent() != null) { 14 7684 return false; 15 7685 } 16 7686 } 17 7687 return true; 18 7688 } catch (ClassCastException e) { 19 7689 } 20 7690 return false; 21 7691 } 22 7692
是否Intent Sender是个Activity
1 7693 @Override 2 7694 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) { 3 7695 if (!(pendingResult instanceof PendingIntentRecord)) { 4 7696 return false; 5 7697 } 6 7698 try { 7 7699 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 8 7700 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) { 9 7701 return true; 10 7702 } 11 7703 return false; 12 7704 } catch (ClassCastException e) { 13 7705 } 14 7706 return false; 15 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
1 7763 @Override 2 7764 public void setProcessLimit(int max) { 3 7765 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 4 7766 "setProcessLimit()"); 5 7767 synchronized (this) { 6 7768 mConstants.setOverrideMaxCachedProcesses(max); 7 7769 } 8 7770 trimApplications(); 9 7771 } 10 7772 11 7773 @Override 12 7774 public int getProcessLimit() { 13 7775 synchronized (this) { 14 7776 return mConstants.getOverrideMaxCachedProcesses(); 15 7777 } 16 7778 }
重要进程死亡
1 7780 void importanceTokenDied(ImportanceToken token) { 2 7781 synchronized (ActivityManagerService.this) { 3 7782 synchronized (mPidsSelfLocked) { 4 7783 ImportanceToken cur 5 7784 = mImportantProcesses.get(token.pid); 6 7785 if (cur != token) { 7 7786 return; 8 7787 } 9 7788 mImportantProcesses.remove(token.pid); 10 7789 ProcessRecord pr = mPidsSelfLocked.get(token.pid); 11 7790 if (pr == null) { 12 7791 return; 13 7792 } 14 7793 pr.forcingToImportant = null; 15 7794 updateProcessForegroundLocked(pr, false, false); 16 7795 } 17 7796 updateOomAdjLocked(); 18 7797 } 19 7798 }
设置进程important
1 7800 @Override 2 7801 public void setProcessImportant(IBinder token, int pid, boolean isForeground, String reason) { 3 7802 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 4 7803 "setProcessImportant()"); 5 7804 synchronized(this) { 6 7805 boolean changed = false; 7 7806 8 7807 synchronized (mPidsSelfLocked) { 9 7808 ProcessRecord pr = mPidsSelfLocked.get(pid); 10 7809 if (pr == null && isForeground) { 11 7810 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid); 12 7811 return; 13 7812 } 14 7813 ImportanceToken oldToken = mImportantProcesses.get(pid); 15 7814 if (oldToken != null) { 16 7815 oldToken.token.unlinkToDeath(oldToken, 0); 17 7816 mImportantProcesses.remove(pid); 18 7817 if (pr != null) { 19 7818 pr.forcingToImportant = null; 20 7819 } 21 7820 changed = true; 22 7821 } 23 7822 if (isForeground && token != null) { 24 7823 ImportanceToken newToken = new ImportanceToken(pid, token, reason) { 25 7824 @Override 26 7825 public void binderDied() { 27 7826 importanceTokenDied(this); 28 7827 } 29 7828 }; 30 7829 try { 31 7830 token.linkToDeath(newToken, 0); 32 7831 mImportantProcesses.put(pid, newToken); 33 7832 pr.forcingToImportant = newToken; 34 7833 changed = true; 35 7834 } catch (RemoteException e) { 36 7835 // If the process died while doing this, we will later 37 7836 // do the cleanup with the process death link. 38 7837 } 39 7838 } 40 7839 } 41 7840 42 7841 if (changed) { 43 7842 updateOomAdjLocked(); 44 7843 } 45 7844 } 46 7845 } 47 7846
判断app是否在前台
1 7847 @Override 2 7848 public boolean isAppForeground(int uid) throws RemoteException { 3 7849 synchronized (this) { 4 7850 UidRecord uidRec = mActiveUids.get(uid); 5 7851 if (uidRec == null || uidRec.idle) { 6 7852 return false; 7 7853 } 8 7854 return uidRec.curProcState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 9 7855 } 10 7856 }
获取uid状态
1 7858 // NOTE: this is an internal method used by the OnShellCommand implementation only and should 2 7859 // be guarded by permission checking. 3 7860 int getUidState(int uid) { 4 7861 synchronized (this) { 5 7862 return getUidStateLocked(uid); 6 7863 } 7 7864 }
获取uid state
1 7866 int getUidStateLocked(int uid) { 2 7867 UidRecord uidRec = mActiveUids.get(uid); 3 7868 return uidRec == null ? ActivityManager.PROCESS_STATE_NONEXISTENT : uidRec.curProcState; 4 7869 }
是否在多窗口模式
1 7871 @Override 2 7872 public boolean isInMultiWindowMode(IBinder token) { 3 7873 final long origId = Binder.clearCallingIdentity(); 4 7874 try { 5 7875 synchronized(this) { 6 7876 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 7 7877 if (r == null) { 8 7878 return false; 9 7879 } 10 7880 // An activity is consider to be in multi-window mode if its task isn't fullscreen. 11 7881 return !r.getTask().mFullscreen; 12 7882 } 13 7883 } finally { 14 7884 Binder.restoreCallingIdentity(origId); 15 7885 } 16 7886 }
pip模式相关
1 7888 @Override 2 7889 public boolean isInPictureInPictureMode(IBinder token) { 3 7890 final long origId = Binder.clearCallingIdentity(); 4 7891 try { 5 7892 synchronized(this) { 6 7893 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token)); 7 7894 } 8 7895 } finally { 9 7896 Binder.restoreCallingIdentity(origId); 10 7897 } 11 7898 } 12 7899 13 7900 private boolean isInPictureInPictureMode(ActivityRecord r) { 14 7901 if (r == null || r.getStack() == null || !r.getStack().isPinnedStack() || 15 7902 r.getStack().isInStackLocked(r) == null) { 16 7903 return false; 17 7904 } 18 7905 19 7906 // If we are animating to fullscreen then we have already dispatched the PIP mode 20 7907 // changed, so we should reflect that check here as well. 21 7908 final PinnedActivityStack stack = r.getStack(); 22 7909 final PinnedStackWindowController windowController = stack.getWindowContainerController(); 23 7910 return !windowController.isAnimatingBoundsToFullscreen(); 24 7911 } 25 7912 26 7913 @Override 27 7914 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) { 28 7915 final long origId = Binder.clearCallingIdentity(); 29 7916 try { 30 7917 synchronized(this) { 31 7918 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked( 32 7919 "enterPictureInPictureMode", token, params); 33 7920 34 7921 // If the activity is already in picture in picture mode, then just return early 35 7922 if (isInPictureInPictureMode(r)) { 36 7923 return true; 37 7924 } 38 7925 39 7926 // Activity supports picture-in-picture, now check that we can enter PiP at this 40 7927 // point, if it is 41 7928 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode", 42 7929 false /* noThrow */, false /* beforeStopping */)) { 43 7930 return false; 44 7931 } 45 7932 46 7933 final Runnable enterPipRunnable = () -> { 47 7934 // Only update the saved args from the args that are set 48 7935 r.pictureInPictureArgs.copyOnlySet(params); 49 7936 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio(); 50 7937 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions(); 51 7938 // Adjust the source bounds by the insets for the transition down 52 7939 final Rect sourceBounds = new Rect(r.pictureInPictureArgs.getSourceRectHint()); 53 7940 mStackSupervisor.moveActivityToPinnedStackLocked(r, sourceBounds, aspectRatio, 54 7941 true /* moveHomeStackToFront */, "enterPictureInPictureMode"); 55 7942 final PinnedActivityStack stack = mStackSupervisor.getStack(PINNED_STACK_ID); 56 7943 stack.setPictureInPictureAspectRatio(aspectRatio); 57 7944 stack.setPictureInPictureActions(actions); 58 7945 59 7946 MetricsLogger.action(mContext, MetricsEvent.ACTION_PICTURE_IN_PICTURE_ENTERED, 60 7947 r.supportsPictureInPictureWhilePausing); 61 7948 logPictureInPictureArgs(params); 62 7949 }; 63 7950 64 7951 if (isKeyguardLocked()) { 65 7952 // If the keyguard is showing or occluded, then try and dismiss it before 66 7953 // entering picture-in-picture (this will prompt the user to authenticate if the 67 7954 // device is currently locked). 68 7955 try { 69 7956 dismissKeyguard(token, new IKeyguardDismissCallback.Stub() { 70 7957 @Override 71 7958 public void onDismissError() throws RemoteException { 72 7959 // Do nothing 73 7960 } 74 7961 75 7962 @Override 76 7963 public void onDismissSucceeded() throws RemoteException { 77 7964 mHandler.post(enterPipRunnable); 78 7965 } 79 7966 80 7967 @Override 81 7968 public void onDismissCancelled() throws RemoteException { 82 7969 // Do nothing 83 7970 } 84 7971 }); 85 7972 } catch (RemoteException e) { 86 7973 // Local call 87 7974 } 88 7975 } else { 89 7976 // Enter picture in picture immediately otherwise 90 7977 enterPipRunnable.run(); 91 7978 } 92 7979 return true; 93 7980 } 94 7981 } finally { 95 7982 Binder.restoreCallingIdentity(origId); 96 7983 } 97 7984 } 98 7985 99 7986 @Override 100 7987 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) { 101 7988 final long origId = Binder.clearCallingIdentity(); 102 7989 try { 103 7990 synchronized(this) { 104 7991 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked( 105 7992 "setPictureInPictureParams", token, params); 106 7993 107 7994 // Only update the saved args from the args that are set 108 7995 r.pictureInPictureArgs.copyOnlySet(params); 109 7996 if (r.getStack().getStackId() == PINNED_STACK_ID) { 110 7997 // If the activity is already in picture-in-picture, update the pinned stack now 111 7998 // if it is not already expanding to fullscreen. Otherwise, the arguments will 112 7999 // be used the next time the activity enters PiP 113 8000 final PinnedActivityStack stack = r.getStack(); 114 8001 if (!stack.isAnimatingBoundsToFullscreen()) { 115 8002 stack.setPictureInPictureAspectRatio( 116 8003 r.pictureInPictureArgs.getAspectRatio()); 117 8004 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions()); 118 8005 } 119 8006 } 120 8007 logPictureInPictureArgs(params); 121 8008 } 122 8009 } finally { 123 8010 Binder.restoreCallingIdentity(origId); 124 8011 } 125 8012 } 126 8013 127 8014 @Override 128 8015 public int getMaxNumPictureInPictureActions(IBinder token) { 129 8016 // Currently, this is a static constant, but later, we may change this to be dependent on 130 8017 // the context of the activity 131 8018 return 3; 132 8019 } 133 8020 134 8021 private void logPictureInPictureArgs(PictureInPictureParams params) { 135 8022 if (params.hasSetActions()) { 136 8023 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count", 137 8024 params.getActions().size()); 138 8025 } 139 8026 if (params.hasSetAspectRatio()) { 140 8027 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED); 141 8028 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio()); 142 8029 MetricsLogger.action(lm); 143 8030 } 144 8031 } 145 8032 146 8033 /** 147 8034 * Checks the state of the system and the activity associated with the given {@param token} to 148 8035 * verify that picture-in-picture is supported for that activity. 149 8036 * 150 8037 * @return the activity record for the given {@param token} if all the checks pass. 151 8038 */ 152 8039 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller, 153 8040 IBinder token, PictureInPictureParams params) { 154 8041 if (!mSupportsPictureInPicture) { 155 8042 throw new IllegalStateException(caller 156 8043 + ": Device doesn't support picture-in-picture mode."); 157 8044 } 158 8045 159 8046 final ActivityRecord r = ActivityRecord.forTokenLocked(token); 160 8047 if (r == null) { 161 8048 throw new IllegalStateException(caller 162 8049 + ": Can't find activity for token=" + token); 163 8050 } 164 8051 165 8052 if (!r.supportsPictureInPicture()) { 166 8053 throw new IllegalStateException(caller 167 8054 + ": Current activity does not support picture-in-picture."); 168 8055 } 169 8056 170 8057 if (!StackId.isAllowedToEnterPictureInPicture(r.getStack().getStackId())) { 171 8058 throw new IllegalStateException(caller 172 8059 + ": Activities on the home, assistant, or recents stack not supported"); 173 8060 } 174 8061 175 8062 if (params.hasSetAspectRatio() 176 8063 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId, 177 8064 params.getAspectRatio())) { 178 8065 final float minAspectRatio = mContext.getResources().getFloat( 179 8066 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio); 180 8067 final float maxAspectRatio = mContext.getResources().getFloat( 181 8068 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio); 182 8069 throw new IllegalArgumentException(String.format(caller 183 8070 + ": Aspect ratio is too extreme (must be between %f and %f).", 184 8071 minAspectRatio, maxAspectRatio)); 185 8072 } 186 8073 187 8074 // Truncate the number of actions if necessary 188 8075 params.truncateActions(getMaxNumPictureInPictureActions(token)); 189 8076 190 8077 return r; 191 8078 }
process info相关
1 8079 2 8080 // ========================================================= 3 8081 // PROCESS INFO 4 8082 // ========================================================= 5 8083 6 8084 static class ProcessInfoService extends IProcessInfoService.Stub { 7 8085 final ActivityManagerService mActivityManagerService; 8 8086 ProcessInfoService(ActivityManagerService activityManagerService) { 9 8087 mActivityManagerService = activityManagerService; 10 8088 } 11 8089 12 8090 @Override 13 8091 public void getProcessStatesFromPids(/*in*/ int[] pids, /*out*/ int[] states) { 14 8092 mActivityManagerService.getProcessStatesAndOomScoresForPIDs( 15 8093 /*in*/ pids, /*out*/ states, null); 16 8094 } 17 8095 18 8096 @Override 19 8097 public void getProcessStatesAndOomScoresFromPids( 20 8098 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) { 21 8099 mActivityManagerService.getProcessStatesAndOomScoresForPIDs( 22 8100 /*in*/ pids, /*out*/ states, /*out*/ scores); 23 8101 } 24 8102 } 25 8103 26 8104 /** 27 8105 * For each PID in the given input array, write the current process state 28 8106 * for that process into the states array, or -1 to indicate that no 29 8107 * process with the given PID exists. If scores array is provided, write 30 8108 * the oom score for the process into the scores array, with INVALID_ADJ 31 8109 * indicating the PID doesn't exist. 32 8110 */ 33 8111 public void getProcessStatesAndOomScoresForPIDs( 34 8112 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) { 35 8113 if (scores != null) { 36 8114 enforceCallingPermission(android.Manifest.permission.GET_PROCESS_STATE_AND_OOM_SCORE, 37 8115 "getProcessStatesAndOomScoresForPIDs()"); 38 8116 } 39 8117 40 8118 if (pids == null) { 41 8119 throw new NullPointerException("pids"); 42 8120 } else if (states == null) { 43 8121 throw new NullPointerException("states"); 44 8122 } else if (pids.length != states.length) { 45 8123 throw new IllegalArgumentException("pids and states arrays have different lengths!"); 46 8124 } else if (scores != null && pids.length != scores.length) { 47 8125 throw new IllegalArgumentException("pids and scores arrays have different lengths!"); 48 8126 } 49 8127 50 8128 synchronized (mPidsSelfLocked) { 51 8129 for (int i = 0; i < pids.length; i++) { 52 8130 ProcessRecord pr = mPidsSelfLocked.get(pids[i]); 53 8131 states[i] = (pr == null) ? ActivityManager.PROCESS_STATE_NONEXISTENT : 54 8132 pr.curProcState; 55 8133 if (scores != null) { 56 8134 scores[i] = (pr == null) ? ProcessList.INVALID_ADJ : pr.curAdj; 57 8135 } 58 8136 } 59 8137 } 60 8138 } 61 8139
permission相关
1 8140 // ========================================================= 2 8141 // PERMISSIONS 3 8142 // ========================================================= 4 8143 5 8144 static class PermissionController extends IPermissionController.Stub { 6 8145 ActivityManagerService mActivityManagerService; 7 8146 PermissionController(ActivityManagerService activityManagerService) { 8 8147 mActivityManagerService = activityManagerService; 9 8148 } 10 8149 11 8150 @Override 12 8151 public boolean checkPermission(String permission, int pid, int uid) { 13 8152 return mActivityManagerService.checkPermission(permission, pid, 14 8153 uid) == PackageManager.PERMISSION_GRANTED; 15 8154 } 16 8155 17 8156 @Override 18 8157 public String[] getPackagesForUid(int uid) { 19 8158 return mActivityManagerService.mContext.getPackageManager() 20 8159 .getPackagesForUid(uid); 21 8160 } 22 8161 23 8162 @Override 24 8163 public boolean isRuntimePermission(String permission) { 25 8164 try { 26 8165 PermissionInfo info = mActivityManagerService.mContext.getPackageManager() 27 8166 .getPermissionInfo(permission, 0); 28 8167 return (info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 29 8168 == PermissionInfo.PROTECTION_DANGEROUS; 30 8169 } catch (NameNotFoundException nnfe) { 31 8170 Slog.e(TAG, "No such permission: "+ permission, nnfe); 32 8171 } 33 8172 return false; 34 8173 } 35 8174 } 36 8175 37 8176 class IntentFirewallInterface implements IntentFirewall.AMSInterface { 38 8177 @Override 39 8178 public int checkComponentPermission(String permission, int pid, int uid, 40 8179 int owningUid, boolean exported) { 41 8180 return ActivityManagerService.this.checkComponentPermission(permission, pid, uid, 42 8181 owningUid, exported); 43 8182 } 44 8183 45 8184 @Override 46 8185 public Object getAMSLock() { 47 8186 return ActivityManagerService.this; 48 8187 } 49 8188 } 50 8189 51 8190 /** 52 8191 * This can be called with or without the global lock held. 53 8192 */ 54 8193 int checkComponentPermission(String permission, int pid, int uid, 55 8194 int owningUid, boolean exported) { 56 8195 if (pid == MY_PID) { 57 8196 return PackageManager.PERMISSION_GRANTED; 58 8197 } 59 8198 return ActivityManager.checkComponentPermission(permission, uid, 60 8199 owningUid, exported); 61 8200 } 62 8201 63 8202 /** 64 8203 * As the only public entry point for permissions checking, this method 65 8204 * can enforce the semantic that requesting a check on a null global 66 8205 * permission is automatically denied. (Internally a null permission 67 8206 * string is used when calling {@link #checkComponentPermission} in cases 68 8207 * when only uid-based security is needed.) 69 8208 * 70 8209 * This can be called with or without the global lock held. 71 8210 */ 72 8211 @Override 73 8212 public int checkPermission(String permission, int pid, int uid) { 74 8213 if (permission == null) { 75 8214 return PackageManager.PERMISSION_DENIED; 76 8215 } 77 8216 return checkComponentPermission(permission, pid, uid, -1, true); 78 8217 } 79 8218 80 8219 @Override 81 8220 public int checkPermissionWithToken(String permission, int pid, int uid, IBinder callerToken) { 82 8221 if (permission == null) { 83 8222 return PackageManager.PERMISSION_DENIED; 84 8223 } 85 8224 86 8225 // We might be performing an operation on behalf of an indirect binder 87 8226 // invocation, e.g. via {@link #openContentUri}. Check and adjust the 88 8227 // client identity accordingly before proceeding. 89 8228 Identity tlsIdentity = sCallerIdentity.get(); 90 8229 if (tlsIdentity != null && tlsIdentity.token == callerToken) { 91 8230 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {" 92 8231 + tlsIdentity.pid + "," + tlsIdentity.uid + "}"); 93 8232 uid = tlsIdentity.uid; 94 8233 pid = tlsIdentity.pid; 95 8234 } 96 8235 97 8236 return checkComponentPermission(permission, pid, uid, -1, true); 98 8237 } 99 8238 100 8239 /** 101 8240 * Binder IPC calls go through the public entry point. 102 8241 * This can be called with or without the global lock held. 103 8242 */ 104 8243 int checkCallingPermission(String permission) { 105 8244 return checkPermission(permission, 106 8245 Binder.getCallingPid(), 107 8246 UserHandle.getAppId(Binder.getCallingUid())); 108 8247 } 109 8248 110 8249 /** 111 8250 * This can be called with or without the global lock held. 112 8251 */ 113 8252 void enforceCallingPermission(String permission, String func) { 114 8253 if (checkCallingPermission(permission) 115 8254 == PackageManager.PERMISSION_GRANTED) { 116 8255 return; 117 8256 } 118 8257 119 8258 String msg = "Permission Denial: " + func + " from pid=" 120 8259 + Binder.getCallingPid() 121 8260 + ", uid=" + Binder.getCallingUid() 122 8261 + " requires " + permission; 123 8262 Slog.w(TAG, msg); 124 8263 throw new SecurityException(msg); 125 8264 } 126 8265 127 8266 /** 128 8267 * Determine if UID is holding permissions required to access {@link Uri} in 129 8268 * the given {@link ProviderInfo}. Final permission checking is always done 130 8269 * in {@link ContentProvider}. 131 8270 */ 132 8271 private final boolean checkHoldingPermissionsLocked( 133 8272 IPackageManager pm, ProviderInfo pi, GrantUri grantUri, int uid, final int modeFlags) { 134 8273 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 135 8274 "checkHoldingPermissionsLocked: uri=" + grantUri + " uid=" + uid); 136 8275 if (UserHandle.getUserId(uid) != grantUri.sourceUserId) { 137 8276 if (ActivityManager.checkComponentPermission(INTERACT_ACROSS_USERS, uid, -1, true) 138 8277 != PERMISSION_GRANTED) { 139 8278 return false; 140 8279 } 141 8280 } 142 8281 return checkHoldingPermissionsInternalLocked(pm, pi, grantUri, uid, modeFlags, true); 143 8282 } 144 8283 145 8284 private final boolean checkHoldingPermissionsInternalLocked(IPackageManager pm, ProviderInfo pi, 146 8285 GrantUri grantUri, int uid, final int modeFlags, boolean considerUidPermissions) { 147 8286 if (pi.applicationInfo.uid == uid) { 148 8287 return true; 149 8288 } else if (!pi.exported) { 150 8289 return false; 151 8290 } 152 8291 153 8292 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0; 154 8293 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0; 155 8294 try { 156 8295 // check if target holds top-level <provider> permissions 157 8296 if (!readMet && pi.readPermission != null && considerUidPermissions 158 8297 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) { 159 8298 readMet = true; 160 8299 } 161 8300 if (!writeMet && pi.writePermission != null && considerUidPermissions 162 8301 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) { 163 8302 writeMet = true; 164 8303 } 165 8304 166 8305 // track if unprotected read/write is allowed; any denied 167 8306 // <path-permission> below removes this ability 168 8307 boolean allowDefaultRead = pi.readPermission == null; 169 8308 boolean allowDefaultWrite = pi.writePermission == null; 170 8309 171 8310 // check if target holds any <path-permission> that match uri 172 8311 final PathPermission[] pps = pi.pathPermissions; 173 8312 if (pps != null) { 174 8313 final String path = grantUri.uri.getPath(); 175 8314 int i = pps.length; 176 8315 while (i > 0 && (!readMet || !writeMet)) { 177 8316 i--; 178 8317 PathPermission pp = pps[i]; 179 8318 if (pp.match(path)) { 180 8319 if (!readMet) { 181 8320 final String pprperm = pp.getReadPermission(); 182 8321 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 183 8322 "Checking read perm for " + pprperm + " for " + pp.getPath() 184 8323 + ": match=" + pp.match(path) 185 8324 + " check=" + pm.checkUidPermission(pprperm, uid)); 186 8325 if (pprperm != null) { 187 8326 if (considerUidPermissions && pm.checkUidPermission(pprperm, uid) 188 8327 == PERMISSION_GRANTED) { 189 8328 readMet = true; 190 8329 } else { 191 8330 allowDefaultRead = false; 192 8331 } 193 8332 } 194 8333 } 195 8334 if (!writeMet) { 196 8335 final String ppwperm = pp.getWritePermission(); 197 8336 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 198 8337 "Checking write perm " + ppwperm + " for " + pp.getPath() 199 8338 + ": match=" + pp.match(path) 200 8339 + " check=" + pm.checkUidPermission(ppwperm, uid)); 201 8340 if (ppwperm != null) { 202 8341 if (considerUidPermissions && pm.checkUidPermission(ppwperm, uid) 203 8342 == PERMISSION_GRANTED) { 204 8343 writeMet = true; 205 8344 } else { 206 8345 allowDefaultWrite = false; 207 8346 } 208 8347 } 209 8348 } 210 8349 } 211 8350 } 212 8351 } 213 8352 214 8353 // grant unprotected <provider> read/write, if not blocked by 215 8354 // <path-permission> above 216 8355 if (allowDefaultRead) readMet = true; 217 8356 if (allowDefaultWrite) writeMet = true; 218 8357 219 8358 } catch (RemoteException e) { 220 8359 return false; 221 8360 } 222 8361 223 8362 return readMet && writeMet; 224 8363 }
是否app start mode被禁止
1 8365 public boolean isAppStartModeDisabled(int uid, String packageName) { 2 8366 synchronized (this) { 3 8367 return getAppStartModeLocked(uid, packageName, 0, -1, false, true) 4 8368 == ActivityManager.APP_START_MODE_DISABLED; 5 8369 } 6 8370 }
app被限制在后台
1 8372 // Unified app-op and target sdk check 2 8373 int appRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk) { 3 8374 // Apps that target O+ are always subject to background check 4 8375 if (packageTargetSdk >= Build.VERSION_CODES.O) { 5 8376 if (DEBUG_BACKGROUND_CHECK) { 6 8377 Slog.i(TAG, "App " + uid + "/" + packageName + " targets O+, restricted"); 7 8378 } 8 8379 return ActivityManager.APP_START_MODE_DELAYED_RIGID; 9 8380 } 10 8381 // ...and legacy apps get an AppOp check 11 8382 int appop = mAppOpsService.noteOperation(AppOpsManager.OP_RUN_IN_BACKGROUND, 12 8383 uid, packageName); 13 8384 if (DEBUG_BACKGROUND_CHECK) { 14 8385 Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " bg appop " + appop); 15 8386 } 16 8387 switch (appop) { 17 8388 case AppOpsManager.MODE_ALLOWED: 18 8389 return ActivityManager.APP_START_MODE_NORMAL; 19 8390 case AppOpsManager.MODE_IGNORED: 20 8391 return ActivityManager.APP_START_MODE_DELAYED; 21 8392 default: 22 8393 return ActivityManager.APP_START_MODE_DELAYED_RIGID; 23 8394 } 24 8395 } 25 8396 26 8397 // Service launch is available to apps with run-in-background exemptions but 27 8398 // some other background operations are not. If we're doing a check 28 8399 // of service-launch policy, allow those callers to proceed unrestricted. 29 8400 int appServicesRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk) { 30 8401 // Persistent app? 31 8402 if (mPackageManagerInt.isPackagePersistent(packageName)) { 32 8403 if (DEBUG_BACKGROUND_CHECK) { 33 8404 Slog.i(TAG, "App " + uid + "/" + packageName 34 8405 + " is persistent; not restricted in background"); 35 8406 } 36 8407 return ActivityManager.APP_START_MODE_NORMAL; 37 8408 } 38 8409 39 8410 // Non-persistent but background whitelisted? 40 8411 if (uidOnBackgroundWhitelist(uid)) { 41 8412 if (DEBUG_BACKGROUND_CHECK) { 42 8413 Slog.i(TAG, "App " + uid + "/" + packageName 43 8414 + " on background whitelist; not restricted in background"); 44 8415 } 45 8416 return ActivityManager.APP_START_MODE_NORMAL; 46 8417 } 47 8418 48 8419 // Is this app on the battery whitelist? 49 8420 if (isOnDeviceIdleWhitelistLocked(uid)) { 50 8421 if (DEBUG_BACKGROUND_CHECK) { 51 8422 Slog.i(TAG, "App " + uid + "/" + packageName 52 8423 + " on idle whitelist; not restricted in background"); 53 8424 } 54 8425 return ActivityManager.APP_START_MODE_NORMAL; 55 8426 } 56 8427 57 8428 // None of the service-policy criteria apply, so we apply the common criteria 58 8429 return appRestrictedInBackgroundLocked(uid, packageName, packageTargetSdk); 59 8430 }
获取app启动模式
1 8432 int getAppStartModeLocked(int uid, String packageName, int packageTargetSdk, 2 8433 int callingPid, boolean alwaysRestrict, boolean disabledOnly) { 3 8434 UidRecord uidRec = mActiveUids.get(uid); 4 8435 if (DEBUG_BACKGROUND_CHECK) Slog.d(TAG, "checkAllowBackground: uid=" + uid + " pkg=" 5 8436 + packageName + " rec=" + uidRec + " always=" + alwaysRestrict + " idle=" 6 8437 + (uidRec != null ? uidRec.idle : false)); 7 8438 if (uidRec == null || alwaysRestrict || uidRec.idle) { 8 8439 boolean ephemeral; 9 8440 if (uidRec == null) { 10 8441 ephemeral = getPackageManagerInternalLocked().isPackageEphemeral( 11 8442 UserHandle.getUserId(uid), packageName); 12 8443 } else { 13 8444 ephemeral = uidRec.ephemeral; 14 8445 } 15 8446 16 8447 if (ephemeral) { 17 8448 // We are hard-core about ephemeral apps not running in the background. 18 8449 return ActivityManager.APP_START_MODE_DISABLED; 19 8450 } else { 20 8451 if (disabledOnly) { 21 8452 // The caller is only interested in whether app starts are completely 22 8453 // disabled for the given package (that is, it is an instant app). So 23 8454 // we don't need to go further, which is all just seeing if we should 24 8455 // apply a "delayed" mode for a regular app. 25 8456 return ActivityManager.APP_START_MODE_NORMAL; 26 8457 } 27 8458 final int startMode = (alwaysRestrict) 28 8459 ? appRestrictedInBackgroundLocked(uid, packageName, packageTargetSdk) 29 8460 : appServicesRestrictedInBackgroundLocked(uid, packageName, 30 8461 packageTargetSdk); 31 8462 if (DEBUG_BACKGROUND_CHECK) Slog.d(TAG, "checkAllowBackground: uid=" + uid 32 8463 + " pkg=" + packageName + " startMode=" + startMode 33 8464 + " onwhitelist=" + isOnDeviceIdleWhitelistLocked(uid)); 34 8465 if (startMode == ActivityManager.APP_START_MODE_DELAYED) { 35 8466 // This is an old app that has been forced into a "compatible as possible" 36 8467 // mode of background check. To increase compatibility, we will allow other 37 8468 // foreground apps to cause its services to start. 38 8469 if (callingPid >= 0) { 39 8470 ProcessRecord proc; 40 8471 synchronized (mPidsSelfLocked) { 41 8472 proc = mPidsSelfLocked.get(callingPid); 42 8473 } 43 8474 if (proc != null && 44 8475 !ActivityManager.isProcStateBackground(proc.curProcState)) { 45 8476 // Whoever is instigating this is in the foreground, so we will allow it 46 8477 // to go through. 47 8478 return ActivityManager.APP_START_MODE_NORMAL; 48 8479 } 49 8480 } 50 8481 } 51 8482 return startMode; 52 8483 } 53 8484 } 54 8485 return ActivityManager.APP_START_MODE_NORMAL; 55 8486 }
是否在设备空闲白名单上
1 8488 boolean isOnDeviceIdleWhitelistLocked(int uid) { 2 8489 final int appId = UserHandle.getAppId(uid); 3 8490 return Arrays.binarySearch(mDeviceIdleWhitelist, appId) >= 0 4 8491 || Arrays.binarySearch(mDeviceIdleTempWhitelist, appId) >= 0 5 8492 || mPendingTempWhitelist.indexOfKey(uid) >= 0; 6 8493 }
获取provider info
1 8495 private ProviderInfo getProviderInfoLocked(String authority, int userHandle, int pmFlags) { 2 8496 ProviderInfo pi = null; 3 8497 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userHandle); 4 8498 if (cpr != null) { 5 8499 pi = cpr.info; 6 8500 } else { 7 8501 try { 8 8502 pi = AppGlobals.getPackageManager().resolveContentProvider( 9 8503 authority, PackageManager.GET_URI_PERMISSION_PATTERNS | pmFlags, 10 8504 userHandle); 11 8505 } catch (RemoteException ex) { 12 8506 } 13 8507 } 14 8508 return pi; 15 8509 } 16 8510
授权访问ephemeral
1 8511 void grantEphemeralAccessLocked(int userId, Intent intent, 2 8512 int targetAppId, int ephemeralAppId) { 3 8513 getPackageManagerInternalLocked(). 4 8514 grantEphemeralAccess(userId, intent, targetAppId, ephemeralAppId); 5 8515 }
uri permission相关
1 8517 private UriPermission findUriPermissionLocked(int targetUid, GrantUri grantUri) { 2 8518 final ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid); 3 8519 if (targetUris != null) { 4 8520 return targetUris.get(grantUri); 5 8521 } 6 8522 return null; 7 8523 } 8 8524 9 8525 private UriPermission findOrCreateUriPermissionLocked(String sourcePkg, 10 8526 String targetPkg, int targetUid, GrantUri grantUri) { 11 8527 ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid); 12 8528 if (targetUris == null) { 13 8529 targetUris = Maps.newArrayMap(); 14 8530 mGrantedUriPermissions.put(targetUid, targetUris); 15 8531 } 16 8532 17 8533 UriPermission perm = targetUris.get(grantUri); 18 8534 if (perm == null) { 19 8535 perm = new UriPermission(sourcePkg, targetPkg, targetUid, grantUri); 20 8536 targetUris.put(grantUri, perm); 21 8537 } 22 8538 23 8539 return perm; 24 8540 } 25 8541 26 8542 private final boolean checkUriPermissionLocked(GrantUri grantUri, int uid, 27 8543 final int modeFlags) { 28 8544 final boolean persistable = (modeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0; 29 8545 final int minStrength = persistable ? UriPermission.STRENGTH_PERSISTABLE 30 8546 : UriPermission.STRENGTH_OWNED; 31 8547 32 8548 // Root gets to do everything. 33 8549 if (uid == 0) { 34 8550 return true; 35 8551 } 36 8552 37 8553 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid); 38 8554 if (perms == null) return false; 39 8555 40 8556 // First look for exact match 41 8557 final UriPermission exactPerm = perms.get(grantUri); 42 8558 if (exactPerm != null && exactPerm.getStrength(modeFlags) >= minStrength) { 43 8559 return true; 44 8560 } 45 8561 46 8562 // No exact match, look for prefixes 47 8563 final int N = perms.size(); 48 8564 for (int i = 0; i < N; i++) { 49 8565 final UriPermission perm = perms.valueAt(i); 50 8566 if (perm.uri.prefix && grantUri.uri.isPathPrefixMatch(perm.uri.uri) 51 8567 && perm.getStrength(modeFlags) >= minStrength) { 52 8568 return true; 53 8569 } 54 8570 } 55 8571 56 8572 return false; 57 8573 } 58 8574 59 8575 /** 60 8576 * @param uri This uri must NOT contain an embedded userId. 61 8577 * @param userId The userId in which the uri is to be resolved. 62 8578 */ 63 8579 @Override 64 8580 public int checkUriPermission(Uri uri, int pid, int uid, 65 8581 final int modeFlags, int userId, IBinder callerToken) { 66 8582 enforceNotIsolatedCaller("checkUriPermission"); 67 8583 68 8584 // Another redirected-binder-call permissions check as in 69 8585 // {@link checkPermissionWithToken}. 70 8586 Identity tlsIdentity = sCallerIdentity.get(); 71 8587 if (tlsIdentity != null && tlsIdentity.token == callerToken) { 72 8588 uid = tlsIdentity.uid; 73 8589 pid = tlsIdentity.pid; 74 8590 } 75 8591 76 8592 // Our own process gets to do everything. 77 8593 if (pid == MY_PID) { 78 8594 return PackageManager.PERMISSION_GRANTED; 79 8595 } 80 8596 synchronized (this) { 81 8597 return checkUriPermissionLocked(new GrantUri(userId, uri, false), uid, modeFlags) 82 8598 ? PackageManager.PERMISSION_GRANTED 83 8599 : PackageManager.PERMISSION_DENIED; 84 8600 } 85 8601 } 86 8602 87 8603 /** 88 8604 * Check if the targetPkg can be granted permission to access uri by 89 8605 * the callingUid using the given modeFlags. Throws a security exception 90 8606 * if callingUid is not allowed to do this. Returns the uid of the target 91 8607 * if the URI permission grant should be performed; returns -1 if it is not 92 8608 * needed (for example targetPkg already has permission to access the URI). 93 8609 * If you already know the uid of the target, you can supply it in 94 8610 * lastTargetUid else set that to -1. 95 8611 */ 96 8612 int checkGrantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri, 97 8613 final int modeFlags, int lastTargetUid) { 98 8614 if (!Intent.isAccessUriMode(modeFlags)) { 99 8615 return -1; 100 8616 } 101 8617 102 8618 if (targetPkg != null) { 103 8619 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 104 8620 "Checking grant " + targetPkg + " permission to " + grantUri); 105 8621 } 106 8622 107 8623 final IPackageManager pm = AppGlobals.getPackageManager(); 108 8624 109 8625 // If this is not a content: uri, we can't do anything with it. 110 8626 if (!ContentResolver.SCHEME_CONTENT.equals(grantUri.uri.getScheme())) { 111 8627 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 112 8628 "Can't grant URI permission for non-content URI: " + grantUri); 113 8629 return -1; 114 8630 } 115 8631 116 8632 final String authority = grantUri.uri.getAuthority(); 117 8633 final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId, 118 8634 MATCH_DEBUG_TRIAGED_MISSING); 119 8635 if (pi == null) { 120 8636 Slog.w(TAG, "No content provider found for permission check: " + 121 8637 grantUri.uri.toSafeString()); 122 8638 return -1; 123 8639 } 124 8640 125 8641 int targetUid = lastTargetUid; 126 8642 if (targetUid < 0 && targetPkg != null) { 127 8643 try { 128 8644 targetUid = pm.getPackageUid(targetPkg, MATCH_DEBUG_TRIAGED_MISSING, 129 8645 UserHandle.getUserId(callingUid)); 130 8646 if (targetUid < 0) { 131 8647 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 132 8648 "Can't grant URI permission no uid for: " + targetPkg); 133 8649 return -1; 134 8650 } 135 8651 } catch (RemoteException ex) { 136 8652 return -1; 137 8653 } 138 8654 } 139 8655 140 8656 // If we're extending a persistable grant, then we always need to create 141 8657 // the grant data structure so that take/release APIs work 142 8658 if ((modeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0) { 143 8659 return targetUid; 144 8660 } 145 8661 146 8662 if (targetUid >= 0) { 147 8663 // First... does the target actually need this permission? 148 8664 if (checkHoldingPermissionsLocked(pm, pi, grantUri, targetUid, modeFlags)) { 149 8665 // No need to grant the target this permission. 150 8666 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 151 8667 "Target " + targetPkg + " already has full permission to " + grantUri); 152 8668 return -1; 153 8669 } 154 8670 } else { 155 8671 // First... there is no target package, so can anyone access it? 156 8672 boolean allowed = pi.exported; 157 8673 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) { 158 8674 if (pi.readPermission != null) { 159 8675 allowed = false; 160 8676 } 161 8677 } 162 8678 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) { 163 8679 if (pi.writePermission != null) { 164 8680 allowed = false; 165 8681 } 166 8682 } 167 8683 if (allowed) { 168 8684 return -1; 169 8685 } 170 8686 } 171 8687 172 8688 /* There is a special cross user grant if: 173 8689 * - The target is on another user. 174 8690 * - Apps on the current user can access the uri without any uid permissions. 175 8691 * In this case, we grant a uri permission, even if the ContentProvider does not normally 176 8692 * grant uri permissions. 177 8693 */ 178 8694 boolean specialCrossUserGrant = UserHandle.getUserId(targetUid) != grantUri.sourceUserId 179 8695 && checkHoldingPermissionsInternalLocked(pm, pi, grantUri, callingUid, 180 8696 modeFlags, false /*without considering the uid permissions*/); 181 8697 182 8698 // Second... is the provider allowing granting of URI permissions? 183 8699 if (!specialCrossUserGrant) { 184 8700 if (!pi.grantUriPermissions) { 185 8701 throw new SecurityException("Provider " + pi.packageName 186 8702 + "/" + pi.name 187 8703 + " does not allow granting of Uri permissions (uri " 188 8704 + grantUri + ")"); 189 8705 } 190 8706 if (pi.uriPermissionPatterns != null) { 191 8707 final int N = pi.uriPermissionPatterns.length; 192 8708 boolean allowed = false; 193 8709 for (int i=0; i<N; i++) { 194 8710 if (pi.uriPermissionPatterns[i] != null 195 8711 && pi.uriPermissionPatterns[i].match(grantUri.uri.getPath())) { 196 8712 allowed = true; 197 8713 break; 198 8714 } 199 8715 } 200 8716 if (!allowed) { 201 8717 throw new SecurityException("Provider " + pi.packageName 202 8718 + "/" + pi.name 203 8719 + " does not allow granting of permission to path of Uri " 204 8720 + grantUri); 205 8721 } 206 8722 } 207 8723 } 208 8724 209 8725 // Third... does the caller itself have permission to access 210 8726 // this uri? 211 8727 final int callingAppId = UserHandle.getAppId(callingUid); 212 8728 if ((callingAppId == SYSTEM_UID) || (callingAppId == ROOT_UID)) { 213 8729 if ("com.android.settings.files".equals(grantUri.uri.getAuthority())) { 214 8730 // Exempted authority for cropping user photos in Settings app 215 8731 } else { 216 8732 Slog.w(TAG, "For security reasons, the system cannot issue a Uri permission" 217 8733 + " grant to " + grantUri + "; use startActivityAsCaller() instead"); 218 8734 return -1; 219 8735 } 220 8736 } 221 8737 if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) { 222 8738 // Require they hold a strong enough Uri permission 223 8739 if (!checkUriPermissionLocked(grantUri, callingUid, modeFlags)) { 224 8740 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(pi.readPermission)) { 225 8741 throw new SecurityException( 226 8742 "UID " + callingUid + " does not have permission to " + grantUri 227 8743 + "; you could obtain access using ACTION_OPEN_DOCUMENT " 228 8744 + "or related APIs"); 229 8745 } else { 230 8746 throw new SecurityException( 231 8747 "UID " + callingUid + " does not have permission to " + grantUri); 232 8748 } 233 8749 } 234 8750 } 235 8751 return targetUid; 236 8752 } 237 8753 238 8754 /** 239 8755 * @param uri This uri must NOT contain an embedded userId. 240 8756 * @param userId The userId in which the uri is to be resolved. 241 8757 */ 242 8758 @Override 243 8759 public int checkGrantUriPermission(int callingUid, String targetPkg, Uri uri, 244 8760 final int modeFlags, int userId) { 245 8761 enforceNotIsolatedCaller("checkGrantUriPermission"); 246 8762 synchronized(this) { 247 8763 return checkGrantUriPermissionLocked(callingUid, targetPkg, 248 8764 new GrantUri(userId, uri, false), modeFlags, -1); 249 8765 } 250 8766 } 251 8767 252 8768 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg, GrantUri grantUri, 253 8769 final int modeFlags, UriPermissionOwner owner) { 254 8770 if (!Intent.isAccessUriMode(modeFlags)) { 255 8771 return; 256 8772 } 257 8773 258 8774 // So here we are: the caller has the assumed permission 259 8775 // to the uri, and the target doesn't. Let's now give this to 260 8776 // the target. 261 8777 262 8778 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 263 8779 "Granting " + targetPkg + "/" + targetUid + " permission to " + grantUri); 264 8780 265 8781 final String authority = grantUri.uri.getAuthority(); 266 8782 final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId, 267 8783 MATCH_DEBUG_TRIAGED_MISSING); 268 8784 if (pi == null) { 269 8785 Slog.w(TAG, "No content provider found for grant: " + grantUri.toSafeString()); 270 8786 return; 271 8787 } 272 8788 273 8789 if ((modeFlags & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0) { 274 8790 grantUri.prefix = true; 275 8791 } 276 8792 final UriPermission perm = findOrCreateUriPermissionLocked( 277 8793 pi.packageName, targetPkg, targetUid, grantUri); 278 8794 perm.grantModes(modeFlags, owner); 279 8795 } 280 8796 281 8797 void grantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri, 282 8798 final int modeFlags, UriPermissionOwner owner, int targetUserId) { 283 8799 if (targetPkg == null) { 284 8800 throw new NullPointerException("targetPkg"); 285 8801 } 286 8802 int targetUid; 287 8803 final IPackageManager pm = AppGlobals.getPackageManager(); 288 8804 try { 289 8805 targetUid = pm.getPackageUid(targetPkg, MATCH_DEBUG_TRIAGED_MISSING, targetUserId); 290 8806 } catch (RemoteException ex) { 291 8807 return; 292 8808 } 293 8809 294 8810 targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, modeFlags, 295 8811 targetUid); 296 8812 if (targetUid < 0) { 297 8813 return; 298 8814 } 299 8815 300 8816 grantUriPermissionUncheckedLocked(targetUid, targetPkg, grantUri, modeFlags, 301 8817 owner); 302 8818 } 303 8819 304 8820 static class NeededUriGrants extends ArrayList<GrantUri> { 305 8821 final String targetPkg; 306 8822 final int targetUid; 307 8823 final int flags; 308 8824 309 8825 NeededUriGrants(String targetPkg, int targetUid, int flags) { 310 8826 this.targetPkg = targetPkg; 311 8827 this.targetUid = targetUid; 312 8828 this.flags = flags; 313 8829 } 314 8830 } 315 8831 316 8832 /** 317 8833 * Like checkGrantUriPermissionLocked, but takes an Intent. 318 8834 */ 319 8835 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid, 320 8836 String targetPkg, Intent intent, int mode, NeededUriGrants needed, int targetUserId) { 321 8837 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 322 8838 "Checking URI perm to data=" + (intent != null ? intent.getData() : null) 323 8839 + " clip=" + (intent != null ? intent.getClipData() : null) 324 8840 + " from " + intent + "; flags=0x" 325 8841 + Integer.toHexString(intent != null ? intent.getFlags() : 0)); 326 8842 327 8843 if (targetPkg == null) { 328 8844 throw new NullPointerException("targetPkg"); 329 8845 } 330 8846 331 8847 if (intent == null) { 332 8848 return null; 333 8849 } 334 8850 Uri data = intent.getData(); 335 8851 ClipData clip = intent.getClipData(); 336 8852 if (data == null && clip == null) { 337 8853 return null; 338 8854 } 339 8855 // Default userId for uris in the intent (if they don't specify it themselves) 340 8856 int contentUserHint = intent.getContentUserHint(); 341 8857 if (contentUserHint == UserHandle.USER_CURRENT) { 342 8858 contentUserHint = UserHandle.getUserId(callingUid); 343 8859 } 344 8860 final IPackageManager pm = AppGlobals.getPackageManager(); 345 8861 int targetUid; 346 8862 if (needed != null) { 347 8863 targetUid = needed.targetUid; 348 8864 } else { 349 8865 try { 350 8866 targetUid = pm.getPackageUid(targetPkg, MATCH_DEBUG_TRIAGED_MISSING, 351 8867 targetUserId); 352 8868 } catch (RemoteException ex) { 353 8869 return null; 354 8870 } 355 8871 if (targetUid < 0) { 356 8872 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 357 8873 "Can't grant URI permission no uid for: " + targetPkg 358 8874 + " on user " + targetUserId); 359 8875 return null; 360 8876 } 361 8877 } 362 8878 if (data != null) { 363 8879 GrantUri grantUri = GrantUri.resolve(contentUserHint, data); 364 8880 targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode, 365 8881 targetUid); 366 8882 if (targetUid > 0) { 367 8883 if (needed == null) { 368 8884 needed = new NeededUriGrants(targetPkg, targetUid, mode); 369 8885 } 370 8886 needed.add(grantUri); 371 8887 } 372 8888 } 373 8889 if (clip != null) { 374 8890 for (int i=0; i<clip.getItemCount(); i++) { 375 8891 Uri uri = clip.getItemAt(i).getUri(); 376 8892 if (uri != null) { 377 8893 GrantUri grantUri = GrantUri.resolve(contentUserHint, uri); 378 8894 targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode, 379 8895 targetUid); 380 8896 if (targetUid > 0) { 381 8897 if (needed == null) { 382 8898 needed = new NeededUriGrants(targetPkg, targetUid, mode); 383 8899 } 384 8900 needed.add(grantUri); 385 8901 } 386 8902 } else { 387 8903 Intent clipIntent = clip.getItemAt(i).getIntent(); 388 8904 if (clipIntent != null) { 389 8905 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked( 390 8906 callingUid, targetPkg, clipIntent, mode, needed, targetUserId); 391 8907 if (newNeeded != null) { 392 8908 needed = newNeeded; 393 8909 } 394 8910 } 395 8911 } 396 8912 } 397 8913 } 398 8914 399 8915 return needed; 400 8916 } 401 8917 402 8918 /** 403 8919 * Like grantUriPermissionUncheckedLocked, but takes an Intent. 404 8920 */ 405 8921 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed, 406 8922 UriPermissionOwner owner) { 407 8923 if (needed != null) { 408 8924 for (int i=0; i<needed.size(); i++) { 409 8925 GrantUri grantUri = needed.get(i); 410 8926 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg, 411 8927 grantUri, needed.flags, owner); 412 8928 } 413 8929 } 414 8930 } 415 8931 416 8932 void grantUriPermissionFromIntentLocked(int callingUid, 417 8933 String targetPkg, Intent intent, UriPermissionOwner owner, int targetUserId) { 418 8934 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, 419 8935 intent, intent != null ? intent.getFlags() : 0, null, targetUserId); 420 8936 if (needed == null) { 421 8937 return; 422 8938 } 423 8939 424 8940 grantUriPermissionUncheckedFromIntentLocked(needed, owner); 425 8941 } 426 8942 427 8943 /** 428 8944 * @param uri This uri must NOT contain an embedded userId. 429 8945 * @param userId The userId in which the uri is to be resolved. 430 8946 */ 431 8947 @Override 432 8948 public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, 433 8949 final int modeFlags, int userId) { 434 8950 enforceNotIsolatedCaller("grantUriPermission"); 435 8951 GrantUri grantUri = new GrantUri(userId, uri, false); 436 8952 synchronized(this) { 437 8953 final ProcessRecord r = getRecordForAppLocked(caller); 438 8954 if (r == null) { 439 8955 throw new SecurityException("Unable to find app for caller " 440 8956 + caller 441 8957 + " when granting permission to uri " + grantUri); 442 8958 } 443 8959 if (targetPkg == null) { 444 8960 throw new IllegalArgumentException("null target"); 445 8961 } 446 8962 if (grantUri == null) { 447 8963 throw new IllegalArgumentException("null uri"); 448 8964 } 449 8965 450 8966 Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION 451 8967 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION 452 8968 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 453 8969 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION); 454 8970 455 8971 grantUriPermissionLocked(r.uid, targetPkg, grantUri, modeFlags, null, 456 8972 UserHandle.getUserId(r.uid)); 457 8973 } 458 8974 } 459 8975 460 8976 void removeUriPermissionIfNeededLocked(UriPermission perm) { 461 8977 if (perm.modeFlags == 0) { 462 8978 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get( 463 8979 perm.targetUid); 464 8980 if (perms != null) { 465 8981 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 466 8982 "Removing " + perm.targetUid + " permission to " + perm.uri); 467 8983 468 8984 perms.remove(perm.uri); 469 8985 if (perms.isEmpty()) { 470 8986 mGrantedUriPermissions.remove(perm.targetUid); 471 8987 } 472 8988 } 473 8989 } 474 8990 } 475 8991 476 8992 private void revokeUriPermissionLocked(String targetPackage, int callingUid, GrantUri grantUri, 477 8993 final int modeFlags) { 478 8994 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 479 8995 "Revoking all granted permissions to " + grantUri); 480 8996 481 8997 final IPackageManager pm = AppGlobals.getPackageManager(); 482 8998 final String authority = grantUri.uri.getAuthority(); 483 8999 final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId, 484 9000 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE); 485 9001 if (pi == null) { 486 9002 Slog.w(TAG, "No content provider found for permission revoke: " 487 9003 + grantUri.toSafeString()); 488 9004 return; 489 9005 } 490 9006 491 9007 // Does the caller have this permission on the URI? 492 9008 if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) { 493 9009 // If they don't have direct access to the URI, then revoke any 494 9010 // ownerless URI permissions that have been granted to them. 495 9011 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(callingUid); 496 9012 if (perms != null) { 497 9013 boolean persistChanged = false; 498 9014 for (int i = perms.size()-1; i >= 0; i--) { 499 9015 final UriPermission perm = perms.valueAt(i); 500 9016 if (targetPackage != null && !targetPackage.equals(perm.targetPkg)) { 501 9017 continue; 502 9018 } 503 9019 if (perm.uri.sourceUserId == grantUri.sourceUserId 504 9020 && perm.uri.uri.isPathPrefixMatch(grantUri.uri)) { 505 9021 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 506 9022 "Revoking non-owned " + perm.targetUid 507 9023 + " permission to " + perm.uri); 508 9024 persistChanged |= perm.revokeModes( 509 9025 modeFlags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION, false); 510 9026 if (perm.modeFlags == 0) { 511 9027 perms.removeAt(i); 512 9028 } 513 9029 } 514 9030 } 515 9031 if (perms.isEmpty()) { 516 9032 mGrantedUriPermissions.remove(callingUid); 517 9033 } 518 9034 if (persistChanged) { 519 9035 schedulePersistUriGrants(); 520 9036 } 521 9037 } 522 9038 return; 523 9039 } 524 9040 525 9041 boolean persistChanged = false; 526 9042 527 9043 // Go through all of the permissions and remove any that match. 528 9044 for (int i = mGrantedUriPermissions.size()-1; i >= 0; i--) { 529 9045 final int targetUid = mGrantedUriPermissions.keyAt(i); 530 9046 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 531 9047 532 9048 for (int j = perms.size()-1; j >= 0; j--) { 533 9049 final UriPermission perm = perms.valueAt(j); 534 9050 if (targetPackage != null && !targetPackage.equals(perm.targetPkg)) { 535 9051 continue; 536 9052 } 537 9053 if (perm.uri.sourceUserId == grantUri.sourceUserId 538 9054 && perm.uri.uri.isPathPrefixMatch(grantUri.uri)) { 539 9055 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 540 9056 "Revoking " + perm.targetUid + " permission to " + perm.uri); 541 9057 persistChanged |= perm.revokeModes( 542 9058 modeFlags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION, 543 9059 targetPackage == null); 544 9060 if (perm.modeFlags == 0) { 545 9061 perms.removeAt(j); 546 9062 } 547 9063 } 548 9064 } 549 9065 550 9066 if (perms.isEmpty()) { 551 9067 mGrantedUriPermissions.removeAt(i); 552 9068 } 553 9069 } 554 9070 555 9071 if (persistChanged) { 556 9072 schedulePersistUriGrants(); 557 9073 } 558 9074 } 559 9075 560 9076 /** 561 9077 * @param uri This uri must NOT contain an embedded userId. 562 9078 * @param userId The userId in which the uri is to be resolved. 563 9079 */ 564 9080 @Override 565 9081 public void revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, 566 9082 final int modeFlags, int userId) { 567 9083 enforceNotIsolatedCaller("revokeUriPermission"); 568 9084 synchronized(this) { 569 9085 final ProcessRecord r = getRecordForAppLocked(caller); 570 9086 if (r == null) { 571 9087 throw new SecurityException("Unable to find app for caller " 572 9088 + caller 573 9089 + " when revoking permission to uri " + uri); 574 9090 } 575 9091 if (uri == null) { 576 9092 Slog.w(TAG, "revokeUriPermission: null uri"); 577 9093 return; 578 9094 } 579 9095 580 9096 if (!Intent.isAccessUriMode(modeFlags)) { 581 9097 return; 582 9098 } 583 9099 584 9100 final String authority = uri.getAuthority(); 585 9101 final ProviderInfo pi = getProviderInfoLocked(authority, userId, 586 9102 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE); 587 9103 if (pi == null) { 588 9104 Slog.w(TAG, "No content provider found for permission revoke: " 589 9105 + uri.toSafeString()); 590 9106 return; 591 9107 } 592 9108 593 9109 revokeUriPermissionLocked(targetPackage, r.uid, new GrantUri(userId, uri, false), 594 9110 modeFlags); 595 9111 } 596 9112 } 597 9113 598 9114 /** 599 9115 * Remove any {@link UriPermission} granted <em>from</em> or <em>to</em> the 600 9116 * given package. 601 9117 * 602 9118 * @param packageName Package name to match, or {@code null} to apply to all 603 9119 * packages. 604 9120 * @param userHandle User to match, or {@link UserHandle#USER_ALL} to apply 605 9121 * to all users. 606 9122 * @param persistable If persistable grants should be removed. 607 9123 */ 608 9124 private void removeUriPermissionsForPackageLocked( 609 9125 String packageName, int userHandle, boolean persistable) { 610 9126 if (userHandle == UserHandle.USER_ALL && packageName == null) { 611 9127 throw new IllegalArgumentException("Must narrow by either package or user"); 612 9128 } 613 9129 614 9130 boolean persistChanged = false; 615 9131 616 9132 int N = mGrantedUriPermissions.size(); 617 9133 for (int i = 0; i < N; i++) { 618 9134 final int targetUid = mGrantedUriPermissions.keyAt(i); 619 9135 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 620 9136 621 9137 // Only inspect grants matching user 622 9138 if (userHandle == UserHandle.USER_ALL 623 9139 || userHandle == UserHandle.getUserId(targetUid)) { 624 9140 for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) { 625 9141 final UriPermission perm = it.next(); 626 9142 627 9143 // Only inspect grants matching package 628 9144 if (packageName == null || perm.sourcePkg.equals(packageName) 629 9145 || perm.targetPkg.equals(packageName)) { 630 9146 // Hacky solution as part of fixing a security bug; ignore 631 9147 // grants associated with DownloadManager so we don't have 632 9148 // to immediately launch it to regrant the permissions 633 9149 if (Downloads.Impl.AUTHORITY.equals(perm.uri.uri.getAuthority()) 634 9150 && !persistable) continue; 635 9151 636 9152 persistChanged |= perm.revokeModes(persistable 637 9153 ? ~0 : ~Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION, true); 638 9154 639 9155 // Only remove when no modes remain; any persisted grants 640 9156 // will keep this alive. 641 9157 if (perm.modeFlags == 0) { 642 9158 it.remove(); 643 9159 } 644 9160 } 645 9161 } 646 9162 647 9163 if (perms.isEmpty()) { 648 9164 mGrantedUriPermissions.remove(targetUid); 649 9165 N--; 650 9166 i--; 651 9167 } 652 9168 } 653 9169 } 654 9170 655 9171 if (persistChanged) { 656 9172 schedulePersistUriGrants(); 657 9173 } 658 9174 } 659 9175 660 9176 @Override 661 9177 public IBinder newUriPermissionOwner(String name) { 662 9178 enforceNotIsolatedCaller("newUriPermissionOwner"); 663 9179 synchronized(this) { 664 9180 UriPermissionOwner owner = new UriPermissionOwner(this, name); 665 9181 return owner.getExternalTokenLocked(); 666 9182 } 667 9183 } 668 9184 669 9185 @Override 670 9186 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) { 671 9187 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity"); 672 9188 synchronized(this) { 673 9189 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken); 674 9190 if (r == null) { 675 9191 throw new IllegalArgumentException("Activity does not exist; token=" 676 9192 + activityToken); 677 9193 } 678 9194 return r.getUriPermissionsLocked().getExternalTokenLocked(); 679 9195 } 680 9196 } 681 9197 /** 682 9198 * @param uri This uri must NOT contain an embedded userId. 683 9199 * @param sourceUserId The userId in which the uri is to be resolved. 684 9200 * @param targetUserId The userId of the app that receives the grant. 685 9201 */ 686 9202 @Override 687 9203 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg, Uri uri, 688 9204 final int modeFlags, int sourceUserId, int targetUserId) { 689 9205 targetUserId = mUserController.handleIncomingUser(Binder.getCallingPid(), 690 9206 Binder.getCallingUid(), targetUserId, false, ALLOW_FULL_ONLY, 691 9207 "grantUriPermissionFromOwner", null); 692 9208 synchronized(this) { 693 9209 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token); 694 9210 if (owner == null) { 695 9211 throw new IllegalArgumentException("Unknown owner: " + token); 696 9212 } 697 9213 if (fromUid != Binder.getCallingUid()) { 698 9214 if (Binder.getCallingUid() != myUid()) { 699 9215 // Only system code can grant URI permissions on behalf 700 9216 // of other users. 701 9217 throw new SecurityException("nice try"); 702 9218 } 703 9219 } 704 9220 if (targetPkg == null) { 705 9221 throw new IllegalArgumentException("null target"); 706 9222 } 707 9223 if (uri == null) { 708 9224 throw new IllegalArgumentException("null uri"); 709 9225 } 710 9226 711 9227 grantUriPermissionLocked(fromUid, targetPkg, new GrantUri(sourceUserId, uri, false), 712 9228 modeFlags, owner, targetUserId); 713 9229 } 714 9230 } 715 9231 716 9232 /** 717 9233 * @param uri This uri must NOT contain an embedded userId. 718 9234 * @param userId The userId in which the uri is to be resolved. 719 9235 */ 720 9236 @Override 721 9237 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode, int userId) { 722 9238 synchronized(this) { 723 9239 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token); 724 9240 if (owner == null) { 725 9241 throw new IllegalArgumentException("Unknown owner: " + token); 726 9242 } 727 9243 728 9244 if (uri == null) { 729 9245 owner.removeUriPermissionsLocked(mode); 730 9246 } else { 731 9247 final boolean prefix = (mode & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0; 732 9248 owner.removeUriPermissionLocked(new GrantUri(userId, uri, prefix), mode); 733 9249 } 734 9250 } 735 9251 } 736 9252 737 9253 private void schedulePersistUriGrants() { 738 9254 if (!mHandler.hasMessages(PERSIST_URI_GRANTS_MSG)) { 739 9255 mHandler.sendMessageDelayed(mHandler.obtainMessage(PERSIST_URI_GRANTS_MSG), 740 9256 10 * DateUtils.SECOND_IN_MILLIS); 741 9257 } 742 9258 } 743 9259 744 9260 private void writeGrantedUriPermissions() { 745 9261 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, "writeGrantedUriPermissions()"); 746 9262 747 9263 // Snapshot permissions so we can persist without lock 748 9264 ArrayList<UriPermission.Snapshot> persist = Lists.newArrayList(); 749 9265 synchronized (this) { 750 9266 final int size = mGrantedUriPermissions.size(); 751 9267 for (int i = 0; i < size; i++) { 752 9268 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 753 9269 for (UriPermission perm : perms.values()) { 754 9270 if (perm.persistedModeFlags != 0) { 755 9271 persist.add(perm.snapshot()); 756 9272 } 757 9273 } 758 9274 } 759 9275 } 760 9276 761 9277 FileOutputStream fos = null; 762 9278 try { 763 9279 fos = mGrantFile.startWrite(); 764 9280 765 9281 XmlSerializer out = new FastXmlSerializer(); 766 9282 out.setOutput(fos, StandardCharsets.UTF_8.name()); 767 9283 out.startDocument(null, true); 768 9284 out.startTag(null, TAG_URI_GRANTS); 769 9285 for (UriPermission.Snapshot perm : persist) { 770 9286 out.startTag(null, TAG_URI_GRANT); 771 9287 writeIntAttribute(out, ATTR_SOURCE_USER_ID, perm.uri.sourceUserId); 772 9288 writeIntAttribute(out, ATTR_TARGET_USER_ID, perm.targetUserId); 773 9289 out.attribute(null, ATTR_SOURCE_PKG, perm.sourcePkg); 774 9290 out.attribute(null, ATTR_TARGET_PKG, perm.targetPkg); 775 9291 out.attribute(null, ATTR_URI, String.valueOf(perm.uri.uri)); 776 9292 writeBooleanAttribute(out, ATTR_PREFIX, perm.uri.prefix); 777 9293 writeIntAttribute(out, ATTR_MODE_FLAGS, perm.persistedModeFlags); 778 9294 writeLongAttribute(out, ATTR_CREATED_TIME, perm.persistedCreateTime); 779 9295 out.endTag(null, TAG_URI_GRANT); 780 9296 } 781 9297 out.endTag(null, TAG_URI_GRANTS); 782 9298 out.endDocument(); 783 9299 784 9300 mGrantFile.finishWrite(fos); 785 9301 } catch (IOException e) { 786 9302 if (fos != null) { 787 9303 mGrantFile.failWrite(fos); 788 9304 } 789 9305 } 790 9306 } 791 9307 792 9308 private void readGrantedUriPermissionsLocked() { 793 9309 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, "readGrantedUriPermissions()"); 794 9310 795 9311 final long now = System.currentTimeMillis(); 796 9312 797 9313 FileInputStream fis = null; 798 9314 try { 799 9315 fis = mGrantFile.openRead(); 800 9316 final XmlPullParser in = Xml.newPullParser(); 801 9317 in.setInput(fis, StandardCharsets.UTF_8.name()); 802 9318 803 9319 int type; 804 9320 while ((type = in.next()) != END_DOCUMENT) { 805 9321 final String tag = in.getName(); 806 9322 if (type == START_TAG) { 807 9323 if (TAG_URI_GRANT.equals(tag)) { 808 9324 final int sourceUserId; 809 9325 final int targetUserId; 810 9326 final int userHandle = readIntAttribute(in, 811 9327 ATTR_USER_HANDLE, UserHandle.USER_NULL); 812 9328 if (userHandle != UserHandle.USER_NULL) { 813 9329 // For backwards compatibility. 814 9330 sourceUserId = userHandle; 815 9331 targetUserId = userHandle; 816 9332 } else { 817 9333 sourceUserId = readIntAttribute(in, ATTR_SOURCE_USER_ID); 818 9334 targetUserId = readIntAttribute(in, ATTR_TARGET_USER_ID); 819 9335 } 820 9336 final String sourcePkg = in.getAttributeValue(null, ATTR_SOURCE_PKG); 821 9337 final String targetPkg = in.getAttributeValue(null, ATTR_TARGET_PKG); 822 9338 final Uri uri = Uri.parse(in.getAttributeValue(null, ATTR_URI)); 823 9339 final boolean prefix = readBooleanAttribute(in, ATTR_PREFIX); 824 9340 final int modeFlags = readIntAttribute(in, ATTR_MODE_FLAGS); 825 9341 final long createdTime = readLongAttribute(in, ATTR_CREATED_TIME, now); 826 9342 827 9343 // Sanity check that provider still belongs to source package 828 9344 // Both direct boot aware and unaware packages are fine as we 829 9345 // will do filtering at query time to avoid multiple parsing. 830 9346 final ProviderInfo pi = getProviderInfoLocked( 831 9347 uri.getAuthority(), sourceUserId, MATCH_DIRECT_BOOT_AWARE 832 9348 | MATCH_DIRECT_BOOT_UNAWARE); 833 9349 if (pi != null && sourcePkg.equals(pi.packageName)) { 834 9350 int targetUid = -1; 835 9351 try { 836 9352 targetUid = AppGlobals.getPackageManager().getPackageUid( 837 9353 targetPkg, MATCH_UNINSTALLED_PACKAGES, targetUserId); 838 9354 } catch (RemoteException e) { 839 9355 } 840 9356 if (targetUid != -1) { 841 9357 final UriPermission perm = findOrCreateUriPermissionLocked( 842 9358 sourcePkg, targetPkg, targetUid, 843 9359 new GrantUri(sourceUserId, uri, prefix)); 844 9360 perm.initPersistedModes(modeFlags, createdTime); 845 9361 } 846 9362 } else { 847 9363 Slog.w(TAG, "Persisted grant for " + uri + " had source " + sourcePkg 848 9364 + " but instead found " + pi); 849 9365 } 850 9366 } 851 9367 } 852 9368 } 853 9369 } catch (FileNotFoundException e) { 854 9370 // Missing grants is okay 855 9371 } catch (IOException e) { 856 9372 Slog.wtf(TAG, "Failed reading Uri grants", e); 857 9373 } catch (XmlPullParserException e) { 858 9374 Slog.wtf(TAG, "Failed reading Uri grants", e); 859 9375 } finally { 860 9376 IoUtils.closeQuietly(fis); 861 9377 } 862 9378 } 863 9379 864 9380 /** 865 9381 * @param uri This uri must NOT contain an embedded userId. 866 9382 * @param userId The userId in which the uri is to be resolved. 867 9383 */ 868 9384 @Override 869 9385 public void takePersistableUriPermission(Uri uri, final int modeFlags, int userId) { 870 9386 enforceNotIsolatedCaller("takePersistableUriPermission"); 871 9387 872 9388 Preconditions.checkFlagsArgument(modeFlags, 873 9389 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 874 9390 875 9391 synchronized (this) { 876 9392 final int callingUid = Binder.getCallingUid(); 877 9393 boolean persistChanged = false; 878 9394 GrantUri grantUri = new GrantUri(userId, uri, false); 879 9395 880 9396 UriPermission exactPerm = findUriPermissionLocked(callingUid, 881 9397 new GrantUri(userId, uri, false)); 882 9398 UriPermission prefixPerm = findUriPermissionLocked(callingUid, 883 9399 new GrantUri(userId, uri, true)); 884 9400 885 9401 final boolean exactValid = (exactPerm != null) 886 9402 && ((modeFlags & exactPerm.persistableModeFlags) == modeFlags); 887 9403 final boolean prefixValid = (prefixPerm != null) 888 9404 && ((modeFlags & prefixPerm.persistableModeFlags) == modeFlags); 889 9405 890 9406 if (!(exactValid || prefixValid)) { 891 9407 throw new SecurityException("No persistable permission grants found for UID " 892 9408 + callingUid + " and Uri " + grantUri.toSafeString()); 893 9409 } 894 9410 895 9411 if (exactValid) { 896 9412 persistChanged |= exactPerm.takePersistableModes(modeFlags); 897 9413 } 898 9414 if (prefixValid) { 899 9415 persistChanged |= prefixPerm.takePersistableModes(modeFlags); 900 9416 } 901 9417 902 9418 persistChanged |= maybePrunePersistedUriGrantsLocked(callingUid); 903 9419 904 9420 if (persistChanged) { 905 9421 schedulePersistUriGrants(); 906 9422 } 907 9423 } 908 9424 } 909 9425 910 9426 /** 911 9427 * @param uri This uri must NOT contain an embedded userId. 912 9428 * @param userId The userId in which the uri is to be resolved. 913 9429 */ 914 9430 @Override 915 9431 public void releasePersistableUriPermission(Uri uri, final int modeFlags, int userId) { 916 9432 enforceNotIsolatedCaller("releasePersistableUriPermission"); 917 9433 918 9434 Preconditions.checkFlagsArgument(modeFlags, 919 9435 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 920 9436 921 9437 synchronized (this) { 922 9438 final int callingUid = Binder.getCallingUid(); 923 9439 boolean persistChanged = false; 924 9440 925 9441 UriPermission exactPerm = findUriPermissionLocked(callingUid, 926 9442 new GrantUri(userId, uri, false)); 927 9443 UriPermission prefixPerm = findUriPermissionLocked(callingUid, 928 9444 new GrantUri(userId, uri, true)); 929 9445 if (exactPerm == null && prefixPerm == null) { 930 9446 throw new SecurityException("No permission grants found for UID " + callingUid 931 9447 + " and Uri " + uri.toSafeString()); 932 9448 } 933 9449 934 9450 if (exactPerm != null) { 935 9451 persistChanged |= exactPerm.releasePersistableModes(modeFlags); 936 9452 removeUriPermissionIfNeededLocked(exactPerm); 937 9453 } 938 9454 if (prefixPerm != null) { 939 9455 persistChanged |= prefixPerm.releasePersistableModes(modeFlags); 940 9456 removeUriPermissionIfNeededLocked(prefixPerm); 941 9457 } 942 9458 943 9459 if (persistChanged) { 944 9460 schedulePersistUriGrants(); 945 9461 } 946 9462 } 947 9463 } 948 9464 949 9465 /** 950 9466 * Prune any older {@link UriPermission} for the given UID until outstanding 951 9467 * persisted grants are below {@link #MAX_PERSISTED_URI_GRANTS}. 952 9468 * 953 9469 * @return if any mutations occured that require persisting. 954 9470 */ 955 9471 private boolean maybePrunePersistedUriGrantsLocked(int uid) { 956 9472 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid); 957 9473 if (perms == null) return false; 958 9474 if (perms.size() < MAX_PERSISTED_URI_GRANTS) return false; 959 9475 960 9476 final ArrayList<UriPermission> persisted = Lists.newArrayList(); 961 9477 for (UriPermission perm : perms.values()) { 962 9478 if (perm.persistedModeFlags != 0) { 963 9479 persisted.add(perm); 964 9480 } 965 9481 } 966 9482 967 9483 final int trimCount = persisted.size() - MAX_PERSISTED_URI_GRANTS; 968 9484 if (trimCount <= 0) return false; 969 9485 970 9486 Collections.sort(persisted, new UriPermission.PersistedTimeComparator()); 971 9487 for (int i = 0; i < trimCount; i++) { 972 9488 final UriPermission perm = persisted.get(i); 973 9489 974 9490 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 975 9491 "Trimming grant created at " + perm.persistedCreateTime); 976 9492 977 9493 perm.releasePersistableModes(~0); 978 9494 removeUriPermissionIfNeededLocked(perm); 979 9495 } 980 9496 981 9497 return true; 982 9498 } 983 9499 984 9500 @Override 985 9501 public ParceledListSlice<android.content.UriPermission> getPersistedUriPermissions( 986 9502 String packageName, boolean incoming) { 987 9503 enforceNotIsolatedCaller("getPersistedUriPermissions"); 988 9504 Preconditions.checkNotNull(packageName, "packageName"); 989 9505 990 9506 final int callingUid = Binder.getCallingUid(); 991 9507 final int callingUserId = UserHandle.getUserId(callingUid); 992 9508 final IPackageManager pm = AppGlobals.getPackageManager(); 993 9509 try { 994 9510 final int packageUid = pm.getPackageUid(packageName, 995 9511 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, callingUserId); 996 9512 if (packageUid != callingUid) { 997 9513 throw new SecurityException( 998 9514 "Package " + packageName + " does not belong to calling UID " + callingUid); 999 9515 } 1000 9516 } catch (RemoteException e) { 1001 9517 throw new SecurityException("Failed to verify package name ownership"); 1002 9518 } 1003 9519 1004 9520 final ArrayList<android.content.UriPermission> result = Lists.newArrayList(); 1005 9521 synchronized (this) { 1006 9522 if (incoming) { 1007 9523 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get( 1008 9524 callingUid); 1009 9525 if (perms == null) { 1010 9526 Slog.w(TAG, "No permission grants found for " + packageName); 1011 9527 } else { 1012 9528 for (UriPermission perm : perms.values()) { 1013 9529 if (packageName.equals(perm.targetPkg) && perm.persistedModeFlags != 0) { 1014 9530 result.add(perm.buildPersistedPublicApiObject()); 1015 9531 } 1016 9532 } 1017 9533 } 1018 9534 } else { 1019 9535 final int size = mGrantedUriPermissions.size(); 1020 9536 for (int i = 0; i < size; i++) { 1021 9537 final ArrayMap<GrantUri, UriPermission> perms = 1022 9538 mGrantedUriPermissions.valueAt(i); 1023 9539 for (UriPermission perm : perms.values()) { 1024 9540 if (packageName.equals(perm.sourcePkg) && perm.persistedModeFlags != 0) { 1025 9541 result.add(perm.buildPersistedPublicApiObject()); 1026 9542 } 1027 9543 } 1028 9544 } 1029 9545 } 1030 9546 } 1031 9547 return new ParceledListSlice<android.content.UriPermission>(result); 1032 9548 } 1033 9549 1034 9550 @Override 1035 9551 public ParceledListSlice<android.content.UriPermission> getGrantedUriPermissions( 1036 9552 String packageName, int userId) { 1037 9553 enforceCallingPermission(android.Manifest.permission.GET_APP_GRANTED_URI_PERMISSIONS, 1038 9554 "getGrantedUriPermissions"); 1039 9555 1040 9556 final ArrayList<android.content.UriPermission> result = Lists.newArrayList(); 1041 9557 synchronized (this) { 1042 9558 final int size = mGrantedUriPermissions.size(); 1043 9559 for (int i = 0; i < size; i++) { 1044 9560 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 1045 9561 for (UriPermission perm : perms.values()) { 1046 9562 if (packageName.equals(perm.targetPkg) && perm.targetUserId == userId 1047 9563 && perm.persistedModeFlags != 0) { 1048 9564 result.add(perm.buildPersistedPublicApiObject()); 1049 9565 } 1050 9566 } 1051 9567 } 1052 9568 } 1053 9569 return new ParceledListSlice<android.content.UriPermission>(result); 1054 9570 } 1055 9571 1056 9572 @Override 1057 9573 public void clearGrantedUriPermissions(String packageName, int userId) { 1058 9574 enforceCallingPermission(android.Manifest.permission.CLEAR_APP_GRANTED_URI_PERMISSIONS, 1059 9575 "clearGrantedUriPermissions"); 1060 9576 removeUriPermissionsForPackageLocked(packageName, userId, true); 1061 9577 } 1062 9578
显示等待debug
1 9579 @Override 2 9580 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) { 3 9581 synchronized (this) { 4 9582 ProcessRecord app = 5 9583 who != null ? getRecordForAppLocked(who) : null; 6 9584 if (app == null) return; 7 9585 8 9586 Message msg = Message.obtain(); 9 9587 msg.what = WAIT_FOR_DEBUGGER_UI_MSG; 10 9588 msg.obj = app; 11 9589 msg.arg1 = waiting ? 1 : 0; 12 9590 mUiHandler.sendMessage(msg); 13 9591 } 14 9592 }
获取mem info
1 9594 @Override 2 9595 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) { 3 9596 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ); 4 9597 final long cachedAppMem = mProcessList.getMemLevel(ProcessList.CACHED_APP_MIN_ADJ); 5 9598 outInfo.availMem = getFreeMemory(); 6 9599 outInfo.totalMem = getTotalMemory(); 7 9600 outInfo.threshold = homeAppMem; 8 9601 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((cachedAppMem-homeAppMem)/2)); 9 9602 outInfo.hiddenAppThreshold = cachedAppMem; 10 9603 outInfo.secondaryServerThreshold = mProcessList.getMemLevel( 11 9604 ProcessList.SERVICE_ADJ); 12 9605 outInfo.visibleAppThreshold = mProcessList.getMemLevel( 13 9606 ProcessList.VISIBLE_APP_ADJ); 14 9607 outInfo.foregroundAppThreshold = mProcessList.getMemLevel( 15 9608 ProcessList.FOREGROUND_APP_ADJ); 16 9609 }
app task stack相关
1 9611 // ========================================================= 2 9612 // TASK MANAGEMENT 3 9613 // ========================================================= 4 9614 5 9615 @Override 6 9616 public List<IBinder> getAppTasks(String callingPackage) { 7 9617 int callingUid = Binder.getCallingUid(); 8 9618 long ident = Binder.clearCallingIdentity(); 9 9619 10 9620 synchronized(this) { 11 9621 ArrayList<IBinder> list = new ArrayList<IBinder>(); 12 9622 try { 13 9623 if (DEBUG_ALL) Slog.v(TAG, "getAppTasks"); 14 9624 15 9625 final int N = mRecentTasks.size(); 16 9626 for (int i = 0; i < N; i++) { 17 9627 TaskRecord tr = mRecentTasks.get(i); 18 9628 // Skip tasks that do not match the caller. We don't need to verify 19 9629 // callingPackage, because we are also limiting to callingUid and know 20 9630 // that will limit to the correct security sandbox. 21 9631 if (tr.effectiveUid != callingUid) { 22 9632 continue; 23 9633 } 24 9634 Intent intent = tr.getBaseIntent(); 25 9635 if (intent == null || 26 9636 !callingPackage.equals(intent.getComponent().getPackageName())) { 27 9637 continue; 28 9638 } 29 9639 ActivityManager.RecentTaskInfo taskInfo = 30 9640 createRecentTaskInfoFromTaskRecord(tr); 31 9641 AppTaskImpl taskImpl = new AppTaskImpl(taskInfo.persistentId, callingUid); 32 9642 list.add(taskImpl.asBinder()); 33 9643 } 34 9644 } finally { 35 9645 Binder.restoreCallingIdentity(ident); 36 9646 } 37 9647 return list; 38 9648 } 39 9649 } 40 9650 41 9651 @Override 42 9652 public List<RunningTaskInfo> getTasks(int maxNum, int flags) { 43 9653 final int callingUid = Binder.getCallingUid(); 44 9654 ArrayList<RunningTaskInfo> list = new ArrayList<RunningTaskInfo>(); 45 9655 46 9656 synchronized(this) { 47 9657 if (DEBUG_ALL) Slog.v( 48 9658 TAG, "getTasks: max=" + maxNum + ", flags=" + flags); 49 9659 50 9660 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(), 51 9661 callingUid); 52 9662 53 9663 // TODO: Improve with MRU list from all ActivityStacks. 54 9664 mStackSupervisor.getTasksLocked(maxNum, list, callingUid, allowed); 55 9665 } 56 9666 57 9667 return list; 58 9668 } 59 9669 60 9670 /** 61 9671 * Creates a new RecentTaskInfo from a TaskRecord. 62 9672 */ 63 9673 private ActivityManager.RecentTaskInfo createRecentTaskInfoFromTaskRecord(TaskRecord tr) { 64 9674 // Update the task description to reflect any changes in the task stack 65 9675 tr.updateTaskDescription(); 66 9676 67 9677 // Compose the recent task info 68 9678 ActivityManager.RecentTaskInfo rti = new ActivityManager.RecentTaskInfo(); 69 9679 rti.id = tr.getTopActivity() == null ? INVALID_TASK_ID : tr.taskId; 70 9680 rti.persistentId = tr.taskId; 71 9681 rti.baseIntent = new Intent(tr.getBaseIntent()); 72 9682 rti.origActivity = tr.origActivity; 73 9683 rti.realActivity = tr.realActivity; 74 9684 rti.description = tr.lastDescription; 75 9685 rti.stackId = tr.getStackId(); 76 9686 rti.userId = tr.userId; 77 9687 rti.taskDescription = new ActivityManager.TaskDescription(tr.lastTaskDescription); 78 9688 rti.firstActiveTime = tr.firstActiveTime; 79 9689 rti.lastActiveTime = tr.lastActiveTime; 80 9690 rti.affiliatedTaskId = tr.mAffiliatedTaskId; 81 9691 rti.affiliatedTaskColor = tr.mAffiliatedTaskColor; 82 9692 rti.numActivities = 0; 83 9693 if (tr.mBounds != null) { 84 9694 rti.bounds = new Rect(tr.mBounds); 85 9695 } 86 9696 rti.supportsSplitScreenMultiWindow = tr.supportsSplitScreen(); 87 9697 rti.resizeMode = tr.mResizeMode; 88 9698 89 9699 ActivityRecord base = null; 90 9700 ActivityRecord top = null; 91 9701 ActivityRecord tmp; 92 9702 93 9703 for (int i = tr.mActivities.size() - 1; i >= 0; --i) { 94 9704 tmp = tr.mActivities.get(i); 95 9705 if (tmp.finishing) { 96 9706 continue; 97 9707 } 98 9708 base = tmp; 99 9709 if (top == null || (top.state == ActivityState.INITIALIZING)) { 100 9710 top = base; 101 9711 } 102 9712 rti.numActivities++; 103 9713 } 104 9714 105 9715 rti.baseActivity = (base != null) ? base.intent.getComponent() : null; 106 9716 rti.topActivity = (top != null) ? top.intent.getComponent() : null; 107 9717 108 9718 return rti; 109 9719 } 110 9720 111 9721 private boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) { 112 9722 boolean allowed = checkPermission(android.Manifest.permission.REAL_GET_TASKS, 113 9723 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED; 114 9724 if (!allowed) { 115 9725 if (checkPermission(android.Manifest.permission.GET_TASKS, 116 9726 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) { 117 9727 // Temporary compatibility: some existing apps on the system image may 118 9728 // still be requesting the old permission and not switched to the new 119 9729 // one; if so, we'll still allow them full access. This means we need 120 9730 // to see if they are holding the old permission and are a system app. 121 9731 try { 122 9732 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) { 123 9733 allowed = true; 124 9734 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid 125 9735 + " is using old GET_TASKS but privileged; allowing"); 126 9736 } 127 9737 } catch (RemoteException e) { 128 9738 } 129 9739 } 130 9740 } 131 9741 if (!allowed) { 132 9742 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid 133 9743 + " does not hold REAL_GET_TASKS; limiting output"); 134 9744 } 135 9745 return allowed; 136 9746 } 137 9747 138 9748 @Override 139 9749 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags, 140 9750 int userId) { 141 9751 final int callingUid = Binder.getCallingUid(); 142 9752 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, userId, 143 9753 false, ALLOW_FULL_ONLY, "getRecentTasks", null); 144 9754 145 9755 final boolean includeProfiles = (flags & ActivityManager.RECENT_INCLUDE_PROFILES) != 0; 146 9756 final boolean withExcluded = (flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0; 147 9757 synchronized (this) { 148 9758 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(), 149 9759 callingUid); 150 9760 final boolean detailed = checkCallingPermission( 151 9761 android.Manifest.permission.GET_DETAILED_TASKS) 152 9762 == PackageManager.PERMISSION_GRANTED; 153 9763 154 9764 if (!isUserRunning(userId, ActivityManager.FLAG_AND_UNLOCKED)) { 155 9765 Slog.i(TAG, "user " + userId + " is still locked. Cannot load recents"); 156 9766 return ParceledListSlice.emptyList(); 157 9767 } 158 9768 mRecentTasks.loadUserRecentsLocked(userId); 159 9769 160 9770 final int recentsCount = mRecentTasks.size(); 161 9771 ArrayList<ActivityManager.RecentTaskInfo> res = 162 9772 new ArrayList<>(maxNum < recentsCount ? maxNum : recentsCount); 163 9773 164 9774 final Set<Integer> includedUsers; 165 9775 if (includeProfiles) { 166 9776 includedUsers = mUserController.getProfileIds(userId); 167 9777 } else { 168 9778 includedUsers = new HashSet<>(); 169 9779 } 170 9780 includedUsers.add(Integer.valueOf(userId)); 171 9781 172 9782 for (int i = 0; i < recentsCount && maxNum > 0; i++) { 173 9783 TaskRecord tr = mRecentTasks.get(i); 174 9784 // Only add calling user or related users recent tasks 175 9785 if (!includedUsers.contains(Integer.valueOf(tr.userId))) { 176 9786 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not user: " + tr); 177 9787 continue; 178 9788 } 179 9789 180 9790 if (tr.realActivitySuspended) { 181 9791 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, activity suspended: " + tr); 182 9792 continue; 183 9793 } 184 9794 185 9795 // Return the entry if desired by the caller. We always return 186 9796 // the first entry, because callers always expect this to be the 187 9797 // foreground app. We may filter others if the caller has 188 9798 // not supplied RECENT_WITH_EXCLUDED and there is some reason 189 9799 // we should exclude the entry. 190 9800 191 9801 if (i == 0 192 9802 || withExcluded 193 9803 || (tr.intent == null) 194 9804 || ((tr.intent.getFlags() & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) 195 9805 == 0)) { 196 9806 if (!allowed) { 197 9807 // If the caller doesn't have the GET_TASKS permission, then only 198 9808 // allow them to see a small subset of tasks -- their own and home. 199 9809 if (!tr.isHomeTask() && tr.effectiveUid != callingUid) { 200 9810 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not allowed: " + tr); 201 9811 continue; 202 9812 } 203 9813 } 204 9814 final ActivityStack stack = tr.getStack(); 205 9815 if ((flags & ActivityManager.RECENT_IGNORE_HOME_AND_RECENTS_STACK_TASKS) != 0) { 206 9816 if (stack != null && stack.isHomeOrRecentsStack()) { 207 9817 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, 208 9818 "Skipping, home or recents stack task: " + tr); 209 9819 continue; 210 9820 } 211 9821 } 212 9822 if ((flags & ActivityManager.RECENT_INGORE_DOCKED_STACK_TOP_TASK) != 0) { 213 9823 if (stack != null && stack.isDockedStack() && stack.topTask() == tr) { 214 9824 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, 215 9825 "Skipping, top task in docked stack: " + tr); 216 9826 continue; 217 9827 } 218 9828 } 219 9829 if ((flags & ActivityManager.RECENT_INGORE_PINNED_STACK_TASKS) != 0) { 220 9830 if (stack != null && stack.isPinnedStack()) { 221 9831 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, 222 9832 "Skipping, pinned stack task: " + tr); 223 9833 continue; 224 9834 } 225 9835 } 226 9836 if (tr.autoRemoveRecents && tr.getTopActivity() == null) { 227 9837 // Don't include auto remove tasks that are finished or finishing. 228 9838 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, 229 9839 "Skipping, auto-remove without activity: " + tr); 230 9840 continue; 231 9841 } 232 9842 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0 233 9843 && !tr.isAvailable) { 234 9844 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, 235 9845 "Skipping, unavail real act: " + tr); 236 9846 continue; 237 9847 } 238 9848 239 9849 if (!tr.mUserSetupComplete) { 240 9850 // Don't include task launched while user is not done setting-up. 241 9851 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, 242 9852 "Skipping, user setup not complete: " + tr); 243 9853 continue; 244 9854 } 245 9855 246 9856 ActivityManager.RecentTaskInfo rti = createRecentTaskInfoFromTaskRecord(tr); 247 9857 if (!detailed) { 248 9858 rti.baseIntent.replaceExtras((Bundle)null); 249 9859 } 250 9860 251 9861 res.add(rti); 252 9862 maxNum--; 253 9863 } 254 9864 } 255 9865 return new ParceledListSlice<>(res); 256 9866 } 257 9867 } 258 9868 259 9869 @Override 260 9870 public ActivityManager.TaskThumbnail getTaskThumbnail(int id) { 261 9871 synchronized (this) { 262 9872 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER, 263 9873 "getTaskThumbnail()"); 264 9874 final TaskRecord tr = mStackSupervisor.anyTaskForIdLocked( 265 9875 id, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS, INVALID_STACK_ID); 266 9876 if (tr != null) { 267 9877 return tr.getTaskThumbnailLocked(); 268 9878 } 269 9879 } 270 9880 return null; 271 9881 } 272 9882 273 9883 @Override 274 9884 public ActivityManager.TaskDescription getTaskDescription(int id) { 275 9885 synchronized (this) { 276 9886 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 277 9887 "getTaskDescription()"); 278 9888 final TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(id, 279 9889 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS, INVALID_STACK_ID); 280 9890 if (tr != null) { 281 9891 return tr.lastTaskDescription; 282 9892 } 283 9893 } 284 9894 return null; 285 9895 } 286 9896 287 9897 @Override 288 9898 public int addAppTask(IBinder activityToken, Intent intent, 289 9899 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException { 290 9900 final int callingUid = Binder.getCallingUid(); 291 9901 final long callingIdent = Binder.clearCallingIdentity(); 292 9902 293 9903 try { 294 9904 synchronized (this) { 295 9905 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken); 296 9906 if (r == null) { 297 9907 throw new IllegalArgumentException("Activity does not exist; token=" 298 9908 + activityToken); 299 9909 } 300 9910 ComponentName comp = intent.getComponent(); 301 9911 if (comp == null) { 302 9912 throw new IllegalArgumentException("Intent " + intent 303 9913 + " must specify explicit component"); 304 9914 } 305 9915 if (thumbnail.getWidth() != mThumbnailWidth 306 9916 || thumbnail.getHeight() != mThumbnailHeight) { 307 9917 throw new IllegalArgumentException("Bad thumbnail size: got " 308 9918 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require " 309 9919 + mThumbnailWidth + "x" + mThumbnailHeight); 310 9920 } 311 9921 if (intent.getSelector() != null) { 312 9922 intent.setSelector(null); 313 9923 } 314 9924 if (intent.getSourceBounds() != null) { 315 9925 intent.setSourceBounds(null); 316 9926 } 317 9927 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) { 318 9928 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) { 319 9929 // The caller has added this as an auto-remove task... that makes no 320 9930 // sense, so turn off auto-remove. 321 9931 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS); 322 9932 } 323 9933 } 324 9934 if (!comp.equals(mLastAddedTaskComponent) || callingUid != mLastAddedTaskUid) { 325 9935 mLastAddedTaskActivity = null; 326 9936 } 327 9937 ActivityInfo ainfo = mLastAddedTaskActivity; 328 9938 if (ainfo == null) { 329 9939 ainfo = mLastAddedTaskActivity = AppGlobals.getPackageManager().getActivityInfo( 330 9940 comp, 0, UserHandle.getUserId(callingUid)); 331 9941 if (ainfo.applicationInfo.uid != callingUid) { 332 9942 throw new SecurityException( 333 9943 "Can't add task for another application: target uid=" 334 9944 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid); 335 9945 } 336 9946 } 337 9947 338 9948 TaskRecord task = new TaskRecord(this, 339 9949 mStackSupervisor.getNextTaskIdForUserLocked(r.userId), 340 9950 ainfo, intent, description, new TaskThumbnailInfo()); 341 9951 342 9952 int trimIdx = mRecentTasks.trimForTaskLocked(task, false); 343 9953 if (trimIdx >= 0) { 344 9954 // If this would have caused a trim, then we'll abort because that 345 9955 // means it would be added at the end of the list but then just removed. 346 9956 return INVALID_TASK_ID; 347 9957 } 348 9958 349 9959 final int N = mRecentTasks.size(); 350 9960 if (N >= (ActivityManager.getMaxRecentTasksStatic()-1)) { 351 9961 final TaskRecord tr = mRecentTasks.remove(N - 1); 352 9962 tr.removedFromRecents(); 353 9963 } 354 9964 355 9965 task.inRecents = true; 356 9966 mRecentTasks.add(task); 357 9967 r.getStack().addTask(task, false, "addAppTask"); 358 9968 359 9969 task.setLastThumbnailLocked(thumbnail); 360 9970 task.freeLastThumbnail(); 361 9971 return task.taskId; 362 9972 } 363 9973 } finally { 364 9974 Binder.restoreCallingIdentity(callingIdent); 365 9975 } 366 9976 } 367 9977 368 9978 @Override 369 9979 public Point getAppTaskThumbnailSize() { 370 9980 synchronized (this) { 371 9981 return new Point(mThumbnailWidth, mThumbnailHeight); 372 9982 } 373 9983 } 374 9984 375 9985 @Override 376 9986 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) { 377 9987 synchronized (this) { 378 9988 ActivityRecord r = ActivityRecord.isInStackLocked(token); 379 9989 if (r != null) { 380 9990 r.setTaskDescription(td); 381 9991 final TaskRecord task = r.getTask(); 382 9992 task.updateTaskDescription(); 383 9993 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td); 384 9994 } 385 9995 } 386 9996 } 387 9997 388 9998 @Override 389 9999 public void setTaskResizeable(int taskId, int resizeableMode) { 390 10000 synchronized (this) { 391 10001 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked( 392 10002 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS, INVALID_STACK_ID); 393 10003 if (task == null) { 394 10004 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found"); 395 10005 return; 396 10006 } 397 10007 task.setResizeMode(resizeableMode); 398 10008 } 399 10009 } 400 10010 401 10011 @Override 402 10012 public void resizeTask(int taskId, Rect bounds, int resizeMode) { 403 10013 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()"); 404 10014 long ident = Binder.clearCallingIdentity(); 405 10015 try { 406 10016 synchronized (this) { 407 10017 TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 408 10018 if (task == null) { 409 10019 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found"); 410 10020 return; 411 10021 } 412 10022 // Place the task in the right stack if it isn't there already based on 413 10023 // the requested bounds. 414 10024 // The stack transition logic is: 415 10025 // - a null bounds on a freeform task moves that task to fullscreen 416 10026 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves 417 10027 // that task to freeform 418 10028 // - otherwise the task is not moved 419 10029 int stackId = task.getStackId(); 420 10030 if (!StackId.isTaskResizeAllowed(stackId)) { 421 10031 throw new IllegalArgumentException("resizeTask not allowed on task=" + task); 422 10032 } 423 10033 if (bounds == null && stackId == FREEFORM_WORKSPACE_STACK_ID) { 424 10034 stackId = FULLSCREEN_WORKSPACE_STACK_ID; 425 10035 } else if (bounds != null && stackId != FREEFORM_WORKSPACE_STACK_ID ) { 426 10036 stackId = FREEFORM_WORKSPACE_STACK_ID; 427 10037 } 428 10038 429 10039 // Reparent the task to the right stack if necessary 430 10040 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0; 431 10041 if (stackId != task.getStackId()) { 432 10042 // Defer resume until the task is resized below 433 10043 task.reparent(stackId, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, 434 10044 DEFER_RESUME, "resizeTask"); 435 10045 preserveWindow = false; 436 10046 } 437 10047 438 10048 // After reparenting (which only resizes the task to the stack bounds), resize the 439 10049 // task to the actual bounds provided 440 10050 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME); 441 10051 } 442 10052 } finally { 443 10053 Binder.restoreCallingIdentity(ident); 444 10054 } 445 10055 } 446 10056 447 10057 @Override 448 10058 public Rect getTaskBounds(int taskId) { 449 10059 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()"); 450 10060 long ident = Binder.clearCallingIdentity(); 451 10061 Rect rect = new Rect(); 452 10062 try { 453 10063 synchronized (this) { 454 10064 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId, 455 10065 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS, INVALID_STACK_ID); 456 10066 if (task == null) { 457 10067 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found"); 458 10068 return rect; 459 10069 } 460 10070 if (task.getStack() != null) { 461 10071 // Return the bounds from window manager since it will be adjusted for various 462 10072 // things like the presense of a docked stack for tasks that aren't resizeable. 463 10073 task.getWindowContainerBounds(rect); 464 10074 } else { 465 10075 // Task isn't in window manager yet since it isn't associated with a stack. 466 10076 // Return the persist value from activity manager 467 10077 if (task.mBounds != null) { 468 10078 rect.set(task.mBounds); 469 10079 } else if (task.mLastNonFullscreenBounds != null) { 470 10080 rect.set(task.mLastNonFullscreenBounds); 471 10081 } 472 10082 } 473 10083 } 474 10084 } finally { 475 10085 Binder.restoreCallingIdentity(ident); 476 10086 } 477 10087 return rect; 478 10088 } 479 10089 480 10090 @Override 481 10091 public void cancelTaskWindowTransition(int taskId) { 482 10092 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "cancelTaskWindowTransition()"); 483 10093 final long ident = Binder.clearCallingIdentity(); 484 10094 try { 485 10095 synchronized (this) { 486 10096 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId, 487 10097 MATCH_TASK_IN_STACKS_ONLY, INVALID_STACK_ID); 488 10098 if (task == null) { 489 10099 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found"); 490 10100 return; 491 10101 } 492 10102 task.cancelWindowTransition(); 493 10103 } 494 10104 } finally { 495 10105 Binder.restoreCallingIdentity(ident); 496 10106 } 497 10107 } 498 10108 499 10109 @Override 500 10110 public void cancelTaskThumbnailTransition(int taskId) { 501 10111 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "cancelTaskThumbnailTransition()"); 502 10112 final long ident = Binder.clearCallingIdentity(); 503 10113 try { 504 10114 synchronized (this) { 505 10115 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId, 506 10116 MATCH_TASK_IN_STACKS_ONLY, INVALID_STACK_ID); 507 10117 if (task == null) { 508 10118 Slog.w(TAG, "cancelTaskThumbnailTransition: taskId=" + taskId + " not found"); 509 10119 return; 510 10120 } 511 10121 task.cancelThumbnailTransition(); 512 10122 } 513 10123 } finally { 514 10124 Binder.restoreCallingIdentity(ident); 515 10125 } 516 10126 } 517 10127 518 10128 @Override 519 10129 public TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) { 520 10130 enforceCallingPermission(READ_FRAME_BUFFER, "getTaskSnapshot()"); 521 10131 final long ident = Binder.clearCallingIdentity(); 522 10132 try { 523 10133 final TaskRecord task; 524 10134 synchronized (this) { 525 10135 task = mStackSupervisor.anyTaskForIdLocked(taskId, 526 10136 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS, INVALID_STACK_ID); 527 10137 if (task == null) { 528 10138 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found"); 529 10139 return null; 530 10140 } 531 10141 } 532 10142 // Don't call this while holding the lock as this operation might hit the disk. 533 10143 return task.getSnapshot(reducedResolution); 534 10144 } finally { 535 10145 Binder.restoreCallingIdentity(ident); 536 10146 } 537 10147 } 538 10148 539 10149 @Override 540 10150 public Bitmap getTaskDescriptionIcon(String filePath, int userId) { 541 10151 if (userId != UserHandle.getCallingUserId()) { 542 10152 enforceCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 543 10153 "getTaskDescriptionIcon"); 544 10154 } 545 10155 final File passedIconFile = new File(filePath); 546 10156 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId), 547 10157 passedIconFile.getName()); 548 10158 if (!legitIconFile.getPath().equals(filePath) 549 10159 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) { 550 10160 throw new IllegalArgumentException("Bad file path: " + filePath 551 10161 + " passed for userId " + userId); 552 10162 } 553 10163 return mRecentTasks.getTaskDescriptionIcon(filePath); 554 10164 } 555 10165 556 10166 @Override 557 10167 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) 558 10168 throws RemoteException { 559 10169 final ActivityOptions activityOptions = ActivityOptions.fromBundle(opts); 560 10170 if (activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE || 561 10171 activityOptions.getCustomInPlaceResId() == 0) { 562 10172 throw new IllegalArgumentException("Expected in-place ActivityOption " + 563 10173 "with valid animation"); 564 10174 } 565 10175 mWindowManager.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false); 566 10176 mWindowManager.overridePendingAppTransitionInPlace(activityOptions.getPackageName(), 567 10177 activityOptions.getCustomInPlaceResId()); 568 10178 mWindowManager.executeAppTransition(); 569 10179 } 570 10180 571 10181 private void removeTasksByPackageNameLocked(String packageName, int userId) { 572 10182 // Remove all tasks with activities in the specified package from the list of recent tasks 573 10183 for (int i = mRecentTasks.size() - 1; i >= 0; i--) { 574 10184 TaskRecord tr = mRecentTasks.get(i); 575 10185 if (tr.userId != userId) continue; 576 10186 577 10187 ComponentName cn = tr.intent.getComponent(); 578 10188 if (cn != null && cn.getPackageName().equals(packageName)) { 579 10189 // If the package name matches, remove the task. 580 10190 mStackSupervisor.removeTaskByIdLocked(tr.taskId, true, REMOVE_FROM_RECENTS); 581 10191 } 582 10192 } 583 10193 } 584 10194 585 10195 private void cleanupDisabledPackageTasksLocked(String packageName, Set<String> filterByClasses, 586 10196 int userId) { 587 10197 588 10198 for (int i = mRecentTasks.size() - 1; i >= 0; i--) { 589 10199 TaskRecord tr = mRecentTasks.get(i); 590 10200 if (userId != UserHandle.USER_ALL && tr.userId != userId) { 591 10201 continue; 592 10202 } 593 10203 594 10204 ComponentName cn = tr.intent.getComponent(); 595 10205 final boolean sameComponent = cn != null && cn.getPackageName().equals(packageName) 596 10206 && (filterByClasses == null || filterByClasses.contains(cn.getClassName())); 597 10207 if (sameComponent) { 598 10208 mStackSupervisor.removeTaskByIdLocked(tr.taskId, false, REMOVE_FROM_RECENTS); 599 10209 } 600 10210 } 601 10211 } 602 10212 603 10213 @Override 604 10214 public void removeStack(int stackId) { 605 10215 enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS, "removeStack()"); 606 10216 if (StackId.isHomeOrRecentsStack(stackId)) { 607 10217 throw new IllegalArgumentException("Removing home or recents stack is not allowed."); 608 10218 } 609 10219 610 10220 synchronized (this) { 611 10221 final long ident = Binder.clearCallingIdentity(); 612 10222 try { 613 10223 mStackSupervisor.removeStackLocked(stackId); 614 10224 } finally { 615 10225 Binder.restoreCallingIdentity(ident); 616 10226 } 617 10227 } 618 10228 } 619 10229 620 10230 @Override 621 10231 public void moveStackToDisplay(int stackId, int displayId) { 622 10232 enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()"); 623 10233 624 10234 synchronized (this) { 625 10235 final long ident = Binder.clearCallingIdentity(); 626 10236 try { 627 10237 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId 628 10238 + " to displayId=" + displayId); 629 10239 mStackSupervisor.moveStackToDisplayLocked(stackId, displayId, ON_TOP); 630 10240 } finally { 631 10241 Binder.restoreCallingIdentity(ident); 632 10242 } 633 10243 } 634 10244 } 635 10245 636 10246 @Override 637 10247 public boolean removeTask(int taskId) { 638 10248 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS, "removeTask()"); 639 10249 synchronized (this) { 640 10250 final long ident = Binder.clearCallingIdentity(); 641 10251 try { 642 10252 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS); 643 10253 } finally { 644 10254 Binder.restoreCallingIdentity(ident); 645 10255 } 646 10256 } 647 10257 } 648 10258 649 10259 /** 650 10260 * TODO: Add mController hook 651 10261 */ 652 10262 @Override 653 10263 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) { 654 10264 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()"); 655 10265 656 10266 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId); 657 10267 synchronized(this) { 658 10268 moveTaskToFrontLocked(taskId, flags, bOptions, false /* fromRecents */); 659 10269 } 660 10270 } 661 10271 662 10272 void moveTaskToFrontLocked(int taskId, int flags, Bundle bOptions, boolean fromRecents) { 663 10273 ActivityOptions options = ActivityOptions.fromBundle(bOptions); 664 10274 665 10275 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 666 10276 Binder.getCallingUid(), -1, -1, "Task to front")) { 667 10277 ActivityOptions.abort(options); 668 10278 return; 669 10279 } 670 10280 final long origId = Binder.clearCallingIdentity(); 671 10281 try { 672 10282 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 673 10283 if (task == null) { 674 10284 Slog.d(TAG, "Could not find task for id: "+ taskId); 675 10285 return; 676 10286 } 677 10287 if (mStackSupervisor.isLockTaskModeViolation(task)) { 678 10288 mStackSupervisor.showLockTaskToast(); 679 10289 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode"); 680 10290 return; 681 10291 } 682 10292 final ActivityRecord prev = mStackSupervisor.topRunningActivityLocked(); 683 10293 if (prev != null) { 684 10294 task.setTaskToReturnTo(prev); 685 10295 } 686 10296 mStackSupervisor.findTaskToMoveToFrontLocked(task, flags, options, "moveTaskToFront", 687 10297 false /* forceNonResizable */); 688 10298 689 10299 final ActivityRecord topActivity = task.getTopActivity(); 690 10300 if (topActivity != null) { 691 10301 692 10302 // We are reshowing a task, use a starting window to hide the initial draw delay 693 10303 // so the transition can start earlier. 694 10304 topActivity.showStartingWindow(null /* prev */, false /* newTask */, 695 10305 true /* taskSwitch */, fromRecents); 696 10306 } 697 10307 } finally { 698 10308 Binder.restoreCallingIdentity(origId); 699 10309 } 700 10310 ActivityOptions.abort(options); 701 10311 } 702 10312 703 10313 /** 704 10314 * Attempts to move a task backwards in z-order (the order of activities within the task is 705 10315 * unchanged). 706 10316 * 707 10317 * There are several possible results of this call: 708 10318 * - if the task is locked, then we will show the lock toast 709 10319 * - if there is a task behind the provided task, then that task is made visible and resumed as 710 10320 * this task is moved to the back 711 10321 * - otherwise, if there are no other tasks in the stack: 712 10322 * - if this task is in the pinned stack, then we remove the stack completely, which will 713 10323 * have the effect of moving the task to the top or bottom of the fullscreen stack 714 10324 * (depending on whether it is visible) 715 10325 * - otherwise, we simply return home and hide this task 716 10326 * 717 10327 * @param token A reference to the activity we wish to move 718 10328 * @param nonRoot If false then this only works if the activity is the root 719 10329 * of a task; if true it will work for any activity in a task. 720 10330 * @return Returns true if the move completed, false if not. 721 10331 */ 722 10332 @Override 723 10333 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) { 724 10334 enforceNotIsolatedCaller("moveActivityTaskToBack"); 725 10335 synchronized(this) { 726 10336 final long origId = Binder.clearCallingIdentity(); 727 10337 try { 728 10338 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot); 729 10339 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 730 10340 if (task != null) { 731 10341 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId); 732 10342 } 733 10343 } finally { 734 10344 Binder.restoreCallingIdentity(origId); 735 10345 } 736 10346 } 737 10347 return false; 738 10348 } 739 10349 740 10350 @Override 741 10351 public void moveTaskBackwards(int task) { 742 10352 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, 743 10353 "moveTaskBackwards()"); 744 10354 745 10355 synchronized(this) { 746 10356 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 747 10357 Binder.getCallingUid(), -1, -1, "Task backwards")) { 748 10358 return; 749 10359 } 750 10360 final long origId = Binder.clearCallingIdentity(); 751 10361 moveTaskBackwardsLocked(task); 752 10362 Binder.restoreCallingIdentity(origId); 753 10363 } 754 10364 } 755 10365 756 10366 private final void moveTaskBackwardsLocked(int task) { 757 10367 Slog.e(TAG, "moveTaskBackwards not yet implemented!"); 758 10368 } 759 10369 760 10370 @Override 761 10371 public IActivityContainer createVirtualActivityContainer(IBinder parentActivityToken, 762 10372 IActivityContainerCallback callback) throws RemoteException { 763 10373 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "createActivityContainer()"); 764 10374 synchronized (this) { 765 10375 if (parentActivityToken == null) { 766 10376 throw new IllegalArgumentException("parent token must not be null"); 767 10377 } 768 10378 ActivityRecord r = ActivityRecord.forTokenLocked(parentActivityToken); 769 10379 if (r == null) { 770 10380 return null; 771 10381 } 772 10382 if (callback == null) { 773 10383 throw new IllegalArgumentException("callback must not be null"); 774 10384 } 775 10385 return mStackSupervisor.createVirtualActivityContainer(r, callback); 776 10386 } 777 10387 } 778 10388 779 10389 @Override 780 10390 public IActivityContainer createStackOnDisplay(int displayId) throws RemoteException { 781 10391 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "createStackOnDisplay()"); 782 10392 synchronized (this) { 783 10393 final int stackId = mStackSupervisor.getNextStackId(); 784 10394 final ActivityStack stack = 785 10395 mStackSupervisor.createStackOnDisplay(stackId, displayId, true /*onTop*/); 786 10396 if (stack == null) { 787 10397 return null; 788 10398 } 789 10399 return stack.mActivityContainer; 790 10400 } 791 10401 } 792 10402 793 10403 @Override 794 10404 public int getActivityDisplayId(IBinder activityToken) throws RemoteException { 795 10405 synchronized (this) { 796 10406 ActivityStack stack = ActivityRecord.getStackLocked(activityToken); 797 10407 if (stack != null && stack.mActivityContainer.isAttachedLocked()) { 798 10408 return stack.mActivityContainer.getDisplayId(); 799 10409 } 800 10410 return DEFAULT_DISPLAY; 801 10411 } 802 10412 } 803 10413 804 10414 @Override 805 10415 public int getActivityStackId(IBinder token) throws RemoteException { 806 10416 synchronized (this) { 807 10417 ActivityStack stack = ActivityRecord.getStackLocked(token); 808 10418 if (stack == null) { 809 10419 return INVALID_STACK_ID; 810 10420 } 811 10421 return stack.mStackId; 812 10422 } 813 10423 } 814 10424 815 10425 @Override 816 10426 public void exitFreeformMode(IBinder token) throws RemoteException { 817 10427 synchronized (this) { 818 10428 long ident = Binder.clearCallingIdentity(); 819 10429 try { 820 10430 final ActivityRecord r = ActivityRecord.forTokenLocked(token); 821 10431 if (r == null) { 822 10432 throw new IllegalArgumentException( 823 10433 "exitFreeformMode: No activity record matching token=" + token); 824 10434 } 825 10435 826 10436 final ActivityStack stack = r.getStack(); 827 10437 if (stack == null || stack.mStackId != FREEFORM_WORKSPACE_STACK_ID) { 828 10438 throw new IllegalStateException( 829 10439 "exitFreeformMode: You can only go fullscreen from freeform."); 830 10440 } 831 10441 832 10442 if (DEBUG_STACK) Slog.d(TAG_STACK, "exitFreeformMode: " + r); 833 10443 r.getTask().reparent(FULLSCREEN_WORKSPACE_STACK_ID, ON_TOP, 834 10444 REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME, "exitFreeformMode"); 835 10445 } finally { 836 10446 Binder.restoreCallingIdentity(ident); 837 10447 } 838 10448 } 839 10449 } 840 10450 841 10451 @Override 842 10452 public void moveTaskToStack(int taskId, int stackId, boolean toTop) { 843 10453 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()"); 844 10454 if (StackId.isHomeOrRecentsStack(stackId)) { 845 10455 throw new IllegalArgumentException( 846 10456 "moveTaskToStack: Attempt to move task " + taskId + " to stack " + stackId); 847 10457 } 848 10458 synchronized (this) { 849 10459 long ident = Binder.clearCallingIdentity(); 850 10460 try { 851 10461 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 852 10462 if (task == null) { 853 10463 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId); 854 10464 return; 855 10465 } 856 10466 857 10467 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId 858 10468 + " to stackId=" + stackId + " toTop=" + toTop); 859 10469 if (stackId == DOCKED_STACK_ID) { 860 10470 mWindowManager.setDockedStackCreateState(DOCKED_STACK_CREATE_MODE_TOP_OR_LEFT, 861 10471 null /* initialBounds */); 862 10472 } 863 10473 task.reparent(stackId, toTop, 864 10474 REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME, "moveTaskToStack"); 865 10475 } finally { 866 10476 Binder.restoreCallingIdentity(ident); 867 10477 } 868 10478 } 869 10479 } 870 10480 871 10481 @Override 872 10482 public void swapDockedAndFullscreenStack() throws RemoteException { 873 10483 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "swapDockedAndFullscreenStack()"); 874 10484 synchronized (this) { 875 10485 long ident = Binder.clearCallingIdentity(); 876 10486 try { 877 10487 final ActivityStack fullscreenStack = mStackSupervisor.getStack( 878 10488 FULLSCREEN_WORKSPACE_STACK_ID); 879 10489 final TaskRecord topTask = fullscreenStack != null ? fullscreenStack.topTask() 880 10490 : null; 881 10491 final ActivityStack dockedStack = mStackSupervisor.getStack(DOCKED_STACK_ID); 882 10492 final ArrayList<TaskRecord> tasks = dockedStack != null ? dockedStack.getAllTasks() 883 10493 : null; 884 10494 if (topTask == null || tasks == null || tasks.size() == 0) { 885 10495 Slog.w(TAG, 886 10496 "Unable to swap tasks, either docked or fullscreen stack is empty."); 887 10497 return; 888 10498 } 889 10499 890 10500 // TODO: App transition 891 10501 mWindowManager.prepareAppTransition(TRANSIT_ACTIVITY_RELAUNCH, false); 892 10502 893 10503 // Defer the resume until we move all the docked tasks to the fullscreen stack below 894 10504 topTask.reparent(DOCKED_STACK_ID, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, 895 10505 DEFER_RESUME, "swapDockedAndFullscreenStack - DOCKED_STACK"); 896 10506 final int size = tasks.size(); 897 10507 for (int i = 0; i < size; i++) { 898 10508 final int id = tasks.get(i).taskId; 899 10509 if (id == topTask.taskId) { 900 10510 continue; 901 10511 } 902 10512 903 10513 // Defer the resume until after all the tasks have been moved 904 10514 tasks.get(i).reparent(FULLSCREEN_WORKSPACE_STACK_ID, ON_TOP, 905 10515 REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, DEFER_RESUME, 906 10516 "swapDockedAndFullscreenStack - FULLSCREEN_STACK"); 907 10517 } 908 10518 909 10519 // Because we deferred the resume to avoid conflicts with stack switches while 910 10520 // resuming, we need to do it after all the tasks are moved. 911 10521 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS); 912 10522 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 913 10523 914 10524 mWindowManager.executeAppTransition(); 915 10525 } finally { 916 10526 Binder.restoreCallingIdentity(ident); 917 10527 } 918 10528 } 919 10529 } 920 10530 921 10531 /** 922 10532 * Moves the input task to the docked stack. 923 10533 * 924 10534 * @param taskId Id of task to move. 925 10535 * @param createMode The mode the docked stack should be created in if it doesn't exist 926 10536 * already. See 927 10537 * {@link android.app.ActivityManager#DOCKED_STACK_CREATE_MODE_TOP_OR_LEFT} 928 10538 * and 929 10539 * {@link android.app.ActivityManager#DOCKED_STACK_CREATE_MODE_BOTTOM_OR_RIGHT} 930 10540 * @param toTop If the task and stack should be moved to the top. 931 10541 * @param animate Whether we should play an animation for the moving the task 932 10542 * @param initialBounds If the docked stack gets created, it will use these bounds for the 933 10543 * docked stack. Pass {@code null} to use default bounds. 934 10544 */ 935 10545 @Override 936 10546 public boolean moveTaskToDockedStack(int taskId, int createMode, boolean toTop, boolean animate, 937 10547 Rect initialBounds) { 938 10548 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToDockedStack()"); 939 10549 synchronized (this) { 940 10550 long ident = Binder.clearCallingIdentity(); 941 10551 try { 942 10552 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 943 10553 if (task == null) { 944 10554 Slog.w(TAG, "moveTaskToDockedStack: No task for id=" + taskId); 945 10555 return false; 946 10556 } 947 10557 948 10558 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToDockedStack: moving task=" + taskId 949 10559 + " to createMode=" + createMode + " toTop=" + toTop); 950 10560 mWindowManager.setDockedStackCreateState(createMode, initialBounds); 951 10561 952 10562 // Defer resuming until we move the home stack to the front below 953 10563 final boolean moved = task.reparent(DOCKED_STACK_ID, toTop, 954 10564 REPARENT_KEEP_STACK_AT_FRONT, animate, !DEFER_RESUME, 955 10565 "moveTaskToDockedStack"); 956 10566 if (moved) { 957 10567 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS); 958 10568 } 959 10569 return moved; 960 10570 } finally { 961 10571 Binder.restoreCallingIdentity(ident); 962 10572 } 963 10573 } 964 10574 } 965 10575 966 10576 /** 967 10577 * Moves the top activity in the input stackId to the pinned stack. 968 10578 * 969 10579 * @param stackId Id of stack to move the top activity to pinned stack. 970 10580 * @param bounds Bounds to use for pinned stack. 971 10581 * 972 10582 * @return True if the top activity of the input stack was successfully moved to the pinned 973 10583 * stack. 974 10584 */ 975 10585 @Override 976 10586 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) { 977 10587 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "moveTopActivityToPinnedStack()"); 978 10588 synchronized (this) { 979 10589 if (!mSupportsPictureInPicture) { 980 10590 throw new IllegalStateException("moveTopActivityToPinnedStack:" 981 10591 + "Device doesn't support picture-in-picture mode"); 982 10592 } 983 10593 984 10594 long ident = Binder.clearCallingIdentity(); 985 10595 try { 986 10596 return mStackSupervisor.moveTopStackActivityToPinnedStackLocked(stackId, bounds); 987 10597 } finally { 988 10598 Binder.restoreCallingIdentity(ident); 989 10599 } 990 10600 } 991 10601 } 992 10602 993 10603 @Override 994 10604 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode, 995 10605 boolean preserveWindows, boolean animate, int animationDuration) { 996 10606 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()"); 997 10607 long ident = Binder.clearCallingIdentity(); 998 10608 try { 999 10609 synchronized (this) { 1000 10610 if (animate) { 1001 10611 if (stackId == PINNED_STACK_ID) { 1002 10612 final PinnedActivityStack pinnedStack = 1003 10613 mStackSupervisor.getStack(PINNED_STACK_ID); 1004 10614 if (pinnedStack != null) { 1005 10615 pinnedStack.animateResizePinnedStack(null /* sourceHintBounds */, 1006 10616 destBounds, animationDuration, false /* fromFullscreen */); 1007 10617 } 1008 10618 } else { 1009 10619 throw new IllegalArgumentException("Stack: " + stackId 1010 10620 + " doesn't support animated resize."); 1011 10621 } 1012 10622 } else { 1013 10623 mStackSupervisor.resizeStackLocked(stackId, destBounds, null /* tempTaskBounds */, 1014 10624 null /* tempTaskInsetBounds */, preserveWindows, 1015 10625 allowResizeInDockedMode, !DEFER_RESUME); 1016 10626 } 1017 10627 } 1018 10628 } finally { 1019 10629 Binder.restoreCallingIdentity(ident); 1020 10630 } 1021 10631 } 1022 10632 1023 10633 @Override 1024 10634 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds, 1025 10635 Rect tempDockedTaskInsetBounds, 1026 10636 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) { 1027 10637 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 1028 10638 "resizeDockedStack()"); 1029 10639 long ident = Binder.clearCallingIdentity(); 1030 10640 try { 1031 10641 synchronized (this) { 1032 10642 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds, 1033 10643 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds, 1034 10644 PRESERVE_WINDOWS); 1035 10645 } 1036 10646 } finally { 1037 10647 Binder.restoreCallingIdentity(ident); 1038 10648 } 1039 10649 } 1040 10650 1041 10651 @Override 1042 10652 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) { 1043 10653 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 1044 10654 "resizePinnedStack()"); 1045 10655 final long ident = Binder.clearCallingIdentity(); 1046 10656 try { 1047 10657 synchronized (this) { 1048 10658 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds); 1049 10659 } 1050 10660 } finally { 1051 10661 Binder.restoreCallingIdentity(ident); 1052 10662 } 1053 10663 } 1054 10664 1055 10665 /** 1056 10666 * Try to place task to provided position. The final position might be different depending on 1057 10667 * current user and stacks state. The task will be moved to target stack if it's currently in 1058 10668 * different stack. 1059 10669 */ 1060 10670 @Override 1061 10671 public void positionTaskInStack(int taskId, int stackId, int position) { 1062 10672 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()"); 1063 10673 if (StackId.isHomeOrRecentsStack(stackId)) { 1064 10674 throw new IllegalArgumentException( 1065 10675 "positionTaskInStack: Attempt to change the position of task " 1066 10676 + taskId + " in/to home/recents stack"); 1067 10677 } 1068 10678 synchronized (this) { 1069 10679 long ident = Binder.clearCallingIdentity(); 1070 10680 try { 1071 10681 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task=" 1072 10682 + taskId + " in stackId=" + stackId + " at position=" + position); 1073 10683 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 1074 10684 if (task == null) { 1075 10685 throw new IllegalArgumentException("positionTaskInStack: no task for id=" 1076 10686 + taskId); 1077 10687 } 1078 10688 1079 10689 final ActivityStack stack = mStackSupervisor.getStack(stackId, CREATE_IF_NEEDED, 1080 10690 !ON_TOP); 1081 10691 1082 10692 // TODO: Have the callers of this API call a separate reparent method if that is 1083 10693 // what they intended to do vs. having this method also do reparenting. 1084 10694 if (task.getStack() == stack) { 1085 10695 // Change position in current stack. 1086 10696 stack.positionChildAt(task, position); 1087 10697 } else { 1088 10698 // Reparent to new stack. 1089 10699 task.reparent(stackId, position, REPARENT_LEAVE_STACK_IN_PLACE, 1090 10700 !ANIMATE, !DEFER_RESUME, "positionTaskInStack"); 1091 10701 } 1092 10702 } finally { 1093 10703 Binder.restoreCallingIdentity(ident); 1094 10704 } 1095 10705 } 1096 10706 } 1097 10707 1098 10708 @Override 1099 10709 public List<StackInfo> getAllStackInfos() { 1100 10710 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()"); 1101 10711 long ident = Binder.clearCallingIdentity(); 1102 10712 try { 1103 10713 synchronized (this) { 1104 10714 return mStackSupervisor.getAllStackInfosLocked(); 1105 10715 } 1106 10716 } finally { 1107 10717 Binder.restoreCallingIdentity(ident); 1108 10718 } 1109 10719 } 1110 10720 1111 10721 @Override 1112 10722 public StackInfo getStackInfo(int stackId) { 1113 10723 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()"); 1114 10724 long ident = Binder.clearCallingIdentity(); 1115 10725 try { 1116 10726 synchronized (this) { 1117 10727 return mStackSupervisor.getStackInfoLocked(stackId); 1118 10728 } 1119 10729 } finally { 1120 10730 Binder.restoreCallingIdentity(ident); 1121 10731 } 1122 10732 } 1123 10733 1124 10734 @Override 1125 10735 public int getTaskForActivity(IBinder token, boolean onlyRoot) { 1126 10736 synchronized(this) { 1127 10737 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot); 1128 10738 } 1129 10739 } 1130 10740 1131 10741 @Override 1132 10742 public void updateDeviceOwner(String packageName) { 1133 10743 final int callingUid = Binder.getCallingUid(); 1134 10744 if (callingUid != 0 && callingUid != SYSTEM_UID) { 1135 10745 throw new SecurityException("updateDeviceOwner called from non-system process"); 1136 10746 } 1137 10747 synchronized (this) { 1138 10748 mDeviceOwnerName = packageName; 1139 10749 } 1140 10750 } 1141 10751 1142 10752 @Override 1143 10753 public void updateLockTaskPackages(int userId, String[] packages) { 1144 10754 final int callingUid = Binder.getCallingUid(); 1145 10755 if (callingUid != 0 && callingUid != SYSTEM_UID) { 1146 10756 enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES, 1147 10757 "updateLockTaskPackages()"); 1148 10758 } 1149 10759 synchronized (this) { 1150 10760 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":" + 1151 10761 Arrays.toString(packages)); 1152 10762 mLockTaskPackages.put(userId, packages); 1153 10763 mStackSupervisor.onLockTaskPackagesUpdatedLocked(); 1154 10764 } 1155 10765 } 1156 10766 1157 10767 1158 10768 void startLockTaskModeLocked(TaskRecord task) { 1159 10769 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task); 1160 10770 if (task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) { 1161 10771 return; 1162 10772 } 1163 10773 1164 10774 // When a task is locked, dismiss the pinned stack if it exists 1165 10775 final PinnedActivityStack pinnedStack = mStackSupervisor.getStack( 1166 10776 PINNED_STACK_ID); 1167 10777 if (pinnedStack != null) { 1168 10778 mStackSupervisor.removeStackLocked(PINNED_STACK_ID); 1169 10779 } 1170 10780 1171 10781 // isSystemInitiated is used to distinguish between locked and pinned mode, as pinned mode 1172 10782 // is initiated by system after the pinning request was shown and locked mode is initiated 1173 10783 // by an authorized app directly 1174 10784 final int callingUid = Binder.getCallingUid(); 1175 10785 boolean isSystemInitiated = callingUid == SYSTEM_UID; 1176 10786 long ident = Binder.clearCallingIdentity(); 1177 10787 try { 1178 10788 if (!isSystemInitiated) { 1179 10789 task.mLockTaskUid = callingUid; 1180 10790 if (task.mLockTaskAuth == LOCK_TASK_AUTH_PINNABLE) { 1181 10791 // startLockTask() called by app and task mode is lockTaskModeDefault. 1182 10792 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Mode default, asking user"); 1183 10793 StatusBarManagerInternal statusBarManager = 1184 10794 LocalServices.getService(StatusBarManagerInternal.class); 1185 10795 if (statusBarManager != null) { 1186 10796 statusBarManager.showScreenPinningRequest(task.taskId); 1187 10797 } 1188 10798 return; 1189 10799 } 1190 10800 1191 10801 final ActivityStack stack = mStackSupervisor.getFocusedStack(); 1192 10802 if (stack == null || task != stack.topTask()) { 1193 10803 throw new IllegalArgumentException("Invalid task, not in foreground"); 1194 10804 } 1195 10805 } 1196 10806 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, isSystemInitiated ? "Locking pinned" : 1197 10807 "Locking fully"); 1198 10808 mStackSupervisor.setLockTaskModeLocked(task, isSystemInitiated ? 1199 10809 ActivityManager.LOCK_TASK_MODE_PINNED : 1200 10810 ActivityManager.LOCK_TASK_MODE_LOCKED, 1201 10811 "startLockTask", true); 1202 10812 } finally { 1203 10813 Binder.restoreCallingIdentity(ident); 1204 10814 } 1205 10815 } 1206 10816 1207 10817 @Override 1208 10818 public void startLockTaskModeById(int taskId) { 1209 10819 synchronized (this) { 1210 10820 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 1211 10821 if (task != null) { 1212 10822 startLockTaskModeLocked(task); 1213 10823 } 1214 10824 } 1215 10825 } 1216 10826 1217 10827 @Override 1218 10828 public void startLockTaskModeByToken(IBinder token) { 1219 10829 synchronized (this) { 1220 10830 final ActivityRecord r = ActivityRecord.forTokenLocked(token); 1221 10831 if (r == null) { 1222 10832 return; 1223 10833 } 1224 10834 final TaskRecord task = r.getTask(); 1225 10835 if (task != null) { 1226 10836 startLockTaskModeLocked(task); 1227 10837 } 1228 10838 } 1229 10839 } 1230 10840 1231 10841 @Override 1232 10842 public void startSystemLockTaskMode(int taskId) throws RemoteException { 1233 10843 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode"); 1234 10844 // This makes inner call to look as if it was initiated by system. 1235 10845 long ident = Binder.clearCallingIdentity(); 1236 10846 try { 1237 10847 synchronized (this) { 1238 10848 startLockTaskModeById(taskId); 1239 10849 } 1240 10850 } finally { 1241 10851 Binder.restoreCallingIdentity(ident); 1242 10852 } 1243 10853 } 1244 10854 1245 10855 @Override 1246 10856 public void stopLockTaskMode() { 1247 10857 final TaskRecord lockTask = mStackSupervisor.getLockedTaskLocked(); 1248 10858 if (lockTask == null) { 1249 10859 // Our work here is done. 1250 10860 return; 1251 10861 } 1252 10862 1253 10863 final int callingUid = Binder.getCallingUid(); 1254 10864 final int lockTaskUid = lockTask.mLockTaskUid; 1255 10865 final int lockTaskModeState = mStackSupervisor.getLockTaskModeState(); 1256 10866 if (lockTaskModeState == ActivityManager.LOCK_TASK_MODE_NONE) { 1257 10867 // Done. 1258 10868 return; 1259 10869 } else { 1260 10870 // Ensure the same caller for startLockTaskMode and stopLockTaskMode. 1261 10871 // It is possible lockTaskMode was started by the system process because 1262 10872 // android:lockTaskMode is set to a locking value in the application manifest 1263 10873 // instead of the app calling startLockTaskMode. In this case 1264 10874 // {@link TaskRecord.mLockTaskUid} will be 0, so we compare the callingUid to the 1265 10875 // {@link TaskRecord.effectiveUid} instead. Also caller with 1266 10876 // {@link MANAGE_ACTIVITY_STACKS} can stop any lock task. 1267 10877 if (checkCallingPermission(MANAGE_ACTIVITY_STACKS) != PERMISSION_GRANTED 1268 10878 && callingUid != lockTaskUid 1269 10879 && (lockTaskUid != 0 || callingUid != lockTask.effectiveUid)) { 1270 10880 throw new SecurityException("Invalid uid, expected " + lockTaskUid 1271 10881 + " callingUid=" + callingUid + " effectiveUid=" + lockTask.effectiveUid); 1272 10882 } 1273 10883 } 1274 10884 long ident = Binder.clearCallingIdentity(); 1275 10885 try { 1276 10886 Log.d(TAG, "stopLockTaskMode"); 1277 10887 // Stop lock task 1278 10888 synchronized (this) { 1279 10889 mStackSupervisor.setLockTaskModeLocked(null, ActivityManager.LOCK_TASK_MODE_NONE, 1280 10890 "stopLockTask", true); 1281 10891 } 1282 10892 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE); 1283 10893 if (tm != null) { 1284 10894 tm.showInCallScreen(false); 1285 10895 } 1286 10896 } finally { 1287 10897 Binder.restoreCallingIdentity(ident); 1288 10898 } 1289 10899 } 1290 10900 1291 10901 /** 1292 10902 * This API should be called by SystemUI only when user perform certain action to dismiss 1293 10903 * lock task mode. We should only dismiss pinned lock task mode in this case. 1294 10904 */ 1295 10905 @Override 1296 10906 public void stopSystemLockTaskMode() throws RemoteException { 1297 10907 if (mStackSupervisor.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_PINNED) { 1298 10908 stopLockTaskMode(); 1299 10909 } else { 1300 10910 mStackSupervisor.showLockTaskToast(); 1301 10911 } 1302 10912 } 1303 10913 1304 10914 @Override 1305 10915 public boolean isInLockTaskMode() { 1306 10916 return getLockTaskModeState() != ActivityManager.LOCK_TASK_MODE_NONE; 1307 10917 } 1308 10918 1309 10919 @Override 1310 10920 public int getLockTaskModeState() { 1311 10921 synchronized (this) { 1312 10922 return mStackSupervisor.getLockTaskModeState(); 1313 10923 } 1314 10924 } 1315 10925 1316 10926 @Override 1317 10927 public void showLockTaskEscapeMessage(IBinder token) { 1318 10928 synchronized (this) { 1319 10929 final ActivityRecord r = ActivityRecord.forTokenLocked(token); 1320 10930 if (r == null) { 1321 10931 return; 1322 10932 } 1323 10933 mStackSupervisor.showLockTaskEscapeMessageLocked(r.getTask()); 1324 10934 } 1325 10935 } 1326 10936 1327 10937 @Override 1328 10938 public void setDisablePreviewScreenshots(IBinder token, boolean disable) 1329 10939 throws RemoteException { 1330 10940 synchronized (this) { 1331 10941 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 1332 10942 if (r == null) { 1333 10943 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token=" 1334 10944 + token); 1335 10945 return; 1336 10946 } 1337 10947 final long origId = Binder.clearCallingIdentity(); 1338 10948 try { 1339 10949 r.setDisablePreviewScreenshots(disable); 1340 10950 } finally { 1341 10951 Binder.restoreCallingIdentity(origId); 1342 10952 } 1343 10953 } 1344 10954 }
content provider相关
1 10956 // ========================================================= 2 10957 // CONTENT PROVIDERS 3 10958 // ========================================================= 4 10959 5 10960 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) { 6 10961 List<ProviderInfo> providers = null; 7 10962 try { 8 10963 providers = AppGlobals.getPackageManager() 9 10964 .queryContentProviders(app.processName, app.uid, 10 10965 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS 11 10966 | MATCH_DEBUG_TRIAGED_MISSING, /*metadastaKey=*/ null) 12 10967 .getList(); 13 10968 } catch (RemoteException ex) { 14 10969 } 15 10970 if (DEBUG_MU) Slog.v(TAG_MU, 16 10971 "generateApplicationProvidersLocked, app.info.uid = " + app.uid); 17 10972 int userId = app.userId; 18 10973 if (providers != null) { 19 10974 int N = providers.size(); 20 10975 app.pubProviders.ensureCapacity(N + app.pubProviders.size()); 21 10976 for (int i=0; i<N; i++) { 22 10977 // TODO: keep logic in sync with installEncryptionUnawareProviders 23 10978 ProviderInfo cpi = 24 10979 (ProviderInfo)providers.get(i); 25 10980 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo, 26 10981 cpi.name, cpi.flags); 27 10982 if (singleton && UserHandle.getUserId(app.uid) != UserHandle.USER_SYSTEM) { 28 10983 // This is a singleton provider, but a user besides the 29 10984 // default user is asking to initialize a process it runs 30 10985 // in... well, no, it doesn't actually run in this process, 31 10986 // it runs in the process of the default user. Get rid of it. 32 10987 providers.remove(i); 33 10988 N--; 34 10989 i--; 35 10990 continue; 36 10991 } 37 10992 38 10993 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 39 10994 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId); 40 10995 if (cpr == null) { 41 10996 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton); 42 10997 mProviderMap.putProviderByClass(comp, cpr); 43 10998 } 44 10999 if (DEBUG_MU) Slog.v(TAG_MU, 45 11000 "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid); 46 11001 app.pubProviders.put(cpi.name, cpr); 47 11002 if (!cpi.multiprocess || !"android".equals(cpi.packageName)) { 48 11003 // Don't add this if it is a platform component that is marked 49 11004 // to run in multiple processes, because this is actually 50 11005 // part of the framework so doesn't make sense to track as a 51 11006 // separate apk in the process. 52 11007 app.addPackage(cpi.applicationInfo.packageName, cpi.applicationInfo.versionCode, 53 11008 mProcessStats); 54 11009 } 55 11010 notifyPackageUse(cpi.applicationInfo.packageName, 56 11011 PackageManager.NOTIFY_PACKAGE_USE_CONTENT_PROVIDER); 57 11012 } 58 11013 } 59 11014 return providers; 60 11015 } 61 11016 62 11017 /** 63 11018 * Check if the calling UID has a possible chance at accessing the provider 64 11019 * at the given authority and user. 65 11020 */ 66 11021 public String checkContentProviderAccess(String authority, int userId) { 67 11022 if (userId == UserHandle.USER_ALL) { 68 11023 mContext.enforceCallingOrSelfPermission( 69 11024 Manifest.permission.INTERACT_ACROSS_USERS_FULL, TAG); 70 11025 userId = UserHandle.getCallingUserId(); 71 11026 } 72 11027 73 11028 ProviderInfo cpi = null; 74 11029 try { 75 11030 cpi = AppGlobals.getPackageManager().resolveContentProvider(authority, 76 11031 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS 77 11032 | PackageManager.MATCH_DISABLED_COMPONENTS 78 11033 | PackageManager.MATCH_DIRECT_BOOT_AWARE 79 11034 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 80 11035 userId); 81 11036 } catch (RemoteException ignored) { 82 11037 } 83 11038 if (cpi == null) { 84 11039 return "Failed to find provider " + authority + " for user " + userId 85 11040 + "; expected to find a valid ContentProvider for this authority"; 86 11041 } 87 11042 88 11043 ProcessRecord r = null; 89 11044 synchronized (mPidsSelfLocked) { 90 11045 r = mPidsSelfLocked.get(Binder.getCallingPid()); 91 11046 } 92 11047 if (r == null) { 93 11048 return "Failed to find PID " + Binder.getCallingPid(); 94 11049 } 95 11050 96 11051 synchronized (this) { 97 11052 return checkContentProviderPermissionLocked(cpi, r, userId, true); 98 11053 } 99 11054 } 100 11055 101 11056 /** 102 11057 * Check if {@link ProcessRecord} has a possible chance at accessing the 103 11058 * given {@link ProviderInfo}. Final permission checking is always done 104 11059 * in {@link ContentProvider}. 105 11060 */ 106 11061 private final String checkContentProviderPermissionLocked( 107 11062 ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser) { 108 11063 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid(); 109 11064 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid(); 110 11065 boolean checkedGrants = false; 111 11066 if (checkUser) { 112 11067 // Looking for cross-user grants before enforcing the typical cross-users permissions 113 11068 int tmpTargetUserId = mUserController.unsafeConvertIncomingUserLocked(userId); 114 11069 if (tmpTargetUserId != UserHandle.getUserId(callingUid)) { 115 11070 if (checkAuthorityGrants(callingUid, cpi, tmpTargetUserId, checkUser)) { 116 11071 return null; 117 11072 } 118 11073 checkedGrants = true; 119 11074 } 120 11075 userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, false, 121 11076 ALLOW_NON_FULL, "checkContentProviderPermissionLocked " + cpi.authority, null); 122 11077 if (userId != tmpTargetUserId) { 123 11078 // When we actually went to determine the final targer user ID, this ended 124 11079 // up different than our initial check for the authority. This is because 125 11080 // they had asked for USER_CURRENT_OR_SELF and we ended up switching to 126 11081 // SELF. So we need to re-check the grants again. 127 11082 checkedGrants = false; 128 11083 } 129 11084 } 130 11085 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid, 131 11086 cpi.applicationInfo.uid, cpi.exported) 132 11087 == PackageManager.PERMISSION_GRANTED) { 133 11088 return null; 134 11089 } 135 11090 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid, 136 11091 cpi.applicationInfo.uid, cpi.exported) 137 11092 == PackageManager.PERMISSION_GRANTED) { 138 11093 return null; 139 11094 } 140 11095 141 11096 PathPermission[] pps = cpi.pathPermissions; 142 11097 if (pps != null) { 143 11098 int i = pps.length; 144 11099 while (i > 0) { 145 11100 i--; 146 11101 PathPermission pp = pps[i]; 147 11102 String pprperm = pp.getReadPermission(); 148 11103 if (pprperm != null && checkComponentPermission(pprperm, callingPid, callingUid, 149 11104 cpi.applicationInfo.uid, cpi.exported) 150 11105 == PackageManager.PERMISSION_GRANTED) { 151 11106 return null; 152 11107 } 153 11108 String ppwperm = pp.getWritePermission(); 154 11109 if (ppwperm != null && checkComponentPermission(ppwperm, callingPid, callingUid, 155 11110 cpi.applicationInfo.uid, cpi.exported) 156 11111 == PackageManager.PERMISSION_GRANTED) { 157 11112 return null; 158 11113 } 159 11114 } 160 11115 } 161 11116 if (!checkedGrants && checkAuthorityGrants(callingUid, cpi, userId, checkUser)) { 162 11117 return null; 163 11118 } 164 11119 165 11120 final String suffix; 166 11121 if (!cpi.exported) { 167 11122 suffix = " that is not exported from UID " + cpi.applicationInfo.uid; 168 11123 } else if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(cpi.readPermission)) { 169 11124 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs"; 170 11125 } else { 171 11126 suffix = " requires " + cpi.readPermission + " or " + cpi.writePermission; 172 11127 } 173 11128 final String msg = "Permission Denial: opening provider " + cpi.name 174 11129 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid 175 11130 + ", uid=" + callingUid + ")" + suffix; 176 11131 Slog.w(TAG, msg); 177 11132 return msg; 178 11133 } 179 11134 180 11135 /** 181 11136 * Returns if the ContentProvider has granted a uri to callingUid 182 11137 */ 183 11138 boolean checkAuthorityGrants(int callingUid, ProviderInfo cpi, int userId, boolean checkUser) { 184 11139 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(callingUid); 185 11140 if (perms != null) { 186 11141 for (int i=perms.size()-1; i>=0; i--) { 187 11142 GrantUri grantUri = perms.keyAt(i); 188 11143 if (grantUri.sourceUserId == userId || !checkUser) { 189 11144 if (matchesProvider(grantUri.uri, cpi)) { 190 11145 return true; 191 11146 } 192 11147 } 193 11148 } 194 11149 } 195 11150 return false; 196 11151 } 197 11152 198 11153 /** 199 11154 * Returns true if the uri authority is one of the authorities specified in the provider. 200 11155 */ 201 11156 boolean matchesProvider(Uri uri, ProviderInfo cpi) { 202 11157 String uriAuth = uri.getAuthority(); 203 11158 String cpiAuth = cpi.authority; 204 11159 if (cpiAuth.indexOf(';') == -1) { 205 11160 return cpiAuth.equals(uriAuth); 206 11161 } 207 11162 String[] cpiAuths = cpiAuth.split(";"); 208 11163 int length = cpiAuths.length; 209 11164 for (int i = 0; i < length; i++) { 210 11165 if (cpiAuths[i].equals(uriAuth)) return true; 211 11166 } 212 11167 return false; 213 11168 } 214 11169 215 11170 ContentProviderConnection incProviderCountLocked(ProcessRecord r, 216 11171 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) { 217 11172 if (r != null) { 218 11173 for (int i=0; i<r.conProviders.size(); i++) { 219 11174 ContentProviderConnection conn = r.conProviders.get(i); 220 11175 if (conn.provider == cpr) { 221 11176 if (DEBUG_PROVIDER) Slog.v(TAG_PROVIDER, 222 11177 "Adding provider requested by " 223 11178 + r.processName + " from process " 224 11179 + cpr.info.processName + ": " + cpr.name.flattenToShortString() 225 11180 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount); 226 11181 if (stable) { 227 11182 conn.stableCount++; 228 11183 conn.numStableIncs++; 229 11184 } else { 230 11185 conn.unstableCount++; 231 11186 conn.numUnstableIncs++; 232 11187 } 233 11188 return conn; 234 11189 } 235 11190 } 236 11191 ContentProviderConnection conn = new ContentProviderConnection(cpr, r); 237 11192 if (stable) { 238 11193 conn.stableCount = 1; 239 11194 conn.numStableIncs = 1; 240 11195 } else { 241 11196 conn.unstableCount = 1; 242 11197 conn.numUnstableIncs = 1; 243 11198 } 244 11199 cpr.connections.add(conn); 245 11200 r.conProviders.add(conn); 246 11201 startAssociationLocked(r.uid, r.processName, r.curProcState, 247 11202 cpr.uid, cpr.name, cpr.info.processName); 248 11203 return conn; 249 11204 } 250 11205 cpr.addExternalProcessHandleLocked(externalProcessToken); 251 11206 return null; 252 11207 } 253 11208 254 11209 boolean decProviderCountLocked(ContentProviderConnection conn, 255 11210 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) { 256 11211 if (conn != null) { 257 11212 cpr = conn.provider; 258 11213 if (DEBUG_PROVIDER) Slog.v(TAG_PROVIDER, 259 11214 "Removing provider requested by " 260 11215 + conn.client.processName + " from process " 261 11216 + cpr.info.processName + ": " + cpr.name.flattenToShortString() 262 11217 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount); 263 11218 if (stable) { 264 11219 conn.stableCount--; 265 11220 } else { 266 11221 conn.unstableCount--; 267 11222 } 268 11223 if (conn.stableCount == 0 && conn.unstableCount == 0) { 269 11224 cpr.connections.remove(conn); 270 11225 conn.client.conProviders.remove(conn); 271 11226 if (conn.client.setProcState < ActivityManager.PROCESS_STATE_LAST_ACTIVITY) { 272 11227 // The client is more important than last activity -- note the time this 273 11228 // is happening, so we keep the old provider process around a bit as last 274 11229 // activity to avoid thrashing it. 275 11230 if (cpr.proc != null) { 276 11231 cpr.proc.lastProviderTime = SystemClock.uptimeMillis(); 277 11232 } 278 11233 } 279 11234 stopAssociationLocked(conn.client.uid, conn.client.processName, cpr.uid, cpr.name); 280 11235 return true; 281 11236 } 282 11237 return false; 283 11238 } 284 11239 cpr.removeExternalProcessHandleLocked(externalProcessToken); 285 11240 return false; 286 11241 } 287 11242 288 11243 private void checkTime(long startTime, String where) { 289 11244 long now = SystemClock.uptimeMillis(); 290 11245 if ((now-startTime) > 50) { 291 11246 // If we are taking more than 50ms, log about it. 292 11247 Slog.w(TAG, "Slow operation: " + (now-startTime) + "ms so far, now at " + where); 293 11248 } 294 11249 } 295 11250 296 11251 private static final int[] PROCESS_STATE_STATS_FORMAT = new int[] { 297 11252 PROC_SPACE_TERM, 298 11253 PROC_SPACE_TERM|PROC_PARENS, 299 11254 PROC_SPACE_TERM|PROC_CHAR|PROC_OUT_LONG, // 3: process state 300 11255 }; 301 11256 302 11257 private final long[] mProcessStateStatsLongs = new long[1]; 303 11258 304 11259 boolean isProcessAliveLocked(ProcessRecord proc) { 305 11260 if (proc.procStatFile == null) { 306 11261 proc.procStatFile = "/proc/" + proc.pid + "/stat"; 307 11262 } 308 11263 mProcessStateStatsLongs[0] = 0; 309 11264 if (!readProcFile(proc.procStatFile, PROCESS_STATE_STATS_FORMAT, null, 310 11265 mProcessStateStatsLongs, null)) { 311 11266 if (DEBUG_OOM_ADJ) Slog.d(TAG, "UNABLE TO RETRIEVE STATE FOR " + proc.procStatFile); 312 11267 return false; 313 11268 } 314 11269 final long state = mProcessStateStatsLongs[0]; 315 11270 if (DEBUG_OOM_ADJ) Slog.d(TAG, "RETRIEVED STATE FOR " + proc.procStatFile + ": " 316 11271 + (char)state); 317 11272 return state != 'Z' && state != 'X' && state != 'x' && state != 'K'; 318 11273 } 319 11274 320 11275 private ContentProviderHolder getContentProviderImpl(IApplicationThread caller, 321 11276 String name, IBinder token, boolean stable, int userId) { 322 11277 ContentProviderRecord cpr; 323 11278 ContentProviderConnection conn = null; 324 11279 ProviderInfo cpi = null; 325 11280 326 11281 synchronized(this) { 327 11282 long startTime = SystemClock.uptimeMillis(); 328 11283 329 11284 ProcessRecord r = null; 330 11285 if (caller != null) { 331 11286 r = getRecordForAppLocked(caller); 332 11287 if (r == null) { 333 11288 throw new SecurityException( 334 11289 "Unable to find app for caller " + caller 335 11290 + " (pid=" + Binder.getCallingPid() 336 11291 + ") when getting content provider " + name); 337 11292 } 338 11293 } 339 11294 340 11295 boolean checkCrossUser = true; 341 11296 342 11297 checkTime(startTime, "getContentProviderImpl: getProviderByName"); 343 11298 344 11299 // First check if this content provider has been published... 345 11300 cpr = mProviderMap.getProviderByName(name, userId); 346 11301 // If that didn't work, check if it exists for user 0 and then 347 11302 // verify that it's a singleton provider before using it. 348 11303 if (cpr == null && userId != UserHandle.USER_SYSTEM) { 349 11304 cpr = mProviderMap.getProviderByName(name, UserHandle.USER_SYSTEM); 350 11305 if (cpr != null) { 351 11306 cpi = cpr.info; 352 11307 if (isSingleton(cpi.processName, cpi.applicationInfo, 353 11308 cpi.name, cpi.flags) 354 11309 && isValidSingletonCall(r.uid, cpi.applicationInfo.uid)) { 355 11310 userId = UserHandle.USER_SYSTEM; 356 11311 checkCrossUser = false; 357 11312 } else { 358 11313 cpr = null; 359 11314 cpi = null; 360 11315 } 361 11316 } 362 11317 } 363 11318 364 11319 boolean providerRunning = cpr != null && cpr.proc != null && !cpr.proc.killed; 365 11320 if (providerRunning) { 366 11321 cpi = cpr.info; 367 11322 String msg; 368 11323 checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission"); 369 11324 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser)) 370 11325 != null) { 371 11326 throw new SecurityException(msg); 372 11327 } 373 11328 checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission"); 374 11329 375 11330 if (r != null && cpr.canRunHere(r)) { 376 11331 // This provider has been published or is in the process 377 11332 // of being published... but it is also allowed to run 378 11333 // in the caller's process, so don't make a connection 379 11334 // and just let the caller instantiate its own instance. 380 11335 ContentProviderHolder holder = cpr.newHolder(null); 381 11336 // don't give caller the provider object, it needs 382 11337 // to make its own. 383 11338 holder.provider = null; 384 11339 return holder; 385 11340 } 386 11341 // Don't expose providers between normal apps and instant apps 387 11342 try { 388 11343 if (AppGlobals.getPackageManager() 389 11344 .resolveContentProvider(name, 0 /*flags*/, userId) == null) { 390 11345 return null; 391 11346 } 392 11347 } catch (RemoteException e) { 393 11348 } 394 11349 395 11350 final long origId = Binder.clearCallingIdentity(); 396 11351 397 11352 checkTime(startTime, "getContentProviderImpl: incProviderCountLocked"); 398 11353 399 11354 // In this case the provider instance already exists, so we can 400 11355 // return it right away. 401 11356 conn = incProviderCountLocked(r, cpr, token, stable); 402 11357 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) { 403 11358 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) { 404 11359 // If this is a perceptible app accessing the provider, 405 11360 // make sure to count it as being accessed and thus 406 11361 // back up on the LRU list. This is good because 407 11362 // content providers are often expensive to start. 408 11363 checkTime(startTime, "getContentProviderImpl: before updateLruProcess"); 409 11364 updateLruProcessLocked(cpr.proc, false, null); 410 11365 checkTime(startTime, "getContentProviderImpl: after updateLruProcess"); 411 11366 } 412 11367 } 413 11368 414 11369 checkTime(startTime, "getContentProviderImpl: before updateOomAdj"); 415 11370 final int verifiedAdj = cpr.proc.verifiedAdj; 416 11371 boolean success = updateOomAdjLocked(cpr.proc, true); 417 11372 // XXX things have changed so updateOomAdjLocked doesn't actually tell us 418 11373 // if the process has been successfully adjusted. So to reduce races with 419 11374 // it, we will check whether the process still exists. Note that this doesn't 420 11375 // completely get rid of races with LMK killing the process, but should make 421 11376 // them much smaller. 422 11377 if (success && verifiedAdj != cpr.proc.setAdj && !isProcessAliveLocked(cpr.proc)) { 423 11378 success = false; 424 11379 } 425 11380 maybeUpdateProviderUsageStatsLocked(r, cpr.info.packageName, name); 426 11381 checkTime(startTime, "getContentProviderImpl: after updateOomAdj"); 427 11382 if (DEBUG_PROVIDER) Slog.i(TAG_PROVIDER, "Adjust success: " + success); 428 11383 // NOTE: there is still a race here where a signal could be 429 11384 // pending on the process even though we managed to update its 430 11385 // adj level. Not sure what to do about this, but at least 431 11386 // the race is now smaller. 432 11387 if (!success) { 433 11388 // Uh oh... it looks like the provider's process 434 11389 // has been killed on us. We need to wait for a new 435 11390 // process to be started, and make sure its death 436 11391 // doesn't kill our process. 437 11392 Slog.i(TAG, "Existing provider " + cpr.name.flattenToShortString() 438 11393 + " is crashing; detaching " + r); 439 11394 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable); 440 11395 checkTime(startTime, "getContentProviderImpl: before appDied"); 441 11396 appDiedLocked(cpr.proc); 442 11397 checkTime(startTime, "getContentProviderImpl: after appDied"); 443 11398 if (!lastRef) { 444 11399 // This wasn't the last ref our process had on 445 11400 // the provider... we have now been killed, bail. 446 11401 return null; 447 11402 } 448 11403 providerRunning = false; 449 11404 conn = null; 450 11405 } else { 451 11406 cpr.proc.verifiedAdj = cpr.proc.setAdj; 452 11407 } 453 11408 454 11409 Binder.restoreCallingIdentity(origId); 455 11410 } 456 11411 457 11412 if (!providerRunning) { 458 11413 try { 459 11414 checkTime(startTime, "getContentProviderImpl: before resolveContentProvider"); 460 11415 cpi = AppGlobals.getPackageManager(). 461 11416 resolveContentProvider(name, 462 11417 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId); 463 11418 checkTime(startTime, "getContentProviderImpl: after resolveContentProvider"); 464 11419 } catch (RemoteException ex) { 465 11420 } 466 11421 if (cpi == null) { 467 11422 return null; 468 11423 } 469 11424 // If the provider is a singleton AND 470 11425 // (it's a call within the same user || the provider is a 471 11426 // privileged app) 472 11427 // Then allow connecting to the singleton provider 473 11428 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo, 474 11429 cpi.name, cpi.flags) 475 11430 && isValidSingletonCall(r.uid, cpi.applicationInfo.uid); 476 11431 if (singleton) { 477 11432 userId = UserHandle.USER_SYSTEM; 478 11433 } 479 11434 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId); 480 11435 checkTime(startTime, "getContentProviderImpl: got app info for user"); 481 11436 482 11437 String msg; 483 11438 checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission"); 484 11439 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, !singleton)) 485 11440 != null) { 486 11441 throw new SecurityException(msg); 487 11442 } 488 11443 checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission"); 489 11444 490 11445 if (!mProcessesReady 491 11446 && !cpi.processName.equals("system")) { 492 11447 // If this content provider does not run in the system 493 11448 // process, and the system is not yet ready to run other 494 11449 // processes, then fail fast instead of hanging. 495 11450 throw new IllegalArgumentException( 496 11451 "Attempt to launch content provider before system ready"); 497 11452 } 498 11453 499 11454 // Make sure that the user who owns this provider is running. If not, 500 11455 // we don't want to allow it to run. 501 11456 if (!mUserController.isUserRunningLocked(userId, 0)) { 502 11457 Slog.w(TAG, "Unable to launch app " 503 11458 + cpi.applicationInfo.packageName + "/" 504 11459 + cpi.applicationInfo.uid + " for provider " 505 11460 + name + ": user " + userId + " is stopped"); 506 11461 return null; 507 11462 } 508 11463 509 11464 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 510 11465 checkTime(startTime, "getContentProviderImpl: before getProviderByClass"); 511 11466 cpr = mProviderMap.getProviderByClass(comp, userId); 512 11467 checkTime(startTime, "getContentProviderImpl: after getProviderByClass"); 513 11468 final boolean firstClass = cpr == null; 514 11469 if (firstClass) { 515 11470 final long ident = Binder.clearCallingIdentity(); 516 11471 517 11472 // If permissions need a review before any of the app components can run, 518 11473 // we return no provider and launch a review activity if the calling app 519 11474 // is in the foreground. 520 11475 if (mPermissionReviewRequired) { 521 11476 if (!requestTargetProviderPermissionsReviewIfNeededLocked(cpi, r, userId)) { 522 11477 return null; 523 11478 } 524 11479 } 525 11480 526 11481 try { 527 11482 checkTime(startTime, "getContentProviderImpl: before getApplicationInfo"); 528 11483 ApplicationInfo ai = 529 11484 AppGlobals.getPackageManager(). 530 11485 getApplicationInfo( 531 11486 cpi.applicationInfo.packageName, 532 11487 STOCK_PM_FLAGS, userId); 533 11488 checkTime(startTime, "getContentProviderImpl: after getApplicationInfo"); 534 11489 if (ai == null) { 535 11490 Slog.w(TAG, "No package info for content provider " 536 11491 + cpi.name); 537 11492 return null; 538 11493 } 539 11494 ai = getAppInfoForUser(ai, userId); 540 11495 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton); 541 11496 } catch (RemoteException ex) { 542 11497 // pm is in same process, this will never happen. 543 11498 } finally { 544 11499 Binder.restoreCallingIdentity(ident); 545 11500 } 546 11501 } 547 11502 548 11503 checkTime(startTime, "getContentProviderImpl: now have ContentProviderRecord"); 549 11504 550 11505 if (r != null && cpr.canRunHere(r)) { 551 11506 // If this is a multiprocess provider, then just return its 552 11507 // info and allow the caller to instantiate it. Only do 553 11508 // this if the provider is the same user as the caller's 554 11509 // process, or can run as root (so can be in any process). 555 11510 return cpr.newHolder(null); 556 11511 } 557 11512 558 11513 if (DEBUG_PROVIDER) Slog.w(TAG_PROVIDER, "LAUNCHING REMOTE PROVIDER (myuid " 559 11514 + (r != null ? r.uid : null) + " pruid " + cpr.appInfo.uid + "): " 560 11515 + cpr.info.name + " callers=" + Debug.getCallers(6)); 561 11516 562 11517 // This is single process, and our app is now connecting to it. 563 11518 // See if we are already in the process of launching this 564 11519 // provider. 565 11520 final int N = mLaunchingProviders.size(); 566 11521 int i; 567 11522 for (i = 0; i < N; i++) { 568 11523 if (mLaunchingProviders.get(i) == cpr) { 569 11524 break; 570 11525 } 571 11526 } 572 11527 573 11528 // If the provider is not already being launched, then get it 574 11529 // started. 575 11530 if (i >= N) { 576 11531 final long origId = Binder.clearCallingIdentity(); 577 11532 578 11533 try { 579 11534 // Content provider is now in use, its package can't be stopped. 580 11535 try { 581 11536 checkTime(startTime, "getContentProviderImpl: before set stopped state"); 582 11537 AppGlobals.getPackageManager().setPackageStoppedState( 583 11538 cpr.appInfo.packageName, false, userId); 584 11539 checkTime(startTime, "getContentProviderImpl: after set stopped state"); 585 11540 } catch (RemoteException e) { 586 11541 } catch (IllegalArgumentException e) { 587 11542 Slog.w(TAG, "Failed trying to unstop package " 588 11543 + cpr.appInfo.packageName + ": " + e); 589 11544 } 590 11545 591 11546 // Use existing process if already started 592 11547 checkTime(startTime, "getContentProviderImpl: looking for process record"); 593 11548 ProcessRecord proc = getProcessRecordLocked( 594 11549 cpi.processName, cpr.appInfo.uid, false); 595 11550 if (proc != null && proc.thread != null && !proc.killed) { 596 11551 if (DEBUG_PROVIDER) Slog.d(TAG_PROVIDER, 597 11552 "Installing in existing process " + proc); 598 11553 if (!proc.pubProviders.containsKey(cpi.name)) { 599 11554 checkTime(startTime, "getContentProviderImpl: scheduling install"); 600 11555 proc.pubProviders.put(cpi.name, cpr); 601 11556 try { 602 11557 proc.thread.scheduleInstallProvider(cpi); 603 11558 } catch (RemoteException e) { 604 11559 } 605 11560 } 606 11561 } else { 607 11562 checkTime(startTime, "getContentProviderImpl: before start process"); 608 11563 proc = startProcessLocked(cpi.processName, 609 11564 cpr.appInfo, false, 0, "content provider", 610 11565 new ComponentName(cpi.applicationInfo.packageName, 611 11566 cpi.name), false, false, false); 612 11567 checkTime(startTime, "getContentProviderImpl: after start process"); 613 11568 if (proc == null) { 614 11569 Slog.w(TAG, "Unable to launch app " 615 11570 + cpi.applicationInfo.packageName + "/" 616 11571 + cpi.applicationInfo.uid + " for provider " 617 11572 + name + ": process is bad"); 618 11573 return null; 619 11574 } 620 11575 } 621 11576 cpr.launchingApp = proc; 622 11577 mLaunchingProviders.add(cpr); 623 11578 } finally { 624 11579 Binder.restoreCallingIdentity(origId); 625 11580 } 626 11581 } 627 11582 628 11583 checkTime(startTime, "getContentProviderImpl: updating data structures"); 629 11584 630 11585 // Make sure the provider is published (the same provider class 631 11586 // may be published under multiple names). 632 11587 if (firstClass) { 633 11588 mProviderMap.putProviderByClass(comp, cpr); 634 11589 } 635 11590 636 11591 mProviderMap.putProviderByName(name, cpr); 637 11592 conn = incProviderCountLocked(r, cpr, token, stable); 638 11593 if (conn != null) { 639 11594 conn.waiting = true; 640 11595 } 641 11596 } 642 11597 checkTime(startTime, "getContentProviderImpl: done!"); 643 11598 644 11599 grantEphemeralAccessLocked(userId, null /*intent*/, 645 11600 cpi.applicationInfo.uid, UserHandle.getAppId(Binder.getCallingUid())); 646 11601 } 647 11602 648 11603 // Wait for the provider to be published... 649 11604 synchronized (cpr) { 650 11605 while (cpr.provider == null) { 651 11606 if (cpr.launchingApp == null) { 652 11607 Slog.w(TAG, "Unable to launch app " 653 11608 + cpi.applicationInfo.packageName + "/" 654 11609 + cpi.applicationInfo.uid + " for provider " 655 11610 + name + ": launching app became null"); 656 11611 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS, 657 11612 UserHandle.getUserId(cpi.applicationInfo.uid), 658 11613 cpi.applicationInfo.packageName, 659 11614 cpi.applicationInfo.uid, name); 660 11615 return null; 661 11616 } 662 11617 try { 663 11618 if (DEBUG_MU) Slog.v(TAG_MU, 664 11619 "Waiting to start provider " + cpr 665 11620 + " launchingApp=" + cpr.launchingApp); 666 11621 if (conn != null) { 667 11622 conn.waiting = true; 668 11623 } 669 11624 cpr.wait(); 670 11625 } catch (InterruptedException ex) { 671 11626 } finally { 672 11627 if (conn != null) { 673 11628 conn.waiting = false; 674 11629 } 675 11630 } 676 11631 } 677 11632 } 678 11633 return cpr != null ? cpr.newHolder(conn) : null; 679 11634 } 680 11635 681 11636 private boolean requestTargetProviderPermissionsReviewIfNeededLocked(ProviderInfo cpi, 682 11637 ProcessRecord r, final int userId) { 683 11638 if (getPackageManagerInternalLocked().isPermissionsReviewRequired( 684 11639 cpi.packageName, userId)) { 685 11640 686 11641 final boolean callerForeground = r == null || r.setSchedGroup 687 11642 != ProcessList.SCHED_GROUP_BACKGROUND; 688 11643 689 11644 // Show a permission review UI only for starting from a foreground app 690 11645 if (!callerForeground) { 691 11646 Slog.w(TAG, "u" + userId + " Instantiating a provider in package" 692 11647 + cpi.packageName + " requires a permissions review"); 693 11648 return false; 694 11649 } 695 11650 696 11651 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS); 697 11652 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 698 11653 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 699 11654 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, cpi.packageName); 700 11655 701 11656 if (DEBUG_PERMISSIONS_REVIEW) { 702 11657 Slog.i(TAG, "u" + userId + " Launching permission review " 703 11658 + "for package " + cpi.packageName); 704 11659 } 705 11660 706 11661 final UserHandle userHandle = new UserHandle(userId); 707 11662 mHandler.post(new Runnable() { 708 11663 @Override 709 11664 public void run() { 710 11665 mContext.startActivityAsUser(intent, userHandle); 711 11666 } 712 11667 }); 713 11668 714 11669 return false; 715 11670 } 716 11671 717 11672 return true; 718 11673 } 719 11674 720 11675 PackageManagerInternal getPackageManagerInternalLocked() { 721 11676 if (mPackageManagerInt == null) { 722 11677 mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class); 723 11678 } 724 11679 return mPackageManagerInt; 725 11680 } 726 11681 727 11682 @Override 728 11683 public final ContentProviderHolder getContentProvider( 729 11684 IApplicationThread caller, String name, int userId, boolean stable) { 730 11685 enforceNotIsolatedCaller("getContentProvider"); 731 11686 if (caller == null) { 732 11687 String msg = "null IApplicationThread when getting content provider " 733 11688 + name; 734 11689 Slog.w(TAG, msg); 735 11690 throw new SecurityException(msg); 736 11691 } 737 11692 // The incoming user check is now handled in checkContentProviderPermissionLocked() to deal 738 11693 // with cross-user grant. 739 11694 return getContentProviderImpl(caller, name, null, stable, userId); 740 11695 } 741 11696 742 11697 public ContentProviderHolder getContentProviderExternal( 743 11698 String name, int userId, IBinder token) { 744 11699 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 745 11700 "Do not have permission in call getContentProviderExternal()"); 746 11701 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 747 11702 userId, false, ALLOW_FULL_ONLY, "getContentProvider", null); 748 11703 return getContentProviderExternalUnchecked(name, token, userId); 749 11704 } 750 11705 751 11706 private ContentProviderHolder getContentProviderExternalUnchecked(String name, 752 11707 IBinder token, int userId) { 753 11708 return getContentProviderImpl(null, name, token, true, userId); 754 11709 } 755 11710 756 11711 /** 757 11712 * Drop a content provider from a ProcessRecord's bookkeeping 758 11713 */ 759 11714 public void removeContentProvider(IBinder connection, boolean stable) { 760 11715 enforceNotIsolatedCaller("removeContentProvider"); 761 11716 long ident = Binder.clearCallingIdentity(); 762 11717 try { 763 11718 synchronized (this) { 764 11719 ContentProviderConnection conn; 765 11720 try { 766 11721 conn = (ContentProviderConnection)connection; 767 11722 } catch (ClassCastException e) { 768 11723 String msg ="removeContentProvider: " + connection 769 11724 + " not a ContentProviderConnection"; 770 11725 Slog.w(TAG, msg); 771 11726 throw new IllegalArgumentException(msg); 772 11727 } 773 11728 if (conn == null) { 774 11729 throw new NullPointerException("connection is null"); 775 11730 } 776 11731 if (decProviderCountLocked(conn, null, null, stable)) { 777 11732 updateOomAdjLocked(); 778 11733 } 779 11734 } 780 11735 } finally { 781 11736 Binder.restoreCallingIdentity(ident); 782 11737 } 783 11738 } 784 11739 785 11740 public void removeContentProviderExternal(String name, IBinder token) { 786 11741 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 787 11742 "Do not have permission in call removeContentProviderExternal()"); 788 11743 int userId = UserHandle.getCallingUserId(); 789 11744 long ident = Binder.clearCallingIdentity(); 790 11745 try { 791 11746 removeContentProviderExternalUnchecked(name, token, userId); 792 11747 } finally { 793 11748 Binder.restoreCallingIdentity(ident); 794 11749 } 795 11750 } 796 11751 797 11752 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) { 798 11753 synchronized (this) { 799 11754 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId); 800 11755 if(cpr == null) { 801 11756 //remove from mProvidersByClass 802 11757 if(DEBUG_ALL) Slog.v(TAG, name+" content provider not found in providers list"); 803 11758 return; 804 11759 } 805 11760 806 11761 //update content provider record entry info 807 11762 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name); 808 11763 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId); 809 11764 if (localCpr.hasExternalProcessHandles()) { 810 11765 if (localCpr.removeExternalProcessHandleLocked(token)) { 811 11766 updateOomAdjLocked(); 812 11767 } else { 813 11768 Slog.e(TAG, "Attmpt to remove content provider " + localCpr 814 11769 + " with no external reference for token: " 815 11770 + token + "."); 816 11771 } 817 11772 } else { 818 11773 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr 819 11774 + " with no external references."); 820 11775 } 821 11776 } 822 11777 } 823 11778 824 11779 public final void publishContentProviders(IApplicationThread caller, 825 11780 List<ContentProviderHolder> providers) { 826 11781 if (providers == null) { 827 11782 return; 828 11783 } 829 11784 830 11785 enforceNotIsolatedCaller("publishContentProviders"); 831 11786 synchronized (this) { 832 11787 final ProcessRecord r = getRecordForAppLocked(caller); 833 11788 if (DEBUG_MU) Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid); 834 11789 if (r == null) { 835 11790 throw new SecurityException( 836 11791 "Unable to find app for caller " + caller 837 11792 + " (pid=" + Binder.getCallingPid() 838 11793 + ") when publishing content providers"); 839 11794 } 840 11795 841 11796 final long origId = Binder.clearCallingIdentity(); 842 11797 843 11798 final int N = providers.size(); 844 11799 for (int i = 0; i < N; i++) { 845 11800 ContentProviderHolder src = providers.get(i); 846 11801 if (src == null || src.info == null || src.provider == null) { 847 11802 continue; 848 11803 } 849 11804 ContentProviderRecord dst = r.pubProviders.get(src.info.name); 850 11805 if (DEBUG_MU) Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid); 851 11806 if (dst != null) { 852 11807 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name); 853 11808 mProviderMap.putProviderByClass(comp, dst); 854 11809 String names[] = dst.info.authority.split(";"); 855 11810 for (int j = 0; j < names.length; j++) { 856 11811 mProviderMap.putProviderByName(names[j], dst); 857 11812 } 858 11813 859 11814 int launchingCount = mLaunchingProviders.size(); 860 11815 int j; 861 11816 boolean wasInLaunchingProviders = false; 862 11817 for (j = 0; j < launchingCount; j++) { 863 11818 if (mLaunchingProviders.get(j) == dst) { 864 11819 mLaunchingProviders.remove(j); 865 11820 wasInLaunchingProviders = true; 866 11821 j--; 867 11822 launchingCount--; 868 11823 } 869 11824 } 870 11825 if (wasInLaunchingProviders) { 871 11826 mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, r); 872 11827 } 873 11828 synchronized (dst) { 874 11829 dst.provider = src.provider; 875 11830 dst.proc = r; 876 11831 dst.notifyAll(); 877 11832 } 878 11833 updateOomAdjLocked(r, true); 879 11834 maybeUpdateProviderUsageStatsLocked(r, src.info.packageName, 880 11835 src.info.authority); 881 11836 } 882 11837 } 883 11838 884 11839 Binder.restoreCallingIdentity(origId); 885 11840 } 886 11841 } 887 11842 888 11843 public boolean refContentProvider(IBinder connection, int stable, int unstable) { 889 11844 ContentProviderConnection conn; 890 11845 try { 891 11846 conn = (ContentProviderConnection)connection; 892 11847 } catch (ClassCastException e) { 893 11848 String msg ="refContentProvider: " + connection 894 11849 + " not a ContentProviderConnection"; 895 11850 Slog.w(TAG, msg); 896 11851 throw new IllegalArgumentException(msg); 897 11852 } 898 11853 if (conn == null) { 899 11854 throw new NullPointerException("connection is null"); 900 11855 } 901 11856 902 11857 synchronized (this) { 903 11858 if (stable > 0) { 904 11859 conn.numStableIncs += stable; 905 11860 } 906 11861 stable = conn.stableCount + stable; 907 11862 if (stable < 0) { 908 11863 throw new IllegalStateException("stableCount < 0: " + stable); 909 11864 } 910 11865 911 11866 if (unstable > 0) { 912 11867 conn.numUnstableIncs += unstable; 913 11868 } 914 11869 unstable = conn.unstableCount + unstable; 915 11870 if (unstable < 0) { 916 11871 throw new IllegalStateException("unstableCount < 0: " + unstable); 917 11872 } 918 11873 919 11874 if ((stable+unstable) <= 0) { 920 11875 throw new IllegalStateException("ref counts can't go to zero here: stable=" 921 11876 + stable + " unstable=" + unstable); 922 11877 } 923 11878 conn.stableCount = stable; 924 11879 conn.unstableCount = unstable; 925 11880 return !conn.dead; 926 11881 } 927 11882 } 928 11883 929 11884 public void unstableProviderDied(IBinder connection) { 930 11885 ContentProviderConnection conn; 931 11886 try { 932 11887 conn = (ContentProviderConnection)connection; 933 11888 } catch (ClassCastException e) { 934 11889 String msg ="refContentProvider: " + connection 935 11890 + " not a ContentProviderConnection"; 936 11891 Slog.w(TAG, msg); 937 11892 throw new IllegalArgumentException(msg); 938 11893 } 939 11894 if (conn == null) { 940 11895 throw new NullPointerException("connection is null"); 941 11896 } 942 11897 943 11898 // Safely retrieve the content provider associated with the connection. 944 11899 IContentProvider provider; 945 11900 synchronized (this) { 946 11901 provider = conn.provider.provider; 947 11902 } 948 11903 949 11904 if (provider == null) { 950 11905 // Um, yeah, we're way ahead of you. 951 11906 return; 952 11907 } 953 11908 954 11909 // Make sure the caller is being honest with us. 955 11910 if (provider.asBinder().pingBinder()) { 956 11911 // Er, no, still looks good to us. 957 11912 synchronized (this) { 958 11913 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid() 959 11914 + " says " + conn + " died, but we don't agree"); 960 11915 return; 961 11916 } 962 11917 } 963 11918 964 11919 // Well look at that! It's dead! 965 11920 synchronized (this) { 966 11921 if (conn.provider.provider != provider) { 967 11922 // But something changed... good enough. 968 11923 return; 969 11924 } 970 11925 971 11926 ProcessRecord proc = conn.provider.proc; 972 11927 if (proc == null || proc.thread == null) { 973 11928 // Seems like the process is already cleaned up. 974 11929 return; 975 11930 } 976 11931 977 11932 // As far as we're concerned, this is just like receiving a 978 11933 // death notification... just a bit prematurely. 979 11934 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid 980 11935 + ") early provider death"); 981 11936 final long ident = Binder.clearCallingIdentity(); 982 11937 try { 983 11938 appDiedLocked(proc); 984 11939 } finally { 985 11940 Binder.restoreCallingIdentity(ident); 986 11941 } 987 11942 } 988 11943 } 989 11944 990 11945 @Override 991 11946 public void appNotRespondingViaProvider(IBinder connection) { 992 11947 enforceCallingPermission( 993 11948 android.Manifest.permission.REMOVE_TASKS, "appNotRespondingViaProvider()"); 994 11949 995 11950 final ContentProviderConnection conn = (ContentProviderConnection) connection; 996 11951 if (conn == null) { 997 11952 Slog.w(TAG, "ContentProviderConnection is null"); 998 11953 return; 999 11954 } 1000 11955 1001 11956 final ProcessRecord host = conn.provider.proc; 1002 11957 if (host == null) { 1003 11958 Slog.w(TAG, "Failed to find hosting ProcessRecord"); 1004 11959 return; 1005 11960 } 1006 11961 1007 11962 mHandler.post(new Runnable() { 1008 11963 @Override 1009 11964 public void run() { 1010 11965 mAppErrors.appNotResponding(host, null, null, false, 1011 11966 "ContentProvider not responding"); 1012 11967 } 1013 11968 }); 1014 11969 } 1015 11970 1016 11971 public final void installSystemProviders() { 1017 11972 List<ProviderInfo> providers; 1018 11973 synchronized (this) { 1019 11974 ProcessRecord app = mProcessNames.get("system", SYSTEM_UID); 1020 11975 providers = generateApplicationProvidersLocked(app); 1021 11976 if (providers != null) { 1022 11977 for (int i=providers.size()-1; i>=0; i--) { 1023 11978 ProviderInfo pi = (ProviderInfo)providers.get(i); 1024 11979 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) { 1025 11980 Slog.w(TAG, "Not installing system proc provider " + pi.name 1026 11981 + ": not system .apk"); 1027 11982 providers.remove(i); 1028 11983 } 1029 11984 } 1030 11985 } 1031 11986 } 1032 11987 if (providers != null) { 1033 11988 mSystemThread.installSystemProviders(providers); 1034 11989 } 1035 11990 1036 11991 mConstants.start(mContext.getContentResolver()); 1037 11992 mCoreSettingsObserver = new CoreSettingsObserver(this); 1038 11993 mFontScaleSettingObserver = new FontScaleSettingObserver(); 1039 11994 1040 11995 // Now that the settings provider is published we can consider sending 1041 11996 // in a rescue party. 1042 11997 RescueParty.onSettingsProviderPublished(mContext); 1043 11998 1044 11999 //mUsageStatsService.monitorPackages(); 1045 12000 } 1046 12001 1047 12002 private void startPersistentApps(int matchFlags) { 1048 12003 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return; 1049 12004 1050 12005 synchronized (this) { 1051 12006 try { 1052 12007 final List<ApplicationInfo> apps = AppGlobals.getPackageManager() 1053 12008 .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList(); 1054 12009 for (ApplicationInfo app : apps) { 1055 12010 if (!"android".equals(app.packageName)) { 1056 12011 addAppLocked(app, null, false, null /* ABI override */); 1057 12012 } 1058 12013 } 1059 12014 } catch (RemoteException ex) { 1060 12015 } 1061 12016 } 1062 12017 } 1063 12018 1064 12019 /** 1065 12020 * When a user is unlocked, we need to install encryption-unaware providers 1066 12021 * belonging to any running apps. 1067 12022 */ 1068 12023 private void installEncryptionUnawareProviders(int userId) { 1069 12024 // We're only interested in providers that are encryption unaware, and 1070 12025 // we don't care about uninstalled apps, since there's no way they're 1071 12026 // running at this point. 1072 12027 final int matchFlags = GET_PROVIDERS | MATCH_DIRECT_BOOT_UNAWARE; 1073 12028 1074 12029 synchronized (this) { 1075 12030 final int NP = mProcessNames.getMap().size(); 1076 12031 for (int ip = 0; ip < NP; ip++) { 1077 12032 final SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 1078 12033 final int NA = apps.size(); 1079 12034 for (int ia = 0; ia < NA; ia++) { 1080 12035 final ProcessRecord app = apps.valueAt(ia); 1081 12036 if (app.userId != userId || app.thread == null || app.unlocked) continue; 1082 12037 1083 12038 final int NG = app.pkgList.size(); 1084 12039 for (int ig = 0; ig < NG; ig++) { 1085 12040 try { 1086 12041 final String pkgName = app.pkgList.keyAt(ig); 1087 12042 final PackageInfo pkgInfo = AppGlobals.getPackageManager() 1088 12043 .getPackageInfo(pkgName, matchFlags, userId); 1089 12044 if (pkgInfo != null && !ArrayUtils.isEmpty(pkgInfo.providers)) { 1090 12045 for (ProviderInfo pi : pkgInfo.providers) { 1091 12046 // TODO: keep in sync with generateApplicationProvidersLocked 1092 12047 final boolean processMatch = Objects.equals(pi.processName, 1093 12048 app.processName) || pi.multiprocess; 1094 12049 final boolean userMatch = isSingleton(pi.processName, 1095 12050 pi.applicationInfo, pi.name, pi.flags) 1096 12051 ? (app.userId == UserHandle.USER_SYSTEM) : true; 1097 12052 if (processMatch && userMatch) { 1098 12053 Log.v(TAG, "Installing " + pi); 1099 12054 app.thread.scheduleInstallProvider(pi); 1100 12055 } else { 1101 12056 Log.v(TAG, "Skipping " + pi); 1102 12057 } 1103 12058 } 1104 12059 } 1105 12060 } catch (RemoteException ignored) { 1106 12061 } 1107 12062 } 1108 12063 } 1109 12064 } 1110 12065 } 1111 12066 } 1112 12067 1113 12068 /** 1114 12069 * Allows apps to retrieve the MIME type of a URI. 1115 12070 * If an app is in the same user as the ContentProvider, or if it is allowed to interact across 1116 12071 * users, then it does not need permission to access the ContentProvider. 1117 12072 * Either, it needs cross-user uri grants. 1118 12073 * 1119 12074 * CTS tests for this functionality can be run with "runtest cts-appsecurity". 1120 12075 * 1121 12076 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/ 1122 12077 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java 1123 12078 */ 1124 12079 public String getProviderMimeType(Uri uri, int userId) { 1125 12080 enforceNotIsolatedCaller("getProviderMimeType"); 1126 12081 final String name = uri.getAuthority(); 1127 12082 int callingUid = Binder.getCallingUid(); 1128 12083 int callingPid = Binder.getCallingPid(); 1129 12084 long ident = 0; 1130 12085 boolean clearedIdentity = false; 1131 12086 synchronized (this) { 1132 12087 userId = mUserController.unsafeConvertIncomingUserLocked(userId); 1133 12088 } 1134 12089 if (canClearIdentity(callingPid, callingUid, userId)) { 1135 12090 clearedIdentity = true; 1136 12091 ident = Binder.clearCallingIdentity(); 1137 12092 } 1138 12093 ContentProviderHolder holder = null; 1139 12094 try { 1140 12095 holder = getContentProviderExternalUnchecked(name, null, userId); 1141 12096 if (holder != null) { 1142 12097 return holder.provider.getType(uri); 1143 12098 } 1144 12099 } catch (RemoteException e) { 1145 12100 Log.w(TAG, "Content provider dead retrieving " + uri, e); 1146 12101 return null; 1147 12102 } catch (Exception e) { 1148 12103 Log.w(TAG, "Exception while determining type of " + uri, e); 1149 12104 return null; 1150 12105 } finally { 1151 12106 // We need to clear the identity to call removeContentProviderExternalUnchecked 1152 12107 if (!clearedIdentity) { 1153 12108 ident = Binder.clearCallingIdentity(); 1154 12109 } 1155 12110 try { 1156 12111 if (holder != null) { 1157 12112 removeContentProviderExternalUnchecked(name, null, userId); 1158 12113 } 1159 12114 } finally { 1160 12115 Binder.restoreCallingIdentity(ident); 1161 12116 } 1162 12117 } 1163 12118 1164 12119 return null; 1165 12120 } 1166 12121 1167 12122 private boolean canClearIdentity(int callingPid, int callingUid, int userId) { 1168 12123 if (UserHandle.getUserId(callingUid) == userId) { 1169 12124 return true; 1170 12125 } 1171 12126 if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid, 1172 12127 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED 1173 12128 || checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid, 1174 12129 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) { 1175 12130 return true; 1176 12131 } 1177 12132 return false; 1178 12133 }
创建新的process record
1 12135 // ========================================================= 2 12136 // GLOBAL MANAGEMENT 3 12137 // ========================================================= 4 12138 5 12139 final ProcessRecord newProcessRecordLocked(ApplicationInfo info, String customProcess, 6 12140 boolean isolated, int isolatedUid) { 7 12141 String proc = customProcess != null ? customProcess : info.processName; 8 12142 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 9 12143 final int userId = UserHandle.getUserId(info.uid); 10 12144 int uid = info.uid; 11 12145 if (isolated) { 12 12146 if (isolatedUid == 0) { 13 12147 int stepsLeft = LAST_ISOLATED_UID - FIRST_ISOLATED_UID + 1; 14 12148 while (true) { 15 12149 if (mNextIsolatedProcessUid < FIRST_ISOLATED_UID 16 12150 || mNextIsolatedProcessUid > LAST_ISOLATED_UID) { 17 12151 mNextIsolatedProcessUid = FIRST_ISOLATED_UID; 18 12152 } 19 12153 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid); 20 12154 mNextIsolatedProcessUid++; 21 12155 if (mIsolatedProcesses.indexOfKey(uid) < 0) { 22 12156 // No process for this uid, use it. 23 12157 break; 24 12158 } 25 12159 stepsLeft--; 26 12160 if (stepsLeft <= 0) { 27 12161 return null; 28 12162 } 29 12163 } 30 12164 } else { 31 12165 // Special case for startIsolatedProcess (internal only), where 32 12166 // the uid of the isolated process is specified by the caller. 33 12167 uid = isolatedUid; 34 12168 } 35 12169 getPackageManagerInternalLocked().addIsolatedUid(uid, info.uid); 36 12170 37 12171 // Register the isolated UID with this application so BatteryStats knows to 38 12172 // attribute resource usage to the application. 39 12173 // 40 12174 // NOTE: This is done here before addProcessNameLocked, which will tell BatteryStats 41 12175 // about the process state of the isolated UID *before* it is registered with the 42 12176 // owning application. 43 12177 mBatteryStatsService.addIsolatedUid(uid, info.uid); 44 12178 } 45 12179 final ProcessRecord r = new ProcessRecord(stats, info, proc, uid); 46 12180 if (!mBooted && !mBooting 47 12181 && userId == UserHandle.USER_SYSTEM 48 12182 && (info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) { 49 12183 r.persistent = true; 50 12184 r.maxAdj = ProcessList.PERSISTENT_PROC_ADJ; 51 12185 } 52 12186 addProcessNameLocked(r); 53 12187 return r; 54 12188 }
后台白名单相关
1 12190 private boolean uidOnBackgroundWhitelist(final int uid) { 2 12191 final int appId = UserHandle.getAppId(uid); 3 12192 final int[] whitelist = mBackgroundAppIdWhitelist; 4 12193 final int N = whitelist.length; 5 12194 for (int i = 0; i < N; i++) { 6 12195 if (appId == whitelist[i]) { 7 12196 return true; 8 12197 } 9 12198 } 10 12199 return false; 11 12200 } 12 12201 13 12202 @Override 14 12203 public void backgroundWhitelistUid(final int uid) { 15 12204 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16 12205 throw new SecurityException("Only the OS may call backgroundWhitelistUid()"); 17 12206 } 18 12207 19 12208 if (DEBUG_BACKGROUND_CHECK) { 20 12209 Slog.i(TAG, "Adding uid " + uid + " to bg uid whitelist"); 21 12210 } 22 12211 synchronized (this) { 23 12212 final int N = mBackgroundAppIdWhitelist.length; 24 12213 int[] newList = new int[N+1]; 25 12214 System.arraycopy(mBackgroundAppIdWhitelist, 0, newList, 0, N); 26 12215 newList[N] = UserHandle.getAppId(uid); 27 12216 mBackgroundAppIdWhitelist = newList; 28 12217 } 29 12218 }
添加app
1 12220 final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, 2 12221 String abiOverride) { 3 12222 ProcessRecord app; 4 12223 if (!isolated) { 5 12224 app = getProcessRecordLocked(customProcess != null ? customProcess : info.processName, 6 12225 info.uid, true); 7 12226 } else { 8 12227 app = null; 9 12228 } 10 12229 11 12230 if (app == null) { 12 12231 app = newProcessRecordLocked(info, customProcess, isolated, 0); 13 12232 updateLruProcessLocked(app, false, null); 14 12233 updateOomAdjLocked(); 15 12234 } 16 12235 17 12236 // This package really, really can not be stopped. 18 12237 try { 19 12238 AppGlobals.getPackageManager().setPackageStoppedState( 20 12239 info.packageName, false, UserHandle.getUserId(app.uid)); 21 12240 } catch (RemoteException e) { 22 12241 } catch (IllegalArgumentException e) { 23 12242 Slog.w(TAG, "Failed trying to unstop package " 24 12243 + info.packageName + ": " + e); 25 12244 } 26 12245 27 12246 if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) { 28 12247 app.persistent = true; 29 12248 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ; 30 12249 } 31 12250 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) { 32 12251 mPersistentStartingProcesses.add(app); 33 12252 startProcessLocked(app, "added application", 34 12253 customProcess != null ? customProcess : app.processName, abiOverride, 35 12254 null /* entryPoint */, null /* entryPointArgs */); 36 12255 } 37 12256 38 12257 return app; 39 12258 } 40 12259
un handle back
1 12260 public void unhandledBack() { 2 12261 enforceCallingPermission(android.Manifest.permission.FORCE_BACK, 3 12262 "unhandledBack()"); 4 12263 5 12264 synchronized(this) { 6 12265 final long origId = Binder.clearCallingIdentity(); 7 12266 try { 8 12267 getFocusedStack().unhandledBackLocked(); 9 12268 } finally { 10 12269 Binder.restoreCallingIdentity(origId); 11 12270 } 12 12271 } 13 12272 }
打开content uri
1 12274 public ParcelFileDescriptor openContentUri(String uriString) throws RemoteException { 2 12275 enforceNotIsolatedCaller("openContentUri"); 3 12276 final int userId = UserHandle.getCallingUserId(); 4 12277 final Uri uri = Uri.parse(uriString); 5 12278 String name = uri.getAuthority(); 6 12279 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId); 7 12280 ParcelFileDescriptor pfd = null; 8 12281 if (cph != null) { 9 12282 // We record the binder invoker's uid in thread-local storage before 10 12283 // going to the content provider to open the file. Later, in the code 11 12284 // that handles all permissions checks, we look for this uid and use 12 12285 // that rather than the Activity Manager's own uid. The effect is that 13 12286 // we do the check against the caller's permissions even though it looks 14 12287 // to the content provider like the Activity Manager itself is making 15 12288 // the request. 16 12289 Binder token = new Binder(); 17 12290 sCallerIdentity.set(new Identity( 18 12291 token, Binder.getCallingPid(), Binder.getCallingUid())); 19 12292 try { 20 12293 pfd = cph.provider.openFile(null, uri, "r", null, token); 21 12294 } catch (FileNotFoundException e) { 22 12295 // do nothing; pfd will be returned null 23 12296 } finally { 24 12297 // Ensure that whatever happens, we clean up the identity state 25 12298 sCallerIdentity.remove(); 26 12299 // Ensure we're done with the provider. 27 12300 removeContentProviderExternalUnchecked(name, null, userId); 28 12301 } 29 12302 } else { 30 12303 Slog.d(TAG, "Failed to get provider for authority '" + name + "'"); 31 12304 } 32 12305 return pfd; 33 12306 }
睡眠唤醒状态
1 12308 // Actually is sleeping or shutting down or whatever else in the future 2 12309 // is an inactive state. 3 12310 boolean isSleepingOrShuttingDownLocked() { 4 12311 return isSleepingLocked() || mShuttingDown; 5 12312 } 6 12313 7 12314 boolean isShuttingDownLocked() { 8 12315 return mShuttingDown; 9 12316 } 10 12317 11 12318 boolean isSleepingLocked() { 12 12319 return mSleeping; 13 12320 } 14 12321 15 12322 void onWakefulnessChanged(int wakefulness) { 16 12323 synchronized(this) { 17 12324 mWakefulness = wakefulness; 18 12325 updateSleepIfNeededLocked(); 19 12326 } 20 12327 }
结束运行的语音
1 12329 void finishRunningVoiceLocked() { 2 12330 if (mRunningVoice != null) { 3 12331 mRunningVoice = null; 4 12332 mVoiceWakeLock.release(); 5 12333 updateSleepIfNeededLocked(); 6 12334 } 7 12335 }
开始track focused activity time
1 12337 void startTimeTrackingFocusedActivityLocked() { 2 12338 final ActivityRecord resumedActivity = mStackSupervisor.getResumedActivityLocked(); 3 12339 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) { 4 12340 mCurAppTimeTracker.start(resumedActivity.packageName); 5 12341 } 6 12342 }
睡眠相关
1 12344 void updateSleepIfNeededLocked() { 2 12345 final boolean shouldSleep = shouldSleepLocked(); 3 12346 if (mSleeping && !shouldSleep) { 4 12347 mSleeping = false; 5 12348 startTimeTrackingFocusedActivityLocked(); 6 12349 mTopProcessState = ActivityManager.PROCESS_STATE_TOP; 7 12350 mStackSupervisor.comeOutOfSleepIfNeededLocked(); 8 12351 sendNotifyVrManagerOfSleepState(false); 9 12352 updateOomAdjLocked(); 10 12353 } else if (!mSleeping && shouldSleep) { 11 12354 mSleeping = true; 12 12355 if (mCurAppTimeTracker != null) { 13 12356 mCurAppTimeTracker.stop(); 14 12357 } 15 12358 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING; 16 12359 mStackSupervisor.goingToSleepLocked(); 17 12360 sendNotifyVrManagerOfSleepState(true); 18 12361 updateOomAdjLocked(); 19 12362 20 12363 // Initialize the wake times of all processes. 21 12364 checkExcessivePowerUsageLocked(false); 22 12365 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 23 12366 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 24 12367 mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_DELAY); 25 12368 } 26 12369 27 12370 // Also update state in a special way for running foreground services UI. 28 12371 switch (mWakefulness) { 29 12372 case PowerManagerInternal.WAKEFULNESS_ASLEEP: 30 12373 case PowerManagerInternal.WAKEFULNESS_DREAMING: 31 12374 case PowerManagerInternal.WAKEFULNESS_DOZING: 32 12375 mServices.updateScreenStateLocked(false); 33 12376 break; 34 12377 case PowerManagerInternal.WAKEFULNESS_AWAKE: 35 12378 default: 36 12379 mServices.updateScreenStateLocked(true); 37 12380 break; 38 12381 } 39 12382 } 40 12383 41 12384 private boolean shouldSleepLocked() { 42 12385 // Resume applications while running a voice interactor. 43 12386 if (mRunningVoice != null) { 44 12387 return false; 45 12388 } 46 12389 47 12390 // TODO: Transform the lock screen state into a sleep token instead. 48 12391 switch (mWakefulness) { 49 12392 case PowerManagerInternal.WAKEFULNESS_AWAKE: 50 12393 case PowerManagerInternal.WAKEFULNESS_DREAMING: 51 12394 case PowerManagerInternal.WAKEFULNESS_DOZING: 52 12395 // Pause applications whenever the lock screen is shown or any sleep 53 12396 // tokens have been acquired. 54 12397 return mKeyguardController.isKeyguardShowing() || !mSleepTokens.isEmpty(); 55 12398 case PowerManagerInternal.WAKEFULNESS_ASLEEP: 56 12399 default: 57 12400 // If we're asleep then pause applications unconditionally. 58 12401 return true; 59 12402 } 60 12403 }
通知 task持久化,task动画开始结束,清空网络
1 12405 /** Pokes the task persister. */ 2 12406 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) { 3 12407 mRecentTasks.notifyTaskPersisterLocked(task, flush); 4 12408 } 5 12409 6 12410 /** 7 12411 * Notifies all listeners when the pinned stack animation starts. 8 12412 */ 9 12413 @Override 10 12414 public void notifyPinnedStackAnimationStarted() { 11 12415 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted(); 12 12416 } 13 12417 14 12418 /** 15 12419 * Notifies all listeners when the pinned stack animation ends. 16 12420 */ 17 12421 @Override 18 12422 public void notifyPinnedStackAnimationEnded() { 19 12423 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded(); 20 12424 } 21 12425 22 12426 @Override 23 12427 public void notifyCleartextNetwork(int uid, byte[] firstPacket) { 24 12428 mHandler.obtainMessage(NOTIFY_CLEARTEXT_NETWORK_MSG, uid, 0, firstPacket).sendToTarget(); 25 12429 }
关机
1 12431 @Override 2 12432 public boolean shutdown(int timeout) { 3 12433 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN) 4 12434 != PackageManager.PERMISSION_GRANTED) { 5 12435 throw new SecurityException("Requires permission " 6 12436 + android.Manifest.permission.SHUTDOWN); 7 12437 } 8 12438 9 12439 boolean timedout = false; 10 12440 11 12441 synchronized(this) { 12 12442 mShuttingDown = true; 13 12443 updateEventDispatchingLocked(); 14 12444 timedout = mStackSupervisor.shutdownLocked(timeout); 15 12445 } 16 12446 17 12447 mAppOpsService.shutdown(); 18 12448 if (mUsageStatsService != null) { 19 12449 mUsageStatsService.prepareShutdown(); 20 12450 } 21 12451 mBatteryStatsService.shutdown(); 22 12452 synchronized (this) { 23 12453 mProcessStats.shutdownLocked(); 24 12454 notifyTaskPersisterLocked(null, true); 25 12455 } 26 12456 27 12457 return timedout; 28 12458 }
activity休眠
1 12460 public final void activitySlept(IBinder token) { 2 12461 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token); 3 12462 4 12463 final long origId = Binder.clearCallingIdentity(); 5 12464 6 12465 synchronized (this) { 7 12466 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 8 12467 if (r != null) { 9 12468 mStackSupervisor.activitySleptLocked(r); 10 12469 } 11 12470 } 12 12471 13 12472 Binder.restoreCallingIdentity(origId); 14 12473 }
开始运行voice
1 12475 void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) { 2 12476 Slog.d(TAG, "<<< startRunningVoiceLocked()"); 3 12477 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid)); 4 12478 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) { 5 12479 boolean wasRunningVoice = mRunningVoice != null; 6 12480 mRunningVoice = session; 7 12481 if (!wasRunningVoice) { 8 12482 mVoiceWakeLock.acquire(); 9 12483 updateSleepIfNeededLocked(); 10 12484 } 11 12485 } 12 12486 }
更新事件发送
1 12488 private void updateEventDispatchingLocked() { 2 12489 mWindowManager.setEventDispatching(mBooted && !mShuttingDown); 3 12490 } 4 12491
设置锁屏
1 12492 @Override 2 12493 public void setLockScreenShown(boolean showing) { 3 12494 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER) 4 12495 != PackageManager.PERMISSION_GRANTED) { 5 12496 throw new SecurityException("Requires permission " 6 12497 + android.Manifest.permission.DEVICE_POWER); 7 12498 } 8 12499 9 12500 synchronized(this) { 10 12501 long ident = Binder.clearCallingIdentity(); 11 12502 try { 12 12503 mKeyguardController.setKeyguardShown(showing); 13 12504 } finally { 14 12505 Binder.restoreCallingIdentity(ident); 15 12506 } 16 12507 } 17 12508 }
通知锁住了配置文件
1 12510 @Override 2 12511 public void notifyLockedProfile(@UserIdInt int userId) { 3 12512 try { 4 12513 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) { 5 12514 throw new SecurityException("Only privileged app can call notifyLockedProfile"); 6 12515 } 7 12516 } catch (RemoteException ex) { 8 12517 throw new SecurityException("Fail to check is caller a privileged app", ex); 9 12518 } 10 12519 11 12520 synchronized (this) { 12 12521 final long ident = Binder.clearCallingIdentity(); 13 12522 try { 14 12523 if (mUserController.shouldConfirmCredentials(userId)) { 15 12524 if (mKeyguardController.isKeyguardLocked()) { 16 12525 // Showing launcher to avoid user entering credential twice. 17 12526 final int currentUserId = mUserController.getCurrentUserIdLocked(); 18 12527 startHomeActivityLocked(currentUserId, "notifyLockedProfile"); 19 12528 } 20 12529 mStackSupervisor.lockAllProfileTasks(userId); 21 12530 } 22 12531 } finally { 23 12532 Binder.restoreCallingIdentity(ident); 24 12533 } 25 12534 } 26 12535 }
开始确认设备可信任
1 12537 @Override 2 12538 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) { 3 12539 enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent"); 4 12540 synchronized (this) { 5 12541 final long ident = Binder.clearCallingIdentity(); 6 12542 try { 7 12543 mActivityStarter.startConfirmCredentialIntent(intent, options); 8 12544 } finally { 9 12545 Binder.restoreCallingIdentity(ident); 10 12546 } 11 12547 } 12 12548 }
app切换相关
1 12550 @Override 2 12551 public void stopAppSwitches() { 3 12552 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES) 4 12553 != PackageManager.PERMISSION_GRANTED) { 5 12554 throw new SecurityException("viewquires permission " 6 12555 + android.Manifest.permission.STOP_APP_SWITCHES); 7 12556 } 8 12557 9 12558 synchronized(this) { 10 12559 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() 11 12560 + APP_SWITCH_DELAY_TIME; 12 12561 mDidAppSwitch = false; 13 12562 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG); 14 12563 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG); 15 12564 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME); 16 12565 } 17 12566 } 18 12567 19 12568 public void resumeAppSwitches() { 20 12569 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES) 21 12570 != PackageManager.PERMISSION_GRANTED) { 22 12571 throw new SecurityException("Requires permission " 23 12572 + android.Manifest.permission.STOP_APP_SWITCHES); 24 12573 } 25 12574 26 12575 synchronized(this) { 27 12576 // Note that we don't execute any pending app switches... we will 28 12577 // let those wait until either the timeout, or the next start 29 12578 // activity request. 30 12579 mAppSwitchesAllowedTime = 0; 31 12580 } 32 12581 } 33 12582 34 12583 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid, 35 12584 int callingPid, int callingUid, String name) { 36 12585 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) { 37 12586 return true; 38 12587 } 39 12588 40 12589 int perm = checkComponentPermission( 41 12590 android.Manifest.permission.STOP_APP_SWITCHES, sourcePid, 42 12591 sourceUid, -1, true); 43 12592 if (perm == PackageManager.PERMISSION_GRANTED) { 44 12593 return true; 45 12594 } 46 12595 47 12596 // If the actual IPC caller is different from the logical source, then 48 12597 // also see if they are allowed to control app switches. 49 12598 if (callingUid != -1 && callingUid != sourceUid) { 50 12599 perm = checkComponentPermission( 51 12600 android.Manifest.permission.STOP_APP_SWITCHES, callingPid, 52 12601 callingUid, -1, true); 53 12602 if (perm == PackageManager.PERMISSION_GRANTED) { 54 12603 return true; 55 12604 } 56 12605 } 57 12606 58 12607 Slog.w(TAG, name + " request from " + sourceUid + " stopped"); 59 12608 return false; 60 12609 }
设置debug app
1 12611 public void setDebugApp(String packageName, boolean waitForDebugger, 2 12612 boolean persistent) { 3 12613 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 4 12614 "setDebugApp()"); 5 12615 6 12616 long ident = Binder.clearCallingIdentity(); 7 12617 try { 8 12618 // Note that this is not really thread safe if there are multiple 9 12619 // callers into it at the same time, but that's not a situation we 10 12620 // care about. 11 12621 if (persistent) { 12 12622 final ContentResolver resolver = mContext.getContentResolver(); 13 12623 Settings.Global.putString( 14 12624 resolver, Settings.Global.DEBUG_APP, 15 12625 packageName); 16 12626 Settings.Global.putInt( 17 12627 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 18 12628 waitForDebugger ? 1 : 0); 19 12629 } 20 12630 21 12631 synchronized (this) { 22 12632 if (!persistent) { 23 12633 mOrigDebugApp = mDebugApp; 24 12634 mOrigWaitForDebugger = mWaitForDebugger; 25 12635 } 26 12636 mDebugApp = packageName; 27 12637 mWaitForDebugger = waitForDebugger; 28 12638 mDebugTransient = !persistent; 29 12639 if (packageName != null) { 30 12640 forceStopPackageLocked(packageName, -1, false, false, true, true, 31 12641 false, UserHandle.USER_ALL, "set debug app"); 32 12642 } 33 12643 } 34 12644 } finally { 35 12645 Binder.restoreCallingIdentity(ident); 36 12646 } 37 12647 }
debug相关
1 12649 void setTrackAllocationApp(ApplicationInfo app, String processName) { 2 12650 synchronized (this) { 3 12651 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 4 12652 if (!isDebuggable) { 5 12653 if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 6 12654 throw new SecurityException("Process not debuggable: " + app.packageName); 7 12655 } 8 12656 } 9 12657 10 12658 mTrackAllocationApp = processName; 11 12659 } 12 12660 } 13 12661 14 12662 void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo) { 15 12663 synchronized (this) { 16 12664 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 17 12665 if (!isDebuggable) { 18 12666 if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 19 12667 throw new SecurityException("Process not debuggable: " + app.packageName); 20 12668 } 21 12669 } 22 12670 mProfileApp = processName; 23 12671 mProfileFile = profilerInfo.profileFile; 24 12672 if (mProfileFd != null) { 25 12673 try { 26 12674 mProfileFd.close(); 27 12675 } catch (IOException e) { 28 12676 } 29 12677 mProfileFd = null; 30 12678 } 31 12679 mProfileFd = profilerInfo.profileFd; 32 12680 mSamplingInterval = profilerInfo.samplingInterval; 33 12681 mAutoStopProfiler = profilerInfo.autoStopProfiler; 34 12682 mStreamingOutput = profilerInfo.streamingOutput; 35 12683 mProfileType = 0; 36 12684 } 37 12685 } 38 12686 39 12687 void setNativeDebuggingAppLocked(ApplicationInfo app, String processName) { 40 12688 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 41 12689 if (!isDebuggable) { 42 12690 if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 43 12691 throw new SecurityException("Process not debuggable: " + app.packageName); 44 12692 } 45 12693 } 46 12694 mNativeDebuggingApp = processName; 47 12695 } 48 12696 49 12697 @Override 50 12698 public void setAlwaysFinish(boolean enabled) { 51 12699 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH, 52 12700 "setAlwaysFinish()"); 53 12701 54 12702 long ident = Binder.clearCallingIdentity(); 55 12703 try { 56 12704 Settings.Global.putInt( 57 12705 mContext.getContentResolver(), 58 12706 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0); 59 12707 60 12708 synchronized (this) { 61 12709 mAlwaysFinishActivities = enabled; 62 12710 } 63 12711 } finally { 64 12712 Binder.restoreCallingIdentity(ident); 65 12713 } 66 12714 }
设置activity控制器
1 12716 @Override 2 12717 public void setActivityController(IActivityController controller, boolean imAMonkey) { 3 12718 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 4 12719 "setActivityController()"); 5 12720 synchronized (this) { 6 12721 mController = controller; 7 12722 mControllerIsAMonkey = imAMonkey; 8 12723 Watchdog.getInstance().setActivityController(controller); 9 12724 } 10 12725 }
monkey相关
1 12727 @Override 2 12728 public void setUserIsMonkey(boolean userIsMonkey) { 3 12729 synchronized (this) { 4 12730 synchronized (mPidsSelfLocked) { 5 12731 final int callingPid = Binder.getCallingPid(); 6 12732 ProcessRecord proc = mPidsSelfLocked.get(callingPid); 7 12733 if (proc == null) { 8 12734 throw new SecurityException("Unknown process: " + callingPid); 9 12735 } 10 12736 if (proc.instr == null || proc.instr.mUiAutomationConnection == null) { 11 12737 throw new SecurityException("Only an instrumentation process " 12 12738 + "with a UiAutomation can call setUserIsMonkey"); 13 12739 } 14 12740 } 15 12741 mUserIsMonkey = userIsMonkey; 16 12742 } 17 12743 } 18 12744 19 12745 @Override 20 12746 public boolean isUserAMonkey() { 21 12747 synchronized (this) { 22 12748 // If there is a controller also implies the user is a monkey. 23 12749 return (mUserIsMonkey || (mController != null && mControllerIsAMonkey)); 24 12750 } 25 12751 } 26 12752
bugreport相关
1 12753 /** 2 12754 * @deprecated This method is only used by a few internal components and it will soon be 3 12755 * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps). 4 12756 * No new code should be calling it. 5 12757 */ 6 12758 @Deprecated 7 12759 @Override 8 12760 public void requestBugReport(int bugreportType) { 9 12761 String extraOptions = null; 10 12762 switch (bugreportType) { 11 12763 case ActivityManager.BUGREPORT_OPTION_FULL: 12 12764 // Default options. 13 12765 break; 14 12766 case ActivityManager.BUGREPORT_OPTION_INTERACTIVE: 15 12767 extraOptions = "bugreportplus"; 16 12768 break; 17 12769 case ActivityManager.BUGREPORT_OPTION_REMOTE: 18 12770 extraOptions = "bugreportremote"; 19 12771 break; 20 12772 case ActivityManager.BUGREPORT_OPTION_WEAR: 21 12773 extraOptions = "bugreportwear"; 22 12774 break; 23 12775 case ActivityManager.BUGREPORT_OPTION_TELEPHONY: 24 12776 extraOptions = "bugreporttelephony"; 25 12777 break; 26 12778 default: 27 12779 throw new IllegalArgumentException("Provided bugreport type is not correct, value: " 28 12780 + bugreportType); 29 12781 } 30 12782 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport"); 31 12783 if (extraOptions != null) { 32 12784 SystemProperties.set("dumpstate.options", extraOptions); 33 12785 } 34 12786 SystemProperties.set("ctl.start", "bugreport"); 35 12787 } 36 12788 37 12789 /** 38 12790 * @deprecated This method is only used by a few internal components and it will soon be 39 12791 * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps). 40 12792 * No new code should be calling it. 41 12793 */ 42 12794 @Deprecated 43 12795 @Override 44 12796 public void requestTelephonyBugReport(String shareTitle, String shareDescription) { 45 12797 46 12798 if (!TextUtils.isEmpty(shareTitle)) { 47 12799 if (shareTitle.length() > MAX_BUGREPORT_TITLE_SIZE) { 48 12800 String errorStr = "shareTitle should be less than " + 49 12801 MAX_BUGREPORT_TITLE_SIZE + " characters"; 50 12802 throw new IllegalArgumentException(errorStr); 51 12803 } else { 52 12804 if (!TextUtils.isEmpty(shareDescription)) { 53 12805 int length; 54 12806 try { 55 12807 length = shareDescription.getBytes("UTF-8").length; 56 12808 } catch (UnsupportedEncodingException e) { 57 12809 String errorStr = "shareDescription: UnsupportedEncodingException"; 58 12810 throw new IllegalArgumentException(errorStr); 59 12811 } 60 12812 if (length > SystemProperties.PROP_VALUE_MAX) { 61 12813 String errorStr = "shareTitle should be less than " + 62 12814 SystemProperties.PROP_VALUE_MAX + " bytes"; 63 12815 throw new IllegalArgumentException(errorStr); 64 12816 } else { 65 12817 SystemProperties.set("dumpstate.options.description", shareDescription); 66 12818 } 67 12819 } 68 12820 SystemProperties.set("dumpstate.options.title", shareTitle); 69 12821 } 70 12822 } 71 12823 72 12824 Slog.d(TAG, "Bugreport notification title " + shareTitle 73 12825 + " description " + shareDescription); 74 12826 requestBugReport(ActivityManager.BUGREPORT_OPTION_TELEPHONY); 75 12827 }
输入分发相关
1 12829 public static long getInputDispatchingTimeoutLocked(ActivityRecord r) { 2 12830 return r != null ? getInputDispatchingTimeoutLocked(r.app) : KEY_DISPATCHING_TIMEOUT; 3 12831 } 4 12832 5 12833 public static long getInputDispatchingTimeoutLocked(ProcessRecord r) { 6 12834 if (r != null && (r.instr != null || r.usingWrapper)) { 7 12835 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT; 8 12836 } 9 12837 return KEY_DISPATCHING_TIMEOUT; 10 12838 } 11 12839 12 12840 @Override 13 12841 public long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) { 14 12842 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS) 15 12843 != PackageManager.PERMISSION_GRANTED) { 16 12844 throw new SecurityException("Requires permission " 17 12845 + android.Manifest.permission.FILTER_EVENTS); 18 12846 } 19 12847 ProcessRecord proc; 20 12848 long timeout; 21 12849 synchronized (this) { 22 12850 synchronized (mPidsSelfLocked) { 23 12851 proc = mPidsSelfLocked.get(pid); 24 12852 } 25 12853 timeout = getInputDispatchingTimeoutLocked(proc); 26 12854 } 27 12855 28 12856 if (!inputDispatchingTimedOut(proc, null, null, aboveSystem, reason)) { 29 12857 return -1; 30 12858 } 31 12859 32 12860 return timeout; 33 12861 } 34 12862 35 12863 /** 36 12864 * Handle input dispatching timeouts. 37 12865 * Returns whether input dispatching should be aborted or not. 38 12866 */ 39 12867 public boolean inputDispatchingTimedOut(final ProcessRecord proc, 40 12868 final ActivityRecord activity, final ActivityRecord parent, 41 12869 final boolean aboveSystem, String reason) { 42 12870 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS) 43 12871 != PackageManager.PERMISSION_GRANTED) { 44 12872 throw new SecurityException("Requires permission " 45 12873 + android.Manifest.permission.FILTER_EVENTS); 46 12874 } 47 12875 48 12876 final String annotation; 49 12877 if (reason == null) { 50 12878 annotation = "Input dispatching timed out"; 51 12879 } else { 52 12880 annotation = "Input dispatching timed out (" + reason + ")"; 53 12881 } 54 12882 55 12883 if (proc != null) { 56 12884 synchronized (this) { 57 12885 if (proc.debugging) { 58 12886 return false; 59 12887 } 60 12888 61 12889 if (mDidDexOpt) { 62 12890 // Give more time since we were dexopting. 63 12891 mDidDexOpt = false; 64 12892 return false; 65 12893 } 66 12894 67 12895 if (proc.instr != null) { 68 12896 Bundle info = new Bundle(); 69 12897 info.putString("shortMsg", "keyDispatchingTimedOut"); 70 12898 info.putString("longMsg", annotation); 71 12899 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info); 72 12900 return true; 73 12901 } 74 12902 } 75 12903 mHandler.post(new Runnable() { 76 12904 @Override 77 12905 public void run() { 78 12906 mAppErrors.appNotResponding(proc, activity, parent, aboveSystem, annotation); 79 12907 } 80 12908 }); 81 12909 } 82 12910 83 12911 return true; 84 12912 }
辅助相关
1 12914 @Override 2 12915 public Bundle getAssistContextExtras(int requestType) { 3 12916 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null, 4 12917 null, null, true /* focused */, true /* newSessionId */, 5 12918 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0); 6 12919 if (pae == null) { 7 12920 return null; 8 12921 } 9 12922 synchronized (pae) { 10 12923 while (!pae.haveResult) { 11 12924 try { 12 12925 pae.wait(); 13 12926 } catch (InterruptedException e) { 14 12927 } 15 12928 } 16 12929 } 17 12930 synchronized (this) { 18 12931 buildAssistBundleLocked(pae, pae.result); 19 12932 mPendingAssistExtras.remove(pae); 20 12933 mUiHandler.removeCallbacks(pae); 21 12934 } 22 12935 return pae.extras; 23 12936 } 24 12937 25 12938 @Override 26 12939 public boolean isAssistDataAllowedOnCurrentActivity() { 27 12940 int userId; 28 12941 synchronized (this) { 29 12942 final ActivityStack focusedStack = getFocusedStack(); 30 12943 if (focusedStack == null || focusedStack.isAssistantStack()) { 31 12944 return false; 32 12945 } 33 12946 34 12947 final ActivityRecord activity = focusedStack.topActivity(); 35 12948 if (activity == null) { 36 12949 return false; 37 12950 } 38 12951 userId = activity.userId; 39 12952 } 40 12953 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService( 41 12954 Context.DEVICE_POLICY_SERVICE); 42 12955 return (dpm == null) || (!dpm.getScreenCaptureDisabled(null, userId)); 43 12956 } 44 12957 45 12958 @Override 46 12959 public boolean showAssistFromActivity(IBinder token, Bundle args) { 47 12960 long ident = Binder.clearCallingIdentity(); 48 12961 try { 49 12962 synchronized (this) { 50 12963 ActivityRecord caller = ActivityRecord.forTokenLocked(token); 51 12964 ActivityRecord top = getFocusedStack().topActivity(); 52 12965 if (top != caller) { 53 12966 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller 54 12967 + " is not current top " + top); 55 12968 return false; 56 12969 } 57 12970 if (!top.nowVisible) { 58 12971 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller 59 12972 + " is not visible"); 60 12973 return false; 61 12974 } 62 12975 } 63 12976 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null, 64 12977 token); 65 12978 } finally { 66 12979 Binder.restoreCallingIdentity(ident); 67 12980 } 68 12981 } 69 12982 70 12983 @Override 71 12984 public boolean requestAssistContextExtras(int requestType, IResultReceiver receiver, 72 12985 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) { 73 12986 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras, 74 12987 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null, 75 12988 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null; 76 12989 } 77 12990 78 12991 @Override 79 12992 public boolean requestAutofillData(IResultReceiver receiver, Bundle receiverExtras, 80 12993 IBinder activityToken, int flags) { 81 12994 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null, 82 12995 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(), 83 12996 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null; 84 12997 } 85 12998 86 12999 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint, 87 13000 IResultReceiver receiver, Bundle receiverExtras, IBinder activityToken, 88 13001 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout, 89 13002 int flags) { 90 13003 enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO, 91 13004 "enqueueAssistContext()"); 92 13005 93 13006 synchronized (this) { 94 13007 ActivityRecord activity = getFocusedStack().topActivity(); 95 13008 if (activity == null) { 96 13009 Slog.w(TAG, "getAssistContextExtras failed: no top activity"); 97 13010 return null; 98 13011 } 99 13012 if (activity.app == null || activity.app.thread == null) { 100 13013 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity); 101 13014 return null; 102 13015 } 103 13016 if (focused) { 104 13017 if (activityToken != null) { 105 13018 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken); 106 13019 if (activity != caller) { 107 13020 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller 108 13021 + " is not current top " + activity); 109 13022 return null; 110 13023 } 111 13024 } 112 13025 } else { 113 13026 activity = ActivityRecord.forTokenLocked(activityToken); 114 13027 if (activity == null) { 115 13028 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken 116 13029 + " couldn't be found"); 117 13030 return null; 118 13031 } 119 13032 } 120 13033 121 13034 PendingAssistExtras pae; 122 13035 Bundle extras = new Bundle(); 123 13036 if (args != null) { 124 13037 extras.putAll(args); 125 13038 } 126 13039 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName); 127 13040 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.uid); 128 13041 129 13042 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras, 130 13043 userHandle); 131 13044 pae.isHome = activity.isHomeActivity(); 132 13045 133 13046 // Increment the sessionId if necessary 134 13047 if (newSessionId) { 135 13048 mViSessionId++; 136 13049 } 137 13050 try { 138 13051 activity.app.thread.requestAssistContextExtras(activity.appToken, pae, requestType, 139 13052 mViSessionId, flags); 140 13053 mPendingAssistExtras.add(pae); 141 13054 mUiHandler.postDelayed(pae, timeout); 142 13055 } catch (RemoteException e) { 143 13056 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity); 144 13057 return null; 145 13058 } 146 13059 return pae; 147 13060 } 148 13061 } 149 13062 150 13063 void pendingAssistExtrasTimedOut(PendingAssistExtras pae) { 151 13064 IResultReceiver receiver; 152 13065 synchronized (this) { 153 13066 mPendingAssistExtras.remove(pae); 154 13067 receiver = pae.receiver; 155 13068 } 156 13069 if (receiver != null) { 157 13070 // Caller wants result sent back to them. 158 13071 Bundle sendBundle = new Bundle(); 159 13072 // At least return the receiver extras 160 13073 sendBundle.putBundle(VoiceInteractionSession.KEY_RECEIVER_EXTRAS, 161 13074 pae.receiverExtras); 162 13075 try { 163 13076 pae.receiver.send(0, sendBundle); 164 13077 } catch (RemoteException e) { 165 13078 } 166 13079 } 167 13080 } 168 13081 169 13082 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) { 170 13083 if (result != null) { 171 13084 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result); 172 13085 } 173 13086 if (pae.hint != null) { 174 13087 pae.extras.putBoolean(pae.hint, true); 175 13088 } 176 13089 } 177 13090 178 13091 /** Called from an app when assist data is ready. */ 179 13092 @Override 180 13093 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure, 181 13094 AssistContent content, Uri referrer) { 182 13095 PendingAssistExtras pae = (PendingAssistExtras)token; 183 13096 synchronized (pae) { 184 13097 pae.result = extras; 185 13098 pae.structure = structure; 186 13099 pae.content = content; 187 13100 if (referrer != null) { 188 13101 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer); 189 13102 } 190 13103 if (structure != null) { 191 13104 structure.setHomeActivity(pae.isHome); 192 13105 } 193 13106 pae.haveResult = true; 194 13107 pae.notifyAll(); 195 13108 if (pae.intent == null && pae.receiver == null) { 196 13109 // Caller is just waiting for the result. 197 13110 return; 198 13111 } 199 13112 } 200 13113 201 13114 // We are now ready to launch the assist activity. 202 13115 IResultReceiver sendReceiver = null; 203 13116 Bundle sendBundle = null; 204 13117 synchronized (this) { 205 13118 buildAssistBundleLocked(pae, extras); 206 13119 boolean exists = mPendingAssistExtras.remove(pae); 207 13120 mUiHandler.removeCallbacks(pae); 208 13121 if (!exists) { 209 13122 // Timed out. 210 13123 return; 211 13124 } 212 13125 if ((sendReceiver=pae.receiver) != null) { 213 13126 // Caller wants result sent back to them. 214 13127 sendBundle = new Bundle(); 215 13128 sendBundle.putBundle(VoiceInteractionSession.KEY_DATA, pae.extras); 216 13129 sendBundle.putParcelable(VoiceInteractionSession.KEY_STRUCTURE, pae.structure); 217 13130 sendBundle.putParcelable(VoiceInteractionSession.KEY_CONTENT, pae.content); 218 13131 sendBundle.putBundle(VoiceInteractionSession.KEY_RECEIVER_EXTRAS, 219 13132 pae.receiverExtras); 220 13133 } 221 13134 } 222 13135 if (sendReceiver != null) { 223 13136 try { 224 13137 sendReceiver.send(0, sendBundle); 225 13138 } catch (RemoteException e) { 226 13139 } 227 13140 return; 228 13141 } 229 13142 230 13143 long ident = Binder.clearCallingIdentity(); 231 13144 try { 232 13145 pae.intent.replaceExtras(pae.extras); 233 13146 pae.intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK 234 13147 | Intent.FLAG_ACTIVITY_SINGLE_TOP 235 13148 | Intent.FLAG_ACTIVITY_CLEAR_TOP); 236 13149 closeSystemDialogs("assist"); 237 13150 try { 238 13151 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle)); 239 13152 } catch (ActivityNotFoundException e) { 240 13153 Slog.w(TAG, "No activity to handle assist action.", e); 241 13154 } 242 13155 } finally { 243 13156 Binder.restoreCallingIdentity(ident); 244 13157 } 245 13158 } 246 13159 247 13160 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle, 248 13161 Bundle args) { 249 13162 return enqueueAssistContext(requestType, intent, hint, null, null, null, 250 13163 true /* focused */, true /* newSessionId */, userHandle, args, 251 13164 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null; 252 13165 }
进程、uid观察者注册与取消
1 13167 public void registerProcessObserver(IProcessObserver observer) { 2 13168 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 3 13169 "registerProcessObserver()"); 4 13170 synchronized (this) { 5 13171 mProcessObservers.register(observer); 6 13172 } 7 13173 } 8 13174 9 13175 @Override 10 13176 public void unregisterProcessObserver(IProcessObserver observer) { 11 13177 synchronized (this) { 12 13178 mProcessObservers.unregister(observer); 13 13179 } 14 13180 } 15 13181 16 13182 @Override 17 13183 public int getUidProcessState(int uid, String callingPackage) { 18 13184 if (!hasUsageStatsPermission(callingPackage)) { 19 13185 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 20 13186 "getUidProcessState"); 21 13187 } 22 13188 23 13189 synchronized (this) { 24 13190 UidRecord uidRec = mActiveUids.get(uid); 25 13191 return uidRec != null ? uidRec.curProcState : ActivityManager.PROCESS_STATE_NONEXISTENT; 26 13192 } 27 13193 } 28 13194 29 13195 @Override 30 13196 public void registerUidObserver(IUidObserver observer, int which, int cutpoint, 31 13197 String callingPackage) { 32 13198 if (!hasUsageStatsPermission(callingPackage)) { 33 13199 enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS, 34 13200 "registerUidObserver"); 35 13201 } 36 13202 synchronized (this) { 37 13203 mUidObservers.register(observer, new UidObserverRegistration(Binder.getCallingUid(), 38 13204 callingPackage, which, cutpoint)); 39 13205 } 40 13206 } 41 13207 42 13208 @Override 43 13209 public void unregisterUidObserver(IUidObserver observer) { 44 13210 synchronized (this) { 45 13211 mUidObservers.unregister(observer); 46 13212 } 47 13213 }
可视性相关
1 13215 @Override 2 13216 public boolean convertFromTranslucent(IBinder token) { 3 13217 final long origId = Binder.clearCallingIdentity(); 4 13218 try { 5 13219 synchronized (this) { 6 13220 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 7 13221 if (r == null) { 8 13222 return false; 9 13223 } 10 13224 final boolean translucentChanged = r.changeWindowTranslucency(true); 11 13225 if (translucentChanged) { 12 13226 r.getStack().releaseBackgroundResources(r); 13 13227 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS); 14 13228 } 15 13229 mWindowManager.setAppFullscreen(token, true); 16 13230 return translucentChanged; 17 13231 } 18 13232 } finally { 19 13233 Binder.restoreCallingIdentity(origId); 20 13234 } 21 13235 } 22 13236 23 13237 @Override 24 13238 public boolean convertToTranslucent(IBinder token, Bundle options) { 25 13239 final long origId = Binder.clearCallingIdentity(); 26 13240 try { 27 13241 synchronized (this) { 28 13242 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 29 13243 if (r == null) { 30 13244 return false; 31 13245 } 32 13246 final TaskRecord task = r.getTask(); 33 13247 int index = task.mActivities.lastIndexOf(r); 34 13248 if (index > 0) { 35 13249 ActivityRecord under = task.mActivities.get(index - 1); 36 13250 under.returningOptions = ActivityOptions.fromBundle(options); 37 13251 } 38 13252 final boolean translucentChanged = r.changeWindowTranslucency(false); 39 13253 if (translucentChanged) { 40 13254 r.getStack().convertActivityToTranslucent(r); 41 13255 } 42 13256 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS); 43 13257 mWindowManager.setAppFullscreen(token, false); 44 13258 return translucentChanged; 45 13259 } 46 13260 } finally { 47 13261 Binder.restoreCallingIdentity(origId); 48 13262 } 49 13263 } 50 13264 51 13265 @Override 52 13266 public boolean requestVisibleBehind(IBinder token, boolean visible) { 53 13267 final long origId = Binder.clearCallingIdentity(); 54 13268 try { 55 13269 synchronized (this) { 56 13270 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 57 13271 if (r != null) { 58 13272 return mStackSupervisor.requestVisibleBehindLocked(r, visible); 59 13273 } 60 13274 } 61 13275 return false; 62 13276 } finally { 63 13277 Binder.restoreCallingIdentity(origId); 64 13278 } 65 13279 } 66 13280 67 13281 @Override 68 13282 public boolean isBackgroundVisibleBehind(IBinder token) { 69 13283 final long origId = Binder.clearCallingIdentity(); 70 13284 try { 71 13285 synchronized (this) { 72 13286 final ActivityStack stack = ActivityRecord.getStackLocked(token); 73 13287 final boolean visible = stack == null ? false : stack.hasVisibleBehindActivity(); 74 13288 if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND, 75 13289 "isBackgroundVisibleBehind: stack=" + stack + " visible=" + visible); 76 13290 return visible; 77 13291 } 78 13292 } finally { 79 13293 Binder.restoreCallingIdentity(origId); 80 13294 } 81 13295 }
获取activity options
1 13297 @Override 2 13298 public Bundle getActivityOptions(IBinder token) { 3 13299 final long origId = Binder.clearCallingIdentity(); 4 13300 try { 5 13301 synchronized (this) { 6 13302 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 7 13303 if (r != null) { 8 13304 final ActivityOptions activityOptions = r.pendingOptions; 9 13305 r.pendingOptions = null; 10 13306 return activityOptions == null ? null : activityOptions.toBundle(); 11 13307 } 12 13308 return null; 13 13309 } 14 13310 } finally { 15 13311 Binder.restoreCallingIdentity(origId); 16 13312 } 17 13313 }
vr相关
1 13315 @Override 2 13316 public void setImmersive(IBinder token, boolean immersive) { 3 13317 synchronized(this) { 4 13318 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 5 13319 if (r == null) { 6 13320 throw new IllegalArgumentException(); 7 13321 } 8 13322 r.immersive = immersive; 9 13323 10 13324 // update associated state if we're frontmost 11 13325 if (r == mStackSupervisor.getResumedActivityLocked()) { 12 13326 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r); 13 13327 applyUpdateLockStateLocked(r); 14 13328 } 15 13329 } 16 13330 } 17 13331 18 13332 @Override 19 13333 public boolean isImmersive(IBinder token) { 20 13334 synchronized (this) { 21 13335 ActivityRecord r = ActivityRecord.isInStackLocked(token); 22 13336 if (r == null) { 23 13337 throw new IllegalArgumentException(); 24 13338 } 25 13339 return r.immersive; 26 13340 } 27 13341 } 28 13342 29 13343 @Override 30 13344 public void setVrThread(int tid) { 31 13345 enforceSystemHasVrFeature(); 32 13346 synchronized (this) { 33 13347 synchronized (mPidsSelfLocked) { 34 13348 final int pid = Binder.getCallingPid(); 35 13349 final ProcessRecord proc = mPidsSelfLocked.get(pid); 36 13350 mVrController.setVrThreadLocked(tid, pid, proc); 37 13351 } 38 13352 } 39 13353 } 40 13354 41 13355 @Override 42 13356 public void setPersistentVrThread(int tid) { 43 13357 if (checkCallingPermission(permission.RESTRICTED_VR_ACCESS) != PERMISSION_GRANTED) { 44 13358 final String msg = "Permission Denial: setPersistentVrThread() from pid=" 45 13359 + Binder.getCallingPid() 46 13360 + ", uid=" + Binder.getCallingUid() 47 13361 + " requires " + permission.RESTRICTED_VR_ACCESS; 48 13362 Slog.w(TAG, msg); 49 13363 throw new SecurityException(msg); 50 13364 } 51 13365 enforceSystemHasVrFeature(); 52 13366 synchronized (this) { 53 13367 synchronized (mPidsSelfLocked) { 54 13368 final int pid = Binder.getCallingPid(); 55 13369 final ProcessRecord proc = mPidsSelfLocked.get(pid); 56 13370 mVrController.setPersistentVrThreadLocked(tid, pid, proc); 57 13371 } 58 13372 } 59 13373 }
vr调度与模式
1 13375 /** 2 13376 * Schedule the given thread a normal scheduling priority. 3 13377 * 4 13378 * @param newTid the tid of the thread to adjust the scheduling of. 5 13379 * @param suppressLogs {@code true} if any error logging should be disabled. 6 13380 * 7 13381 * @return {@code true} if this succeeded. 8 13382 */ 9 13383 static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) { 10 13384 try { 11 13385 Process.setThreadScheduler(tid, Process.SCHED_OTHER, 0); 12 13386 return true; 13 13387 } catch (IllegalArgumentException e) { 14 13388 if (!suppressLogs) { 15 13389 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e); 16 13390 } 17 13391 } 18 13392 return false; 19 13393 } 20 13394 21 13395 /** 22 13396 * Schedule the given thread an FIFO scheduling priority. 23 13397 * 24 13398 * @param newTid the tid of the thread to adjust the scheduling of. 25 13399 * @param suppressLogs {@code true} if any error logging should be disabled. 26 13400 * 27 13401 * @return {@code true} if this succeeded. 28 13402 */ 29 13403 static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) { 30 13404 try { 31 13405 Process.setThreadScheduler(tid, Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1); 32 13406 return true; 33 13407 } catch (IllegalArgumentException e) { 34 13408 if (!suppressLogs) { 35 13409 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e); 36 13410 } 37 13411 } 38 13412 return false; 39 13413 } 40 13414 41 13415 /** 42 13416 * Check that we have the features required for VR-related API calls, and throw an exception if 43 13417 * not. 44 13418 */ 45 13419 private void enforceSystemHasVrFeature() { 46 13420 if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_VR_MODE)) { 47 13421 throw new UnsupportedOperationException("VR mode not supported on this device!"); 48 13422 } 49 13423 } 50 13424 51 13425 @Override 52 13426 public void setRenderThread(int tid) { 53 13427 synchronized (this) { 54 13428 ProcessRecord proc; 55 13429 int pid = Binder.getCallingPid(); 56 13430 if (pid == Process.myPid()) { 57 13431 demoteSystemServerRenderThread(tid); 58 13432 return; 59 13433 } 60 13434 synchronized (mPidsSelfLocked) { 61 13435 proc = mPidsSelfLocked.get(pid); 62 13436 if (proc != null && proc.renderThreadTid == 0 && tid > 0) { 63 13437 // ensure the tid belongs to the process 64 13438 if (!isThreadInProcess(pid, tid)) { 65 13439 throw new IllegalArgumentException( 66 13440 "Render thread does not belong to process"); 67 13441 } 68 13442 proc.renderThreadTid = tid; 69 13443 if (DEBUG_OOM_ADJ) { 70 13444 Slog.d("UI_FIFO", "Set RenderThread tid " + tid + " for pid " + pid); 71 13445 } 72 13446 // promote to FIFO now 73 13447 if (proc.curSchedGroup == ProcessList.SCHED_GROUP_TOP_APP) { 74 13448 if (DEBUG_OOM_ADJ) Slog.d("UI_FIFO", "Promoting " + tid + "out of band"); 75 13449 if (mUseFifoUiScheduling) { 76 13450 setThreadScheduler(proc.renderThreadTid, 77 13451 SCHED_FIFO | SCHED_RESET_ON_FORK, 1); 78 13452 } else { 79 13453 setThreadPriority(proc.renderThreadTid, TOP_APP_PRIORITY_BOOST); 80 13454 } 81 13455 } 82 13456 } else { 83 13457 if (DEBUG_OOM_ADJ) { 84 13458 Slog.d("UI_FIFO", "Didn't set thread from setRenderThread? " + 85 13459 "PID: " + pid + ", TID: " + tid + " FIFO: " + 86 13460 mUseFifoUiScheduling); 87 13461 } 88 13462 } 89 13463 } 90 13464 } 91 13465 } 92 13466 93 13467 /** 94 13468 * We only use RenderThread in system_server to store task snapshots to the disk, which should 95 13469 * happen in the background. Thus, demote render thread from system_server to a lower priority. 96 13470 * 97 13471 * @param tid the tid of the RenderThread 98 13472 */ 99 13473 private void demoteSystemServerRenderThread(int tid) { 100 13474 setThreadPriority(tid, Process.THREAD_PRIORITY_BACKGROUND); 101 13475 } 102 13476 103 13477 @Override 104 13478 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) { 105 13479 if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_VR_MODE)) { 106 13480 throw new UnsupportedOperationException("VR mode not supported on this device!"); 107 13481 } 108 13482 109 13483 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class); 110 13484 111 13485 ActivityRecord r; 112 13486 synchronized (this) { 113 13487 r = ActivityRecord.isInStackLocked(token); 114 13488 } 115 13489 116 13490 if (r == null) { 117 13491 throw new IllegalArgumentException(); 118 13492 } 119 13493 120 13494 int err; 121 13495 if ((err = vrService.hasVrPackage(packageName, r.userId)) != 122 13496 VrManagerInternal.NO_ERROR) { 123 13497 return err; 124 13498 } 125 13499 126 13500 synchronized(this) { 127 13501 r.requestedVrComponent = (enabled) ? packageName : null; 128 13502 129 13503 // Update associated state if this activity is currently focused 130 13504 if (r == mStackSupervisor.getResumedActivityLocked()) { 131 13505 applyUpdateVrModeLocked(r); 132 13506 } 133 13507 return 0; 134 13508 } 135 13509 } 136 13510 137 13511 @Override 138 13512 public boolean isVrModePackageEnabled(ComponentName packageName) { 139 13513 if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_VR_MODE)) { 140 13514 throw new UnsupportedOperationException("VR mode not supported on this device!"); 141 13515 } 142 13516 143 13517 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class); 144 13518 145 13519 return vrService.hasVrPackage(packageName, UserHandle.getCallingUserId()) == 146 13520 VrManagerInternal.NO_ERROR; 147 13521 } 148 13522 149 13523 public boolean isTopActivityImmersive() { 150 13524 enforceNotIsolatedCaller("startActivity"); 151 13525 synchronized (this) { 152 13526 ActivityRecord r = getFocusedStack().topRunningActivityLocked(); 153 13527 return (r != null) ? r.immersive : false; 154 13528 } 155 13529 } 156 13530 157 13531 /** 158 13532 * @return whether the system should disable UI modes incompatible with VR mode. 159 13533 */ 160 13534 boolean shouldDisableNonVrUiLocked() { 161 13535 return mVrController.shouldDisableNonVrUiLocked(); 162 13536 }
是否拥有top ui
1 13549 @Override 2 13550 public void setHasTopUi(boolean hasTopUi) throws RemoteException { 3 13551 if (checkCallingPermission(permission.INTERNAL_SYSTEM_WINDOW) != PERMISSION_GRANTED) { 4 13552 String msg = "Permission Denial: setHasTopUi() from pid=" 5 13553 + Binder.getCallingPid() 6 13554 + ", uid=" + Binder.getCallingUid() 7 13555 + " requires " + permission.INTERNAL_SYSTEM_WINDOW; 8 13556 Slog.w(TAG, msg); 9 13557 throw new SecurityException(msg); 10 13558 } 11 13559 final int pid = Binder.getCallingPid(); 12 13560 final long origId = Binder.clearCallingIdentity(); 13 13561 try { 14 13562 synchronized (this) { 15 13563 boolean changed = false; 16 13564 ProcessRecord pr; 17 13565 synchronized (mPidsSelfLocked) { 18 13566 pr = mPidsSelfLocked.get(pid); 19 13567 if (pr == null) { 20 13568 Slog.w(TAG, "setHasTopUi called on unknown pid: " + pid); 21 13569 return; 22 13570 } 23 13571 if (pr.hasTopUi != hasTopUi) { 24 13572 if (DEBUG_OOM_ADJ) { 25 13573 Slog.d(TAG, "Setting hasTopUi=" + hasTopUi + " for pid=" + pid); 26 13574 } 27 13575 pr.hasTopUi = hasTopUi; 28 13576 changed = true; 29 13577 } 30 13578 } 31 13579 if (changed) { 32 13580 updateOomAdjLocked(pr, true); 33 13581 } 34 13582 } 35 13583 } finally { 36 13584 Binder.restoreCallingIdentity(origId); 37 13585 } 38 13586 }
safe mode相关
1 13588 public final void enterSafeMode() { 2 13589 synchronized(this) { 3 13590 // It only makes sense to do this before the system is ready 4 13591 // and started launching other packages. 5 13592 if (!mSystemReady) { 6 13593 try { 7 13594 AppGlobals.getPackageManager().enterSafeMode(); 8 13595 } catch (RemoteException e) { 9 13596 } 10 13597 } 11 13598 12 13599 mSafeMode = true; 13 13600 } 14 13601 } 15 13602 16 13603 public final void showSafeModeOverlay() { 17 13604 View v = LayoutInflater.from(mContext).inflate( 18 13605 com.android.internal.R.layout.safe_mode, null); 19 13606 WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); 20 13607 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY; 21 13608 lp.width = WindowManager.LayoutParams.WRAP_CONTENT; 22 13609 lp.height = WindowManager.LayoutParams.WRAP_CONTENT; 23 13610 lp.gravity = Gravity.BOTTOM | Gravity.START; 24 13611 lp.format = v.getBackground().getOpacity(); 25 13612 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 26 13613 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; 27 13614 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS; 28 13615 ((WindowManager)mContext.getSystemService( 29 13616 Context.WINDOW_SERVICE)).addView(v, lp); 30 13617 }
通告alarm状态
1 13619 public void noteWakeupAlarm(IIntentSender sender, int sourceUid, String sourcePkg, String tag) { 2 13620 if (sender != null && !(sender instanceof PendingIntentRecord)) { 3 13621 return; 4 13622 } 5 13623 final PendingIntentRecord rec = (PendingIntentRecord)sender; 6 13624 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 7 13625 synchronized (stats) { 8 13626 if (mBatteryStatsService.isOnBattery()) { 9 13627 mBatteryStatsService.enforceCallingPermission(); 10 13628 int MY_UID = Binder.getCallingUid(); 11 13629 final int uid; 12 13630 if (sender == null) { 13 13631 uid = sourceUid; 14 13632 } else { 15 13633 uid = rec.uid == MY_UID ? SYSTEM_UID : rec.uid; 16 13634 } 17 13635 BatteryStatsImpl.Uid.Pkg pkg = 18 13636 stats.getPackageStatsLocked(sourceUid >= 0 ? sourceUid : uid, 19 13637 sourcePkg != null ? sourcePkg : rec.key.packageName); 20 13638 pkg.noteWakeupAlarmLocked(tag); 21 13639 } 22 13640 } 23 13641 } 24 13642 25 13643 public void noteAlarmStart(IIntentSender sender, int sourceUid, String tag) { 26 13644 if (sender != null && !(sender instanceof PendingIntentRecord)) { 27 13645 return; 28 13646 } 29 13647 final PendingIntentRecord rec = (PendingIntentRecord)sender; 30 13648 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 31 13649 synchronized (stats) { 32 13650 mBatteryStatsService.enforceCallingPermission(); 33 13651 int MY_UID = Binder.getCallingUid(); 34 13652 final int uid; 35 13653 if (sender == null) { 36 13654 uid = sourceUid; 37 13655 } else { 38 13656 uid = rec.uid == MY_UID ? SYSTEM_UID : rec.uid; 39 13657 } 40 13658 mBatteryStatsService.noteAlarmStart(tag, sourceUid >= 0 ? sourceUid : uid); 41 13659 } 42 13660 } 43 13661 44 13662 public void noteAlarmFinish(IIntentSender sender, int sourceUid, String tag) { 45 13663 if (sender != null && !(sender instanceof PendingIntentRecord)) { 46 13664 return; 47 13665 } 48 13666 final PendingIntentRecord rec = (PendingIntentRecord)sender; 49 13667 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 50 13668 synchronized (stats) { 51 13669 mBatteryStatsService.enforceCallingPermission(); 52 13670 int MY_UID = Binder.getCallingUid(); 53 13671 final int uid; 54 13672 if (sender == null) { 55 13673 uid = sourceUid; 56 13674 } else { 57 13675 uid = rec.uid == MY_UID ? SYSTEM_UID : rec.uid; 58 13676 } 59 13677 mBatteryStatsService.noteAlarmFinish(tag, sourceUid >= 0 ? sourceUid : uid); 60 13678 } 61 13679 }
杀进程,hang,restart系统
1 13681 public boolean killPids(int[] pids, String pReason, boolean secure) { 2 13682 if (Binder.getCallingUid() != SYSTEM_UID) { 3 13683 throw new SecurityException("killPids only available to the system"); 4 13684 } 5 13685 String reason = (pReason == null) ? "Unknown" : pReason; 6 13686 // XXX Note: don't acquire main activity lock here, because the window 7 13687 // manager calls in with its locks held. 8 13688 9 13689 boolean killed = false; 10 13690 synchronized (mPidsSelfLocked) { 11 13691 int worstType = 0; 12 13692 for (int i=0; i<pids.length; i++) { 13 13693 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 14 13694 if (proc != null) { 15 13695 int type = proc.setAdj; 16 13696 if (type > worstType) { 17 13697 worstType = type; 18 13698 } 19 13699 } 20 13700 } 21 13701 22 13702 // If the worst oom_adj is somewhere in the cached proc LRU range, 23 13703 // then constrain it so we will kill all cached procs. 24 13704 if (worstType < ProcessList.CACHED_APP_MAX_ADJ 25 13705 && worstType > ProcessList.CACHED_APP_MIN_ADJ) { 26 13706 worstType = ProcessList.CACHED_APP_MIN_ADJ; 27 13707 } 28 13708 29 13709 // If this is not a secure call, don't let it kill processes that 30 13710 // are important. 31 13711 if (!secure && worstType < ProcessList.SERVICE_ADJ) { 32 13712 worstType = ProcessList.SERVICE_ADJ; 33 13713 } 34 13714 35 13715 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType); 36 13716 for (int i=0; i<pids.length; i++) { 37 13717 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 38 13718 if (proc == null) { 39 13719 continue; 40 13720 } 41 13721 int adj = proc.setAdj; 42 13722 if (adj >= worstType && !proc.killedByAm) { 43 13723 proc.kill(reason, true); 44 13724 killed = true; 45 13725 } 46 13726 } 47 13727 } 48 13728 return killed; 49 13729 } 50 13730 51 13731 @Override 52 13732 public void killUid(int appId, int userId, String reason) { 53 13733 enforceCallingPermission(Manifest.permission.KILL_UID, "killUid"); 54 13734 synchronized (this) { 55 13735 final long identity = Binder.clearCallingIdentity(); 56 13736 try { 57 13737 killPackageProcessesLocked(null, appId, userId, 58 13738 ProcessList.PERSISTENT_PROC_ADJ, false, true, true, true, 59 13739 reason != null ? reason : "kill uid"); 60 13740 } finally { 61 13741 Binder.restoreCallingIdentity(identity); 62 13742 } 63 13743 } 64 13744 } 65 13745 66 13746 @Override 67 13747 public boolean killProcessesBelowForeground(String reason) { 68 13748 if (Binder.getCallingUid() != SYSTEM_UID) { 69 13749 throw new SecurityException("killProcessesBelowForeground() only available to system"); 70 13750 } 71 13751 72 13752 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason); 73 13753 } 74 13754 75 13755 private boolean killProcessesBelowAdj(int belowAdj, String reason) { 76 13756 if (Binder.getCallingUid() != SYSTEM_UID) { 77 13757 throw new SecurityException("killProcessesBelowAdj() only available to system"); 78 13758 } 79 13759 80 13760 boolean killed = false; 81 13761 synchronized (mPidsSelfLocked) { 82 13762 final int size = mPidsSelfLocked.size(); 83 13763 for (int i = 0; i < size; i++) { 84 13764 final int pid = mPidsSelfLocked.keyAt(i); 85 13765 final ProcessRecord proc = mPidsSelfLocked.valueAt(i); 86 13766 if (proc == null) continue; 87 13767 88 13768 final int adj = proc.setAdj; 89 13769 if (adj > belowAdj && !proc.killedByAm) { 90 13770 proc.kill(reason, true); 91 13771 killed = true; 92 13772 } 93 13773 } 94 13774 } 95 13775 return killed; 96 13776 } 97 13777 98 13778 @Override 99 13779 public void hang(final IBinder who, boolean allowRestart) { 100 13780 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 101 13781 != PackageManager.PERMISSION_GRANTED) { 102 13782 throw new SecurityException("Requires permission " 103 13783 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 104 13784 } 105 13785 106 13786 final IBinder.DeathRecipient death = new DeathRecipient() { 107 13787 @Override 108 13788 public void binderDied() { 109 13789 synchronized (this) { 110 13790 notifyAll(); 111 13791 } 112 13792 } 113 13793 }; 114 13794 115 13795 try { 116 13796 who.linkToDeath(death, 0); 117 13797 } catch (RemoteException e) { 118 13798 Slog.w(TAG, "hang: given caller IBinder is already dead."); 119 13799 return; 120 13800 } 121 13801 122 13802 synchronized (this) { 123 13803 Watchdog.getInstance().setAllowRestart(allowRestart); 124 13804 Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid()); 125 13805 synchronized (death) { 126 13806 while (who.isBinderAlive()) { 127 13807 try { 128 13808 death.wait(); 129 13809 } catch (InterruptedException e) { 130 13810 } 131 13811 } 132 13812 } 133 13813 Watchdog.getInstance().setAllowRestart(true); 134 13814 } 135 13815 } 136 13816 137 13817 @Override 138 13818 public void restart() { 139 13819 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 140 13820 != PackageManager.PERMISSION_GRANTED) { 141 13821 throw new SecurityException("Requires permission " 142 13822 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 143 13823 } 144 13824 145 13825 Log.i(TAG, "Sending shutdown broadcast..."); 146 13826 147 13827 BroadcastReceiver br = new BroadcastReceiver() { 148 13828 @Override public void onReceive(Context context, Intent intent) { 149 13829 // Now the broadcast is done, finish up the low-level shutdown. 150 13830 Log.i(TAG, "Shutting down activity manager..."); 151 13831 shutdown(10000); 152 13832 Log.i(TAG, "Shutdown complete, restarting!"); 153 13833 killProcess(myPid()); 154 13834 System.exit(10); 155 13835 } 156 13836 }; 157 13837 158 13838 // First send the high-level shut down broadcast. 159 13839 Intent intent = new Intent(Intent.ACTION_SHUTDOWN); 160 13840 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 161 13841 intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true); 162 13842 /* For now we are not doing a clean shutdown, because things seem to get unhappy. 163 13843 mContext.sendOrderedBroadcastAsUser(intent, 164 13844 UserHandle.ALL, null, br, mHandler, 0, null, null); 165 13845 */ 166 13846 br.onReceive(mContext, intent); 167 13847 }
low mem,idle处理
1 13849 private long getLowRamTimeSinceIdle(long now) { 2 13850 return mLowRamTimeSinceLastIdle + (mLowRamStartTime > 0 ? (now-mLowRamStartTime) : 0); 3 13851 } 4 13852 5 13853 @Override 6 13854 public void performIdleMaintenance() { 7 13855 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 8 13856 != PackageManager.PERMISSION_GRANTED) { 9 13857 throw new SecurityException("Requires permission " 10 13858 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 11 13859 } 12 13860 13 13861 synchronized (this) { 14 13862 final long now = SystemClock.uptimeMillis(); 15 13863 final long timeSinceLastIdle = now - mLastIdleTime; 16 13864 final long lowRamSinceLastIdle = getLowRamTimeSinceIdle(now); 17 13865 mLastIdleTime = now; 18 13866 mLowRamTimeSinceLastIdle = 0; 19 13867 if (mLowRamStartTime != 0) { 20 13868 mLowRamStartTime = now; 21 13869 } 22 13870 23 13871 StringBuilder sb = new StringBuilder(128); 24 13872 sb.append("Idle maintenance over "); 25 13873 TimeUtils.formatDuration(timeSinceLastIdle, sb); 26 13874 sb.append(" low RAM for "); 27 13875 TimeUtils.formatDuration(lowRamSinceLastIdle, sb); 28 13876 Slog.i(TAG, sb.toString()); 29 13877 30 13878 // If at least 1/3 of our time since the last idle period has been spent 31 13879 // with RAM low, then we want to kill processes. 32 13880 boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3); 33 13881 34 13882 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 35 13883 ProcessRecord proc = mLruProcesses.get(i); 36 13884 if (proc.notCachedSinceIdle) { 37 13885 if (proc.setProcState != ActivityManager.PROCESS_STATE_TOP_SLEEPING 38 13886 && proc.setProcState >= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE 39 13887 && proc.setProcState <= ActivityManager.PROCESS_STATE_SERVICE) { 40 13888 if (doKilling && proc.initialIdlePss != 0 41 13889 && proc.lastPss > ((proc.initialIdlePss*3)/2)) { 42 13890 sb = new StringBuilder(128); 43 13891 sb.append("Kill"); 44 13892 sb.append(proc.processName); 45 13893 sb.append(" in idle maint: pss="); 46 13894 sb.append(proc.lastPss); 47 13895 sb.append(", swapPss="); 48 13896 sb.append(proc.lastSwapPss); 49 13897 sb.append(", initialPss="); 50 13898 sb.append(proc.initialIdlePss); 51 13899 sb.append(", period="); 52 13900 TimeUtils.formatDuration(timeSinceLastIdle, sb); 53 13901 sb.append(", lowRamPeriod="); 54 13902 TimeUtils.formatDuration(lowRamSinceLastIdle, sb); 55 13903 Slog.wtfQuiet(TAG, sb.toString()); 56 13904 proc.kill("idle maint (pss " + proc.lastPss 57 13905 + " from " + proc.initialIdlePss + ")", true); 58 13906 } 59 13907 } 60 13908 } else if (proc.setProcState < ActivityManager.PROCESS_STATE_HOME 61 13909 && proc.setProcState >= ActivityManager.PROCESS_STATE_PERSISTENT) { 62 13910 proc.notCachedSinceIdle = true; 63 13911 proc.initialIdlePss = 0; 64 13912 proc.nextPssTime = ProcessList.computeNextPssTime(proc.setProcState, true, 65 13913 mTestPssMode, isSleepingLocked(), now); 66 13914 } 67 13915 } 68 13916 69 13917 mHandler.removeMessages(REQUEST_ALL_PSS_MSG); 70 13918 mHandler.sendEmptyMessageDelayed(REQUEST_ALL_PSS_MSG, 2*60*1000); 71 13919 } 72 13920 } 73 13921
发送idle job触发器
1 13922 @Override 2 13923 public void sendIdleJobTrigger() { 3 13924 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 4 13925 != PackageManager.PERMISSION_GRANTED) { 5 13926 throw new SecurityException("Requires permission " 6 13927 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 7 13928 } 8 13929 9 13930 final long ident = Binder.clearCallingIdentity(); 10 13931 try { 11 13932 Intent intent = new Intent(ACTION_TRIGGER_IDLE) 12 13933 .setPackage("android") 13 13934 .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 14 13935 broadcastIntent(null, intent, null, null, 0, null, null, null, 15 13936 android.app.AppOpsManager.OP_NONE, null, true, false, UserHandle.USER_ALL); 16 13937 } finally { 17 13938 Binder.restoreCallingIdentity(ident); 18 13939 } 19 13940 }
获取setting变化
1 13942 private void retrieveSettings() { 2 13943 final ContentResolver resolver = mContext.getContentResolver(); 3 13944 final boolean freeformWindowManagement = 4 13945 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT) 5 13946 || Settings.Global.getInt( 6 13947 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0; 7 13948 final boolean supportsPictureInPicture = 8 13949 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE); 9 13950 10 13951 final boolean supportsMultiWindow = ActivityManager.supportsMultiWindow(mContext); 11 13952 final boolean supportsSplitScreenMultiWindow = 12 13953 ActivityManager.supportsSplitScreenMultiWindow(mContext); 13 13954 final boolean supportsMultiDisplay = mContext.getPackageManager() 14 13955 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS); 15 13956 final String debugApp = Settings.Global.getString(resolver, DEBUG_APP); 16 13957 final boolean waitForDebugger = Settings.Global.getInt(resolver, WAIT_FOR_DEBUGGER, 0) != 0; 17 13958 final boolean alwaysFinishActivities = 18 13959 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0; 19 13960 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0; 20 13961 final boolean forceResizable = Settings.Global.getInt( 21 13962 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0; 22 13963 final long waitForNetworkTimeoutMs = Settings.Global.getLong(resolver, 23 13964 NETWORK_ACCESS_TIMEOUT_MS, NETWORK_ACCESS_TIMEOUT_DEFAULT_MS); 24 13965 final boolean supportsLeanbackOnly = 25 13966 mContext.getPackageManager().hasSystemFeature(FEATURE_LEANBACK_ONLY); 26 13967 27 13968 // Transfer any global setting for forcing RTL layout, into a System Property 28 13969 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0"); 29 13970 30 13971 final Configuration configuration = new Configuration(); 31 13972 Settings.System.getConfiguration(resolver, configuration); 32 13973 if (forceRtl) { 33 13974 // This will take care of setting the correct layout direction flags 34 13975 configuration.setLayoutDirection(configuration.locale); 35 13976 } 36 13977 37 13978 synchronized (this) { 38 13979 mDebugApp = mOrigDebugApp = debugApp; 39 13980 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger; 40 13981 mAlwaysFinishActivities = alwaysFinishActivities; 41 13982 mSupportsLeanbackOnly = supportsLeanbackOnly; 42 13983 mForceResizableActivities = forceResizable; 43 13984 final boolean multiWindowFormEnabled = freeformWindowManagement 44 13985 || supportsSplitScreenMultiWindow 45 13986 || supportsPictureInPicture 46 13987 || supportsMultiDisplay; 47 13988 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) { 48 13989 mSupportsMultiWindow = true; 49 13990 mSupportsFreeformWindowManagement = freeformWindowManagement; 50 13991 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow; 51 13992 mSupportsPictureInPicture = supportsPictureInPicture; 52 13993 mSupportsMultiDisplay = supportsMultiDisplay; 53 13994 } else { 54 13995 mSupportsMultiWindow = false; 55 13996 mSupportsFreeformWindowManagement = false; 56 13997 mSupportsSplitScreenMultiWindow = false; 57 13998 mSupportsPictureInPicture = false; 58 13999 mSupportsMultiDisplay = false; 59 14000 } 60 14001 mWindowManager.setForceResizableTasks(mForceResizableActivities); 61 14002 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture); 62 14003 // This happens before any activities are started, so we can change global configuration 63 14004 // in-place. 64 14005 updateConfigurationLocked(configuration, null, true); 65 14006 final Configuration globalConfig = getGlobalConfiguration(); 66 14007 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig); 67 14008 68 14009 // Load resources only after the current configuration has been set. 69 14010 final Resources res = mContext.getResources(); 70 14011 mHasRecents = res.getBoolean(com.android.internal.R.bool.config_hasRecents); 71 14012 mThumbnailWidth = res.getDimensionPixelSize( 72 14013 com.android.internal.R.dimen.thumbnail_width); 73 14014 mThumbnailHeight = res.getDimensionPixelSize( 74 14015 com.android.internal.R.dimen.thumbnail_height); 75 14016 mAppErrors.loadAppsNotReportingCrashesFromConfigLocked(res.getString( 76 14017 com.android.internal.R.string.config_appsNotReportingCrashes)); 77 14018 mUserController.mUserSwitchUiEnabled = !res.getBoolean( 78 14019 com.android.internal.R.bool.config_customUserSwitchUi); 79 14020 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) { 80 14021 mFullscreenThumbnailScale = (float) res 81 14022 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) / 82 14023 (float) globalConfig.screenWidthDp; 83 14024 } else { 84 14025 mFullscreenThumbnailScale = res.getFraction( 85 14026 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1); 86 14027 } 87 14028 mWaitForNetworkTimeoutMs = waitForNetworkTimeoutMs; 88 14029 } 89 14030 }
system ready回调
1 14032 public void systemReady(final Runnable goingCallback, BootTimingsTraceLog traceLog) { 2 14033 traceLog.traceBegin("PhaseActivityManagerReady"); 3 14034 synchronized(this) { 4 14035 if (mSystemReady) { 5 14036 // If we're done calling all the receivers, run the next "boot phase" passed in 6 14037 // by the SystemServer 7 14038 if (goingCallback != null) { 8 14039 goingCallback.run(); 9 14040 } 10 14041 return; 11 14042 } 12 14043 13 14044 mLocalDeviceIdleController 14 14045 = LocalServices.getService(DeviceIdleController.LocalService.class); 15 14046 mAssistUtils = new AssistUtils(mContext); 16 14047 mVrController.onSystemReady(); 17 14048 // Make sure we have the current profile info, since it is needed for security checks. 18 14049 mUserController.onSystemReady(); 19 14050 mRecentTasks.onSystemReadyLocked(); 20 14051 mAppOpsService.systemReady(); 21 14052 mSystemReady = true; 22 14053 } 23 14054 24 14055 ArrayList<ProcessRecord> procsToKill = null; 25 14056 synchronized(mPidsSelfLocked) { 26 14057 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) { 27 14058 ProcessRecord proc = mPidsSelfLocked.valueAt(i); 28 14059 if (!isAllowedWhileBooting(proc.info)){ 29 14060 if (procsToKill == null) { 30 14061 procsToKill = new ArrayList<ProcessRecord>(); 31 14062 } 32 14063 procsToKill.add(proc); 33 14064 } 34 14065 } 35 14066 } 36 14067 37 14068 synchronized(this) { 38 14069 if (procsToKill != null) { 39 14070 for (int i=procsToKill.size()-1; i>=0; i--) { 40 14071 ProcessRecord proc = procsToKill.get(i); 41 14072 Slog.i(TAG, "Removing system update proc: " + proc); 42 14073 removeProcessLocked(proc, true, false, "system update done"); 43 14074 } 44 14075 } 45 14076 46 14077 // Now that we have cleaned up any update processes, we 47 14078 // are ready to start launching real processes and know that 48 14079 // we won't trample on them any more. 49 14080 mProcessesReady = true; 50 14081 } 51 14082 52 14083 Slog.i(TAG, "System now ready"); 53 14084 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY, 54 14085 SystemClock.uptimeMillis()); 55 14086 56 14087 synchronized(this) { 57 14088 // Make sure we have no pre-ready processes sitting around. 58 14089 59 14090 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) { 60 14091 ResolveInfo ri = mContext.getPackageManager() 61 14092 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), 62 14093 STOCK_PM_FLAGS); 63 14094 CharSequence errorMsg = null; 64 14095 if (ri != null) { 65 14096 ActivityInfo ai = ri.activityInfo; 66 14097 ApplicationInfo app = ai.applicationInfo; 67 14098 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 68 14099 mTopAction = Intent.ACTION_FACTORY_TEST; 69 14100 mTopData = null; 70 14101 mTopComponent = new ComponentName(app.packageName, 71 14102 ai.name); 72 14103 } else { 73 14104 errorMsg = mContext.getResources().getText( 74 14105 com.android.internal.R.string.factorytest_not_system); 75 14106 } 76 14107 } else { 77 14108 errorMsg = mContext.getResources().getText( 78 14109 com.android.internal.R.string.factorytest_no_action); 79 14110 } 80 14111 if (errorMsg != null) { 81 14112 mTopAction = null; 82 14113 mTopData = null; 83 14114 mTopComponent = null; 84 14115 Message msg = Message.obtain(); 85 14116 msg.what = SHOW_FACTORY_ERROR_UI_MSG; 86 14117 msg.getData().putCharSequence("msg", errorMsg); 87 14118 mUiHandler.sendMessage(msg); 88 14119 } 89 14120 } 90 14121 } 91 14122 92 14123 retrieveSettings(); 93 14124 final int currentUserId; 94 14125 synchronized (this) { 95 14126 currentUserId = mUserController.getCurrentUserIdLocked(); 96 14127 readGrantedUriPermissionsLocked(); 97 14128 } 98 14129 99 14130 if (goingCallback != null) goingCallback.run(); 100 14131 traceLog.traceBegin("ActivityManagerStartApps"); 101 14132 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, 102 14133 Integer.toString(currentUserId), currentUserId); 103 14134 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, 104 14135 Integer.toString(currentUserId), currentUserId); 105 14136 mSystemServiceManager.startUser(currentUserId); 106 14137 107 14138 synchronized (this) { 108 14139 // Only start up encryption-aware persistent apps; once user is 109 14140 // unlocked we'll come back around and start unaware apps 110 14141 startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE); 111 14142 112 14143 // Start up initial activity. 113 14144 mBooting = true; 114 14145 // Enable home activity for system user, so that the system can always boot. We don't 115 14146 // do this when the system user is not setup since the setup wizard should be the one 116 14147 // to handle home activity in this case. 117 14148 if (UserManager.isSplitSystemUser() && 118 14149 Settings.Secure.getInt(mContext.getContentResolver(), 119 14150 Settings.Secure.USER_SETUP_COMPLETE, 0) != 0) { 120 14151 ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class); 121 14152 try { 122 14153 AppGlobals.getPackageManager().setComponentEnabledSetting(cName, 123 14154 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0, 124 14155 UserHandle.USER_SYSTEM); 125 14156 } catch (RemoteException e) { 126 14157 throw e.rethrowAsRuntimeException(); 127 14158 } 128 14159 } 129 14160 startHomeActivityLocked(currentUserId, "systemReady"); 130 14161 131 14162 try { 132 14163 if (AppGlobals.getPackageManager().hasSystemUidErrors()) { 133 14164 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your" 134 14165 + " data partition or your device will be unstable."); 135 14166 mUiHandler.obtainMessage(SHOW_UID_ERROR_UI_MSG).sendToTarget(); 136 14167 } 137 14168 } catch (RemoteException e) { 138 14169 } 139 14170 140 14171 if (!Build.isBuildConsistent()) { 141 14172 Slog.e(TAG, "Build fingerprint is not consistent, warning user"); 142 14173 mUiHandler.obtainMessage(SHOW_FINGERPRINT_ERROR_UI_MSG).sendToTarget(); 143 14174 } 144 14175 145 14176 long ident = Binder.clearCallingIdentity(); 146 14177 try { 147 14178 Intent intent = new Intent(Intent.ACTION_USER_STARTED); 148 14179 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 149 14180 | Intent.FLAG_RECEIVER_FOREGROUND); 150 14181 intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId); 151 14182 broadcastIntentLocked(null, null, intent, 152 14183 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 153 14184 null, false, false, MY_PID, SYSTEM_UID, 154 14185 currentUserId); 155 14186 intent = new Intent(Intent.ACTION_USER_STARTING); 156 14187 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 157 14188 intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId); 158 14189 broadcastIntentLocked(null, null, intent, 159 14190 null, new IIntentReceiver.Stub() { 160 14191 @Override 161 14192 public void performReceive(Intent intent, int resultCode, String data, 162 14193 Bundle extras, boolean ordered, boolean sticky, int sendingUser) 163 14194 throws RemoteException { 164 14195 } 165 14196 }, 0, null, null, 166 14197 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE, 167 14198 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL); 168 14199 } catch (Throwable t) { 169 14200 Slog.wtf(TAG, "Failed sending first user broadcasts", t); 170 14201 } finally { 171 14202 Binder.restoreCallingIdentity(ident); 172 14203 } 173 14204 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 174 14205 mUserController.sendUserSwitchBroadcastsLocked(-1, currentUserId); 175 14206 traceLog.traceEnd(); // ActivityManagerStartApps 176 14207 traceLog.traceEnd(); // PhaseActivityManagerReady 177 14208 } 178 14209 }
根据用户请求杀掉app
1 14211 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) { 2 14212 synchronized (this) { 3 14213 mAppErrors.killAppAtUserRequestLocked(app, fromDialog); 4 14214 } 5 14215 }
跳过当前接收的广播
1 14217 void skipCurrentReceiverLocked(ProcessRecord app) { 2 14218 for (BroadcastQueue queue : mBroadcastQueues) { 3 14219 queue.skipCurrentReceiverLocked(app); 4 14220 } 5 14221
浙公网安备 33010602011771号