Android前台服务如何在后台启动activity?

本来最近在开发一个app保活另外一个app的功能,方案介绍如下:

  1. 应用A 启动一个前台服务保活自己
  2. 应用A 用grpc连接应用B(服务端)是否存活
  3. 如果发现B不存活,则在服务中拉起B

这次没有做好调研,直接开始了开发工作,等grpc都调试开发完了,才发现 后台服务中启动应用B有时候能成功,有时候不能正常,不能成功报错如下:

Background activity start [callingPackage。。。。

问题原因就是 android10增加了后台启动activity的限制,当应用A在前台时,拉起应用B是可以的,担当应用A回到后台,即使有一个前台服务,也不能直接拉起应用B。

在网上查了很多资料,参考:Android 后台启动Activity适配

解决方案

我采用的是添加SYSTEM_ALERT_WINDOW权限,并申请该权限。

只需要申请权限,并不需要真的弹出一个悬浮窗出来。

  1. 在AndroidManifest.xml中添加
XML 复制代码
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
  1. 申请权限
Kotlin 复制代码
private val requestAlertWindowsPermission = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        Log.i(TAG, "result code:${result.resultCode}")
        if (result.resultCode == Activity.RESULT_OK) {
            Log.i(TAG, "data_return:${result.data?.getStringExtra("data_return")}")
        }
        if (!Settings.canDrawOverlays(this)) {
            Log.i(TAG, "request alert windows Permission failed")
        } else {
            Log.i(TAG, "request alert windows Permission success")
        }
    }

private fun requestAlertWindowPermission() {
        if (!Settings.canDrawOverlays(this)) {
            Log.i(TAG, "requestAlertWinPerm: request alert windows Permission")
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
            intent.setData(Uri.parse("package:$packageName"))
            requestAlertWindowsPermission.launch(intent)
        } else {
            Log.i(TAG, "requestAlertWindowPermission already has Permission.")
        }
    }
  1. 服务中启动activity。别忘了添加 FLAG_ACTIVITY_NEW_TASK
Kotlin 复制代码
val packageName = "pkg"
val launchIntent = packageManager.getLaunchIntentForPackage(packageName)
if (launchIntent == null) {
    Log.e(TAG, "目标应用未安装")
    throw RuntimeException("目标应用未安装")
}
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(launchIntent)
相关推荐
程序员陆业聪1 小时前
绕过Frida/Xposed的最后防线:SVC直接系统调用与Native反Hook实战
android
程序员陆业聪2 小时前
WebView与原生JS交互:JSBridge生产级实现与安全防护
android
我命由我123455 小时前
Android 开发问题:MlKitException: An internal error occurred during initialization.
android·java·java-ee·android jetpack·android-studio·androidx·android runtime
Meteors.5 小时前
Android自定义 View 三核心方法详解
android
2501_916007475 小时前
前端开发常用软件与工具全面指南
android·ios·小程序·https·uni-app·iphone·webview
赏金术士6 小时前
Android Tinker 热修复集成与使用指南 1.9.15.2
android·热修复·tinker
2603_954138397 小时前
安卓误删文件先别慌!5个实用小技巧指南教你补救
android·智能手机
波诺波8 小时前
5-SOFA可变形的3D物体 5-elasticity.scn
android
2501_9159090610 小时前
iOS应用性能优化:十大策略提升用户体验与开发效率
android·ios·小程序·https·uni-app·iphone·webview
sun00770010 小时前
打通android全链路,网卡驱动, 内核 , 到上层hal, framework
android