Android 8.0+ 后臺廣播限制分析

一、背景

廣播限制官方文檔

為了減少后臺應用的系統資源消耗,提升用戶體驗,Android 7.0(API 級別 24)對廣播施加了限制,Android 8.0(API 級別 26)讓這些限制更為嚴格。

限制點Android 8.0 +版本的應用無法靜態注冊廣播接收者接收到隱式廣播。

基于android-13.0.0_r43 源碼測試:

廣播接收者 廣播發送方 結果
靜態注冊 隱式廣播 ?
靜態注冊 顯式廣播 ?
靜態注冊 隱式廣播 + addFlags(0x01000000)FLAG_RECEIVER_INCLUDE_BACKGROUND ?
靜態注冊 豁免的系統隱式廣播
測試:BOOT_COMPLETED
注:接收方需要添加權限:<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
?
動態注冊 隱式/顯式廣播 ?

另外:需要簽名權限的廣播不受此限制所限,因為這些廣播只會發送到使用相同證書簽名的應用,而不是發送到設備上的所有應用。

二、限制點源碼分析

2.1 調試發送廣播方法梳理出核心調用棧:

at com.android.server.am.BroadcastQueue.performReceiveLocked(Native Method)
at com.android.server.am.BroadcastQueue.processNextBroadcastLocked(BroadcastQueue.java:1359)
at com.android.server.am.BroadcastQueue.processNextBroadcast(BroadcastQueue.java:1155)
at com.android.server.am.BroadcastQueue$BroadcastHandler.handleMessage(BroadcastQueue.java:224)
at com.android.server.am.BroadcastQueue.scheduleBroadcastsLocked(Native Method)
at com.android.server.am.ActivityManagerService.broadcastIntentLocked(ActivityManagerService.java:14208)
at com.android.server.am.ActivityManagerService.broadcastIntentWithFeature(ActivityManagerService.java:14461)
at android.app.ContextImpl.sendBroadcastAsUser(ContextImpl.java:1416)

2.2 核心限制點邏輯分析

Background execution not allowed: receiving Intent { act=android.intent.action.EVAN flg=0x10 } to com.stan.simpledemo/.TestReceiver

基于系統限制日志, 定位代碼:

com.android.server.am.BroadcastQueue#processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj)

...
        // 靜態注冊的廣播接收者限制點
        if (!skip) {
              // ① AMS. getAppStartModeLOSP 返回的mode值
            final int allowed = mService.getAppStartModeLOSP( 成mode
                    info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
                    info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false, false);
            if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
                // We won't allow this receiver to be launched if the app has been
                // completely disabled from launches, or it was not explicitly sent
                // to it and the app is in a state that should not receive it
                // (depending on how getAppStartModeLOSP has determined that).
                if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
                    Slog.w(TAG, "Background execution disabled: receiving "
                            + r.intent + " to "
                            + component.flattenToShortString());
                    skip = true;
                  // ② intent參數判斷
                } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
                        || (r.intent.getComponent() == null
                            && r.intent.getPackage() == null
                            && ((r.intent.getFlags()
                                    & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0)
                            && !isSignaturePerm(r.requiredPermissions))) { 
                    mService.addBackgroundCheckViolationLocked(r.intent.getAction(),
                            component.getPackageName());
                    Slog.w(TAG, "Background execution not allowed: receiving "
                            + r.intent + " to "
                            + component.flattenToShortString());
                    skip = true;
                }
            }
        }
        ...

這里主要有兩個部分:

  • ① AMS. getAppStartModeLOSP 生成mode
  • ② intent參數判斷

結合前面的測試,來看下是如何限制的:
① getAppStartModeLOSP 核心邏輯:

 final int startMode = (alwaysRestrict)  //當前路徑下alwaysRestrict = true
                        ? appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk)
                        : appServicesRestrictedInBackgroundLOSP(uid, packageName,
                                packageTargetSdk);

而appRestrictedInBackgroundLOSP開頭就是版本限制:

int appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) {
        // Apps that target O+ are always subject to background check
        if (packageTargetSdk >= Build.VERSION_CODES.O) {
            if (DEBUG_BACKGROUND_CHECK) {
                Slog.i(TAG, "App " + uid + "/" + packageName + " targets O+, restricted");
            }
            return ActivityManager.APP_START_MODE_DELAYED_RIGID;
        }
...
從調試看,基本都是返回 2 即:APP_START_MODE_DELAYED_RIGID

② intent參數判斷

((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
 
 || (r.intent.getComponent() == null 
     && r.intent.getPackage() == null 
     && ((r.intent.getFlags()& Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0)
     && !isSignaturePerm(r.requiredPermissions))

二者滿足其一,廣播接收就會被限制。

不限制條件總結:
首先,intent不包含FLAG_RECEIVER_EXCLUDE_BACKGROUND,在此基礎上:

  • 1)發送顯示廣播,即指定Component,r.intent.getComponent() == null 不滿足而繞過;
  • 2)intent包含flag: Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND 即&上該flags不等于0繞過;
  • 3)滿足組件簽名權限條件的,可以繞過;

至此,我們已經知道了,為什么發送顯示廣播、添加FLAG_RECEIVER_INCLUDE_BACKGROUND flag 、滿足組件簽名權限條件可以繞過后臺廣播限制。

那么最后,豁免的系統隱式廣播是怎么繞過的呢? 還是BOOT_COMPLETED舉例分析:

com.android.server.am.UserController#sendLockedBootCompletedBroadcast

    private void sendLockedBootCompletedBroadcast(IIntentReceiver receiver, @UserIdInt int userId) {
        final Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
        intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
        intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
                | Intent.FLAG_RECEIVER_OFFLOAD
                | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); // 添加了FLAG_RECEIVER_INCLUDE_BACKGROUND
        mInjector.broadcastIntent(intent, null, receiver, 0, null, null,
                new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
                AppOpsManager.OP_NONE,
                getTemporaryAppAllowlistBroadcastOptions(REASON_LOCKED_BOOT_COMPLETED)
                        .toBundle(), true,
                false, MY_PID, SYSTEM_UID,
                Binder.getCallingUid(), Binder.getCallingPid(), userId);
    }

這里明顯看到構建Intent的時候,添加了FLAG_RECEIVER_INCLUDE_BACKGROUND。

2.3 廠商魔改分析
經過測試,普通三方應用靜態注冊的情況下,基于原生系統顯式廣播/flag/豁免系統廣播方式均可拉活應用,但是廠商(小米、華為、榮耀、vivo、oppo)均無法拉活, 主要是針對三方應用非存活狀態下廣播接收做了限制。

oppo(colorOs14 android 14)為例:
系統日志:

2024-10-24 17:08:54.652  1816-1877  OplusAppStartupManager  system_server                        W  prevent start com.stan.simpledemo, cmp ComponentInfo{com.stan.simpledemo/com.stan.simpledemo.TestReceiver} by broadcast com.stan.evan callingUid 10176, scenePriority = 0

定位到觸發的方法:com.android.server.am.OplusAppStartupManager#shouldPreventSendReceiverReal
限制關鍵方法:com.android.server.am.OplusAppStartupManager#isAllowForSPS

 private SPSCase isAllowForSPS(Intent intent, int callingUid, String pkgName, String cpnName, int uid, String cpnType, ApplicationInfo appInfo) {
        if (this.mOplusStartupStrategy.isInLruProcessesLocked(uid) && uid > 10000) {
            return SPSCase.TRUE;
...
 }

uid大于10000的應用需要進程存活情況下才不會被限制拉活。

其他廠商不做一一分析,這里僅貼下關鍵系統日志:
xiaomi:

10-24 16:35:34.018  2267  2311 W WakePathChecker: MIUILOG-AutoStart, Service/Provider/Broadcast Reject userId= 0 caller= com.stan.evan callee= com.stan.simpledemo classname=com.stan.simpledemo.TestReceiver action=android.intent.action.EVAN wakeType=2

10-24 16:35:34.018  2267  2311 W BroadcastQueueInjector: Unable to launch app com.stan.simpledemo/10181 for broadcast Intent { act=android.intent.action.EVAN flg=0x10 cmp=com.stan.simpledemo/.TestReceiver }: process is not permitted to  wake path

vivo:

10-24 17:16:29.321  1486  1680 D _V_VivoBroadcastQueueModernImpl: intent:Intent { act=android.intent.action.EVAN flg=0x10 cmp=com.stan.simpledemo/.TestReceiver },toBeFiltered:true,userid:10325,packageName:com.stan.simpledemo

huawei/honor:

10-24 16:48:39.746  1692  3400 I ActivityManager: App 10040/com.stan.simpledemo targets O+, restricted
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容