You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android 10中如何实现应用进程终止后后台服务仍运行及启停控制

需求与现有代码实现

功能需求

  • 开发一个后台常驻Service,关闭宿主应用后仍能保持运行
  • 从启动Activity中启动该Service
  • 支持在启动Activity中关闭此Service

LockerService实现代码(Kotlin)

class LockerService: Service() {
    private val screenUnlockedBroadcastReceiver = ScreenUnlockedBroadcastReceiver()
    private val taskPausedBroadcastReceiver = TaskPausedBroadcastReceiver()

    override fun onBind(intent: Intent?): IBinder? {
        return null;
    }

    override fun onCreate() {
        super.onCreate()
        Log.d("LockerService", "Created")
        registerReceiver(screenUnlockedBroadcastReceiver, IntentFilter(Intent.ACTION_SCREEN_ON))
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(taskPausedBroadcastReceiver,
                IntentFilter(TaskPausedBroadcastReceiver.TASK_PAUSED),
                RECEIVER_NOT_EXPORTED)
        } else {
            registerReceiver(taskPausedBroadcastReceiver,
                IntentFilter(TaskPausedBroadcastReceiver.TASK_PAUSED))
        }
    }

    override fun onDestroy() {
        unregisterReceiver(screenUnlockedBroadcastReceiver)
        unregisterReceiver(taskPausedBroadcastReceiver)
        super.onDestroy()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY
    }
}

Activity中启动Service的代码

val serviceIntent = Intent(this, LockerService::class.java)
serviceIntent.addFlags(Service.START_STICKY)
startService(serviceIntent)

内容的提问来源于stack exchange,提问作者Diphenylamyn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 15:43:15