且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在android上检测应用程序退出?

更新时间:2023-01-25 22:02:22

我不知道这是否有帮助,但是如果你杀死你的应用程序,那么在后台运行的服务会调用方法:

I don't know if that help, but if you kill your app, then service that runs in background calls method:

@Override
public void onTaskRemoved(Intent rootIntent){

    super.onTaskRemoved(rootIntent);
}

例如,我曾经有一个正在运行服务的应用程序.当我杀死应用程序时 - 服务也消失了,但我希望它保持活力.通过使用 onTaskRemoved 我能够安排服务的重启:

For example I had once app that was running service. When I killed app - service died too, but I wanted it to stay alive. By using onTaskRemoved I was able to schedule restart of service:

@Override
public void onTaskRemoved(Intent rootIntent){
    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(
            AlarmManager.ELAPSED_REALTIME,
            SystemClock.elapsedRealtime() + 1000,
            restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
}

效果是 -> 我正在杀死我的应用程序 -> 服务看到正在删除任务并调用 onTaskRemoved -> 我计划在 1 秒内重新启动服务 -> 服务终止 -> 一秒后它唤醒 -> 结果:应用程序被杀死,我执行了重新启动我的服务的代码,因此它仍在后台运行(仅在首选项中可见 -> 作为进程的应用程序)

Effect was -> I am killing my app -> Service see that tasks are being removed and calls onTaskRemoved -> I am scheduling restart of service in 1 sec -> Service dies -> After one sec it wakes up -> RESULT: App is killed, i executed code that restarted my service so it is still running in background (visible only in preferences -> applications as process)

http://developer.android.com/reference/android/app/服务.html

void     onTaskRemoved(Intent rootIntent)

如果服务当前正在运行并且用户已删除来自服务应用程序的任务,则调用此方法.

This is called if the service is currently running and the user has removed a task that comes from the service's application.