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)
相关推荐
csj501 小时前
安卓基础之《(6)—Activity组件(3)》
android
怀旧,1 小时前
【Linux系统编程】13. Ext系列⽂件系统
android·linux·缓存
Dabei1 小时前
Android 语音助手简单实现与语音助手“执行任务”交流
android·前端
jzlhll1232 小时前
android NDSDManager onResolveFailed errorCode=3的解决方案
android
芦半山2 小时前
四年之后,重新审视 MTE:从硬件架构到工程落地
android·安全
2501_916007472 小时前
iOS与Android符号还原服务统一重构实践总结
android·ios·小程序·重构·uni-app·iphone·webview
allk552 小时前
Android 屏幕适配全维深度解析
android·性能优化·界面适配
Android系统攻城狮2 小时前
Android ALSA驱动进阶之获取采样格式位宽snd_pcm_format_width:用法实例(九十八)
android·pcm·音频进阶·alsa驱动
莫比乌斯环3 小时前
【日常随笔】Android 跳离行为分析 - Instrumentation
android·架构·代码规范
aningxiaoxixi3 小时前
android 媒体之 MediaSession
android·媒体