如何在android上检测应用程序退出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24406508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect application exit on android?
提问by Xzil0
How to execute some code on application exit? I want to delete temp data on application exit. By application exit i mean that app is not running minimized in background and its totally gone.
如何在应用程序退出时执行一些代码?我想在应用程序退出时删除临时数据。通过应用程序退出我的意思是应用程序没有在后台最小化运行并且它完全消失了。
I tried to make service that runs in separate process, the service is checking if app process is not running it should delete temp folder. With this approach temp folder is not always deleted because process is still running with the lowest priority.
我试图让服务在单独的进程中运行,该服务正在检查应用程序进程是否没有运行它应该删除临时文件夹。使用这种方法临时文件夹并不总是被删除,因为进程仍在以最低优先级运行。
I can't do this in OnDestroy().
我不能在 OnDestroy() 中做到这一点。
Service code:
服务代码:
[Service(Process = "com.lobomonitor")]
[IntentFilter(new string[] { "com.androidgui.ProcessMonitorService" })]
public class ProcessMonitorService : Service
{
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Thread processThread = new Thread(() =>
{
ActivityManager actManager = (ActivityManager) this.GetSystemService(ActivityService);
while (true)
{
Thread.Sleep(1000);
IList<ActivityManager.RunningAppProcessInfo> procList = actManager.RunningAppProcesses;
procList.Any(i => i.ProcessName.Equals("com.androidgui"));
if (!procList.Any(i => i.ProcessName.Equals("com.androidgui")))
{
FolderManager.Singleton.DeleteTempFolder();
break;
}
}
});
processThread.Start();
return StartCommandResult.RedeliverIntent;
}
public override IBinder OnBind(Intent intent)
{
return null;
}
}
回答by F1sher
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);
}
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:
例如,我曾经有一个正在运行服务的应用程序。当我杀死应用程序时 - 服务也消失了,但我希望它保持活力。通过使用 onTaskRemoved 我能够安排服务的重启:
@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);
}
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)
效果是 -> 我正在杀死我的应用程序 -> 服务看到正在删除任务并调用 onTaskRemoved -> 我计划在 1 秒内重新启动服务 -> 服务终止 -> 一秒后它唤醒 -> 结果:应用程序是被杀死,我执行了重新启动我的服务的代码,因此它仍在后台运行(仅在首选项中可见 - > 作为进程的应用程序)
http://developer.android.com/reference/android/app/Service.html
http://developer.android.com/reference/android/app/Service.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.
如果服务当前正在运行并且用户已删除来自服务应用程序的任务,则会调用此方法。
回答by Gilad Haimov
My experience shows that most apps do not really need an exit-callback of the sort you are describing.
我的经验表明,大多数应用程序并不真正需要您所描述的那种退出回调。
The Android way, which usually works fine, is of component-level (Activity, Service..) lifecycle management.
Android 的方式通常很好用,是组件级(Activity、Service..)生命周期管理。
Some apps allow for an 'Exit' functionality (via button, menu etc.) that, when activated by the user, allows the app to close all open components and basically go down.
一些应用程序允许“退出”功能(通过按钮、菜单等),当用户激活时,允许应用程序关闭所有打开的组件并基本上关闭。
But, if exit-callback is really what you want, the closest thing to it would probably be to create a dedicated service with no logic other than onDestroy() function and to activate it at app startup without ever closing it!
但是,如果退出回调真的是您想要的,那么最接近它的方法可能是创建一个除了 onDestroy() 函数之外没有其他逻辑的专用服务,并在应用程序启动时激活它而无需关闭它!
class ExitListenerService extends Service {
@Override
public void onDestroy() {
super.onDestroy();
// App exit logic here. Not deterministic!
}
}
The odds are such a service will probably be the last component to be reclaimed by the operating system. This should work in most cases, it worked fine for me. But it is not 100% guaranteed.
这种服务很有可能是操作系统回收的最后一个组件。这在大多数情况下应该有效,对我来说效果很好。但这不是 100% 保证的。
But.. if you must have a bullet proof solution the only other way I know is to create a peer application, call it watchdog, that will periodically wake up to check weather or not your main app is still running and, if not running, will activate the exit logic.
但是..如果你必须有一个防弹解决方案,我知道的唯一另一种方法是创建一个对等应用程序,称之为看门狗,它会定期醒来检查天气或你的主应用程序是否仍在运行,如果没有运行,将激活退出逻辑。
To run this last check you will need to call
要运行最后一次检查,您需要调用
List<RunningAppProcessInfo> runningApps = activityManager.getRunningAppProcesses();
and iterate over runningApps looking for your own.
并遍历 runningApps 寻找你自己的。