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)
相关推荐
Digitally6 分钟前
如何将文件从 iPhone 传输到 Android(新指南)
android·ios·iphone
whysqwhw1 小时前
OkHttp深度架构缺陷分析与演进规划
android
用户7093722538511 小时前
Android14 SystemUI NotificationShadeWindowView 加载显示过程
android
木叶丸2 小时前
跨平台方案该如何选择?
android·前端·ios
顾林海2 小时前
Android ClassLoader加载机制详解
android·面试·源码
用户2018792831672 小时前
🎨 童话:Android画布王国的奇妙冒险
android
whysqwhw3 小时前
OkHttp框架的全面深入架构分析
android
你过来啊你3 小时前
Android App冷启动流程详解
android
泓博4 小时前
KMP(Kotlin Multiplatform)改造(Android/iOS)老项目
android·ios·kotlin
移动开发者1号4 小时前
使用Baseline Profile提升Android应用启动速度的终极指南
android·kotlin