Android後臺啟動Activity的實現示例

概述

前幾天產品提瞭一個需求,想在後臺的時候啟動我們 APP 的一個 Activity,隨著 Android 版本的更新,以及各傢 ROM 廠商的無限改造,這種影響用戶體驗的功能許多都受到瞭限制,沒辦法,雖然是比較流氓的功能,但拿人錢財替人消災,於是開啟瞭哼哧哼哧的調研之路。

原生Android ROM

首先從 Android 的原生 ROM 開始,根據官方的介紹,後臺啟動 Activity 的限制是從 Android 10(API 29) 才開始的,在此之前原生 ROM 是沒有這個限制的,於是我分別啟動瞭一個 Android 9(API 28) 和 10(API 29) 版本的模擬器,發現在 API 28 上可以直接從後臺啟動 Activity,而在 API 29 上則受到瞭限制無法直接啟動。參照官方 從後臺啟動 Activity 的限制 的說明,給出瞭一些不受限制的例外情況,此外官方的推薦是對於後臺啟動的需求,先向用戶展示一個 Notification 而不是直接啟動 Activity,然後在用戶點擊 Notification 後才處理對應的邏輯。還可以在設置 Notification 時通過 setFullScreenIntent 添加一個全屏 Intent 對象,該方法經過測試,可以在 Android 10 的模擬器上從後臺啟動一個 Activity 界面(需要 android.permission.USE_FULL_SCREEN_INTENT 權限)。代碼如下:

object NotificationUtils {
    private const val ID = "channel_1"
    private const val NAME = "notification"

    private var manager: NotificationManager? = null

    private fun getNotificationManagerManager(context: Context): NotificationManager? {
        if (manager == null) {
            manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
        }
        return manager
    }

    fun sendNotificationFullScreen(context: Context, title: String?, content: String?) {
        if (Build.VERSION.SDK_INT >= 26) {
            clearAllNotification(context)
            val channel = NotificationChannel(ID, NAME, NotificationManager.IMPORTANCE_HIGH)
            channel.setSound(null, null)
            getNotificationManagerManager(context)?.createNotificationChannel(channel)
            val notification = getChannelNotificationQ(context, title, content)
            getNotificationManagerManager(context)?.notify(1, notification)
        }
    }

    private fun clearAllNotification(context: Context) {
        getNotificationManagerManager(context)?.cancelAll()
    }

    private fun getChannelNotificationQ(context: Context, title: String?, content: String?): Notification {
        val fullScreenPendingIntent = PendingIntent.getActivity(
            context,
            0,
            DemoActivity.genIntent(context),
            PendingIntent.FLAG_UPDATE_CURRENT
        )
        val notificationBuilder = NotificationCompat.Builder(context, ID)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle(title)
            .setContentText(content)
            .setSound(null)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setCategory(Notification.CATEGORY_CALL)
            .setOngoing(true)
            .setFullScreenIntent(fullScreenPendingIntent, true)
        return notificationBuilder.build()
    }
}

到現在,整體上感覺還是不錯的,現階段的 Android 原生 ROM 都能正常地從後臺啟動 Activity 界面,無論是 Android 9 還是 10 版本,都美滋滋。

定制化ROM

問題開始浮出水面,由於各大廠商對 Android 的定制化各有不一,而 Android 並沒有繼承 GPL 協議,它使用的是 Apache 開源許可協議,即第三方廠商在修改代碼後可以閉源,因此也無法得知廠商 ROM 的源碼到底做瞭哪些修改。有的機型增加瞭一項權限——後臺彈出界面,比如說在 MIUI 上便新增瞭這項權限且默認是關閉的,除非加入瞭它們的白名單,小米開放平臺的文檔 裡有說明:該權限默認為拒絕的,既為應用默認不允許在後臺彈出頁面,針對特殊應用會提供白名單,例如音樂(歌詞顯示)、運動、VOIP(來電)等;白名單應用一旦出現推廣等惡意行為,將永久取消白名單。

檢測後臺彈出界面權限

在小米機型上,新增的這個 後臺彈出界面 的權限是在 AppOpsService 裡擴展瞭新的權限,查看 AppOpsManager 源代碼,可以在裡面看到許多熟悉的常量:

@SystemService(Context.APP_OPS_SERVICE)
public class AppOpsManager {
    public static final int OP_GPS = 2;
    public static final int OP_READ_CONTACTS = 4;
    // ...
}

因此可以通過 AppOpsService 來檢測是否具有 後臺彈出界面 的權限,那麼這個權限對應的 OpCode 是啥呢?網上有知情人士透露這個權限的 Code 是 10021,因此可以使用 AppOpsManager.checkOpNoThrow 或 AppOpsManager.noteOpNoThrow 等系列的方法檢測該權限是否存在,不過這些方法都是 @hide 標識的,需要使用反射:

fun checkOpNoThrow(context: Context, op: Int): Boolean {
    val ops = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
    try {
        val method: Method = ops.javaClass.getMethod(
            "checkOpNoThrow", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, String::class.java
        )
        val result = method.invoke(ops, op, myUid(), context.packageName) as Int
        return result == AppOpsManager.MODE_ALLOWED
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return false
}

fun noteOpNoThrow(context: Context, op: Int): Int {
    val ops = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
    try {
        val method: Method = ops.javaClass.getMethod(
            "noteOpNoThrow", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, String::class.java
        )
        return method.invoke(ops, op, myUid(), context.packageName) as Int
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return -100
}

另外如果想知道其它新增權限的 code, 可以通過上面的方法去遍歷某個范圍(如10000~10100)內的 code 的權限,然後手機操作去開關想要查詢的權限,根據遍歷的結果,就大致可以得到對應權限的 code 瞭。

Android P後臺啟動權限

在小米 Max3 上測試發現瞭兩種方式可以實現從後臺啟動 Activity 界面,其系統是基於 Android 9 的 MIUI 系統。

方式一:moveTaskToFront

這種方式不算是直接從後臺啟動 Activity,而是換瞭一個思路,在後臺啟動目標 Activity 之前先將應用切換到前臺,然後再啟動目標 Activity,如果有必要的話,還可以通過 Activity.moveTaskToBack 方法將之前切換到前臺的 Activity 重新移入後臺,經過測試,在 Android 10 上這個方法已經失效瞭…但是 10 以下的版本還是可以搶救一下的(需要聲明 android.permission.REORDER_TASKS 權限)。

啟動目標 Activity 之前先判斷一下應用是否在後臺,判斷方法可以借助 ActivityManager.getRunningAppProcesses 方法或者 Application.ActivityLifecycleCallbacks 來監聽前後臺,這兩種方法網上都有文章講解,就不贅述瞭。直接貼出後臺切換到前臺的代碼:

fun moveToFront(context: Context) {
    val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
    activityManager?.getRunningTasks(100)?.forEach { taskInfo ->
        if (taskInfo.topActivity?.packageName == context.packageName) {
            Log.d("LLL", "Try to move to front")
            activityManager.moveTaskToFront(taskInfo.id, 0)
            return
        }
    }
}

fun startActivity(activity: Activity, intent: Intent) {
    if (!isRunningForeground(activity)) {
        Log.d("LLL", "Now is in background")
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            // TODO 防止 moveToFront 失敗,可以多嘗試調用幾次
            moveToFront(activity)
            activity.startActivity(intent)
            activity.moveTaskToBack(true)
        } else {
            NotificationUtils.sendNotificationFullScreen(activity, "", "")
        }
    } else {
        Log.d("LLL", "Now is in foreground")
        activity.startActivity(intent)
    }
}

方式二:Hook

由於 MIUI 系統不開源,因此嘗試再研究研究 AOSP 源碼,死馬當活馬醫看能不能找到什麼蛛絲馬跡。首先從 Activity.startActivity 方法開始追,如果閱讀過 Activity 啟動源碼流程的話可以知道 Activity.startActivity 或調用到 Instrumentation.execStartActivity 中,然後通過 Binder 調用到 AMS 相關的方法,權限認證就在 AMS 中完成,如果權限不滿足自然啟動就失敗瞭(Android 10)。

// APP 進程
public ActivityResult execStartActivity(Context who, IBinder contextThread, ...) {
    // ...
    // 這裡會通過 Binder 調用到 AMS 相關的代碼
    int result = ActivityManager.getService().startActivity(whoThread, who.getBasePackageName(),
            intent, intent.resolveTypeIfNeeded(who.getContentResolver()),
            token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
    // ...
}

// system_server進程
// AMS
public final int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
    String resolvedType, IBinder resultTo, String resultWho, int requestCode,
    int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
    // ...
}

看一下這幾個參數:

  • caller: AMS 在完成相關任務後會通過它來 Binder 調用到客戶端 APP 進程來實例化 Activity 對象並回調其生命周期方法,caller 的 Binder 服務端位於 APP 進程。
  • callingPackage: 這個參數標識調用者包名。

這裡可以嘗試 Hook 一些系統的東西,具體怎麼 Hook 的代碼先不給出瞭,經過測試在 Android 9 的小米設備上可以成功,有興趣可以自行研究談論哈,暫時不公開瞭,有需要的同學可以留言告訴我。或者反編譯小米 ROM 源碼,可以從裡面發現一些東西。

Android Q後臺啟動權限

在上面介紹過 Android Q 版本開始原生系統也加入瞭後臺啟動的限制,通過通知設置 fullScreenIntent 可以在原生 Android 10 系統上從後臺啟動 Activity。查看 AOSP 源碼,可以在 AMS 找到這部分後臺權限限制的代碼,上面講到 startActivity 的流程,在 APP 進程發起請求後,會通過 Binder 跨進程調用到 system_server 進程中的 AMS,然後調用到 ActivityStarter.startActivity 方法,關於後臺啟動的限制就這這裡:

// 好傢夥,整整二十多個參數,嘿嘿,嘿嘿
private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
        String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
        String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
        SafeActivityOptions options,
        boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
        TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup,
        PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
    // ...
    boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho,
        requestCode, callingPid, callingUid, callingPackage, ignoreTargetSecurity,
        inTask != null, callerApp, resultRecord, resultStack);
    abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
            callingPid, resolvedType, aInfo.applicationInfo);
    abort |= !mService.getPermissionPolicyInternal().checkStartActivity(intent, callingUid,
            callingPackage);

    boolean restrictedBgActivity = false;
    if (!abort) {
        restrictedBgActivity = shouldAbortBackgroundActivityStart(callingUid,
                callingPid, callingPackage, realCallingUid, realCallingPid, callerApp,
                originatingPendingIntent, allowBackgroundActivityStart, intent);
    }
    // ...
}

這裡的 shouldAbortBackgroundActivityStart 調用是在 Android Q 中新增的,看方法名就能菜刀這是針對後臺啟動的:

boolean shouldAbortBackgroundActivityStart(...) {
    final int callingAppId = UserHandle.getAppId(callingUid);
    if (callingUid == Process.ROOT_UID || callingAppId == Process.SYSTEM_UID
            || callingAppId == Process.NFC_UID) {
        return false;
    }
    if (callingUidHasAnyVisibleWindow || isCallingUidPersistentSystemProcess) {
        return false;
    }
    // don't abort if the callingUid has START_ACTIVITIES_FROM_BACKGROUND permission
    if (mService.checkPermission(START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid)
            == PERMISSION_GRANTED) {
        return false;
    }
    // don't abort if the caller has the same uid as the recents component
    if (mSupervisor.mRecentTasks.isCallerRecents(callingUid)) {
        return false;
    }
    // don't abort if the callingUid is the device owner
    if (mService.isDeviceOwner(callingUid)) {
        return false;
    }
    // don't abort if the callingUid has SYSTEM_ALERT_WINDOW permission
    if (mService.hasSystemAlertWindowPermission(callingUid, callingPid, callingPackage)) {
        Slog.w(TAG, "Background activity start for " + callingPackage
                + " allowed because SYSTEM_ALERT_WINDOW permission is granted.");
        return false;
    }
    // ...
}

從這個方法可以看到後臺啟動的限制和官方文檔 從後臺啟動 Activity 的限制 中的說明是可以對應上的,這裡面都是針對 uid 去做權限判斷的,且是在系統進程 system_server 中完成,單純更改包名已經沒用瞭。。。

在一些沒有針對後臺啟動單獨做限制的 ROM 上通過 全屏通知 可以成功彈出後臺 Activity 頁面,比如說小米 A3,另外還有一臺 vivo 和一臺三星手機,具體機型忘記瞭;在做瞭限制的設備上則彈不出來,比如說紅米 Note 8 Pro。

對於紅米 Note 8 Pro 這塊硬骨頭,不停嘗試瞭好多方法,但其實都是碰運氣的,因為拿不到 MIUI 的源碼,後來想轉變思路,是否可以嘗試從這臺手機上 pull 出相關的 framework.jar 包然後反編譯呢?說不定就有收獲!不過需要 Root 手機,這個好辦,小米自己是有提供可以 Root 的開發版系統的,於是就去 MIUI 官網找瞭一下,發現這臺紅米 Note 8 Pro 機型沒有提供開發版系統(笑哭),想起來好像之前是說過低端機小米不再提供開發版瞭。。。好吧,手裡頭沒有其它可以嘗試的手機瞭。

再轉念一想,是否可以直接下載穩定版的 ROM 包,解壓後有沒有工具能夠得到一些源碼相關的痕跡呢?於是下載瞭一個 ROM.zip 後,解壓看到裡面隻有一些系統映像 img 文件和 .dat.br 文件,這一塊我還不太懂,猜想就算能得到我想要的東西,整套流程花費的時間成本估計也超出預期瞭,所以暫時隻能先放下這個想法瞭。後續有足夠的時間再深入研究研究吧。

總結

原生Android ROM

Android 原生 ROM 都能正常地從後臺啟動 Activity 界面,無論是 Android 9(直接啟動) 還是 10 版本(借助全屏通知)。

定制化ROM

檢測後臺彈出界面權限:

  • 通過反射 AppOpsManager 相關方法檢測對應 opCode 的權限;
  • opCode = 10021(小米機型);
  • 其它機型可以嘗試遍歷得到 opCode;

Android P版本的小米:

  • 通過Hook相關參數來後臺啟動Activity,代碼由於某些原因不能給出瞭,有需要的同學可以留言告訴我哈;
  • 隻測試過小米機型,其它機型不一定可用;
  • 理論上 P 版本以下的小米應該也支持;

Android P版本的機型:

  • 通過 moveTaskToFront 方法將應用切換到前臺;
  • 這種方法畢竟是官方 API,因此兼容性可能更好一些;
  • 如果切換失敗的話可以多嘗試幾次調用 moveTaskToFront 方法;
  • 理論上 P 版本以下的機型應該也支持;

Android Q版本的機型:

  • 通過系統全屏通知的方式調起後臺 Activity;
  • 在一些另作瞭限制的 ROM 上可能調起失敗;

至於反編譯 MIUI 代碼的方式隻是一個猜想,時間原因未能付諸行動。看樣子產品哥哥的需求暫時不能完全實現瞭,不知道有沒有做過相關研究(或者知道內情)的小夥伴能不能提供一些參考思路,雖然是一個比較流氓的功能,但是代碼是無罪的嘿嘿,朝著一個需求目標,為此思考解決方法,並從各個方向去調研,我覺得本身是一件有意思也有提升的事情!歡迎有過相關研究的同學在評論區提出建議,做好需求奧裡給。

以上就是Android後臺啟動Activity的實現示例的詳細內容,更多關於Android後臺啟動Activity的資料請關註WalkonNet其它相關文章!

推薦閱讀:

    None Found