Android 8.0+ 后臺(tái)廣播限制分析

一、背景

廣播限制官方文檔

為了減少后臺(tái)應(yīng)用的系統(tǒng)資源消耗,提升用戶體驗(yàn),Android 7.0(API 級(jí)別 24)對(duì)廣播施加了限制,Android 8.0(API 級(jí)別 26)讓這些限制更為嚴(yán)格。

限制點(diǎn)Android 8.0 +版本的應(yīng)用無(wú)法靜態(tài)注冊(cè)廣播接收者接收到隱式廣播。

基于android-13.0.0_r43 源碼測(cè)試:

廣播接收者 廣播發(fā)送方 結(jié)果
靜態(tài)注冊(cè) 隱式廣播 ?
靜態(tài)注冊(cè) 顯式廣播 + 目標(biāo)進(jìn)程存活 ?
靜態(tài)注冊(cè) 隱式廣播 + addFlags(0x01000000)FLAG_RECEIVER_INCLUDE_BACKGROUND ?
靜態(tài)注冊(cè) 豁免的系統(tǒng)隱式廣播
測(cè)試:BOOT_COMPLETED
注:接收方需要添加權(quán)限:<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
? 但是廠商都不行了?
動(dòng)態(tài)注冊(cè) 隱式/顯式廣播 ?

另外:需要簽名權(quán)限的廣播不受此限制所限,因?yàn)檫@些廣播只會(huì)發(fā)送到使用相同證書簽名的應(yīng)用,而不是發(fā)送到設(shè)備上的所有應(yīng)用。

靜態(tài)注冊(cè)的方式,目標(biāo)進(jìn)程需要存活,如果不存活,也拉活不了。

二、限制點(diǎn)源碼分析

2.1 調(diào)試發(fā)送廣播方法梳理出核心調(diào)用棧:

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 核心限制點(diǎn)邏輯分析

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

基于系統(tǒng)限制日志, 定位代碼:

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

...
        // 靜態(tài)注冊(cè)的廣播接收者限制點(diǎn)
        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參數(shù)判斷
                } 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;
                }
            }
        }
        ...

這里主要有兩個(gè)部分:

  • ① AMS. getAppStartModeLOSP 生成mode
  • ② intent參數(shù)判斷

結(jié)合前面的測(cè)試,來(lái)看下是如何限制的:
① getAppStartModeLOSP 核心邏輯:

 final int startMode = (alwaysRestrict)  //當(dāng)前路徑下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;
        }
...
從調(diào)試看,基本都是返回 2 即:APP_START_MODE_DELAYED_RIGID

② intent參數(shù)判斷

((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))

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

不限制條件總結(jié):
首先,intent不包含F(xiàn)LAG_RECEIVER_EXCLUDE_BACKGROUND,在此基礎(chǔ)上:

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

至此,我們已經(jīng)知道了,為什么發(fā)送顯示廣播、添加FLAG_RECEIVER_INCLUDE_BACKGROUND flag 、滿足組件簽名權(quán)限條件可以繞過(guò)后臺(tái)廣播限制。

那么最后,豁免的系統(tǒng)隱式廣播是怎么繞過(guò)的呢? 還是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);
    }

這里明顯看到構(gòu)建Intent的時(shí)候,添加了FLAG_RECEIVER_INCLUDE_BACKGROUND。

2.3 廠商魔改分析

經(jīng)過(guò)測(cè)試,普通三方應(yīng)用靜態(tài)注冊(cè)的情況下,基于原生系統(tǒng)顯式廣播/flag/豁免系統(tǒng)廣播方式均可拉活應(yīng)用,但是廠商(小米、華為、榮耀、vivo、oppo)均無(wú)法拉活, 主要是針對(duì)三方應(yīng)用非存活狀態(tài)下廣播接收做了限制。

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

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

定位到觸發(fā)的方法:com.android.server.am.OplusAppStartupManager#shouldPreventSendReceiverReal
限制關(guān)鍵方法: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的應(yīng)用需要進(jìn)程存活情況下才不會(huì)被限制拉活。

其他廠商不做一一分析,這里僅貼下關(guān)鍵系統(tǒng)日志:
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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過(guò)簡(jiǎn)信或評(píng)論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容