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

如何检测应用被杀死的准确时刻?滑动清除后台时生命周期回调失效

Android检测应用被滑动清除的实现方案

当用户从最近任务列表向上滑动清除应用时,系统会直接终止应用进程,Activity的onPause/onStop/onDestroy等生命周期回调不会触发,此时可以通过以下方式准确检测这个时刻:

核心方案:利用Service的onTaskRemoved回调

系统在用户清除应用任务时,会向应用内运行的Service发送onTaskRemoved回调,这是目前最可靠的检测方式。

步骤1:注册后台Service

在AndroidManifest.xml中注册自定义Service:

<service
    android:name=".AppClearDetectionService"
    android:exported="false" />

步骤2:实现Service逻辑

重写onTaskRemoved方法,在这里执行API调用;同时为了避免Service被系统提前回收,Android 8.0+需要将Service设为前台服务:

class AppClearDetectionService : Service() {
    override fun onBind(intent: Intent?): IBinder? = null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // Android 8.0+ 必须启动前台服务,防止被系统立即回收
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                "app_clear_channel",
                "应用状态检测",
                NotificationManager.IMPORTANCE_LOW
            )
            getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
            
            val notification = Notification.Builder(this, "app_clear_channel")
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("后台运行中")
                .setContentText("检测应用清除状态")
                .build()
            
            startForeground(1001, notification)
        }
        return START_STICKY
    }

    override fun onTaskRemoved(rootIntent: Intent?) {
        super.onTaskRemoved(rootIntent)
        // 在这里调用你的目标API
        invokeCleanupApi()
        // 任务完成后停止服务
        stopSelf()
    }

    private fun invokeCleanupApi() {
        // 编写API请求逻辑,例如使用Retrofit或OkHttp发送请求
    }
}

步骤3:启动Service

在Application的onCreate或主Activity的onCreate中启动Service:

// 启动检测服务
startService(Intent(this, AppClearDetectionService::class.java))

注意事项

  • Android 12及以上版本需要动态申请POST_NOTIFICATIONS权限,否则无法启动前台服务
  • 如果API调用是耗时操作,建议使用WorkManager将任务加入后台队列,避免进程被终止导致请求中断

备选方案:后台延迟检测(有误差)

通过ProcessLifecycleOwner监听应用进入后台的事件,设置一个延迟任务(例如5秒),若用户未在延迟时间内回到应用,则执行API调用。这种方法适合对检测精度要求不高的场景,但可能会误触发(比如用户只是切换到其他应用而非清除)。

ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {
    private val handler = Handler(Looper.getMainLooper())
    private val cleanupRunnable = Runnable { invokeCleanupApi() }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        // 应用进入后台,启动延迟任务
        handler.postDelayed(cleanupRunnable, 5000)
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        // 用户回到应用,取消延迟任务
        handler.removeCallbacks(cleanupRunnable)
    }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:57:30