简体   繁体   English

如何检测应用是否已被服务杀死? 安卓

[英]How to detect if the app has been killed using a service? android

How do i detect if the app has been killed? 如何检测该应用是否已被杀死? i have found a solution which is call activity on onDestroy 我找到了一个解决方案,它是onDestroy上的呼叫活动

@Override
protected void onDestroy() {
    super.onDestroy();
    Intent intent = new Intent(this, ConnectionStablizer.class);
    startActivity(intent);
    // code here
}

it is working fine on galaxy note 3 (4.4.2) but not working on android emulator (android 4.2.2), galaxy y duos (2.3.6) and htc desire (4.0.2) 它在银河笔记3(4.4.2)上工作正常,但在android模拟器(android 4.2.2),银河y duos(2.3.6)和htc欲望(4.0.2)上无法正常工作

so i found another solution- 所以我找到了另一种解决方案-

run a background service which detects when app gets destroyed and launch the activity again like this one 运行后台服务,以检测应用何时被破坏,并像这样再次启动活动

i have the exact implementation but it doesn't do anything? 我有确切的实现,但是它什么都不做? where am i wrong? 我哪里错了? my code is the same as in the link 我的代码与链接中的相同

where am I wrong 我在哪里错

You are wrong trying to reopen your app once it's been destroyed . 销毁应用程序后重新尝试打开它是错误的 This is a hacky behavior... 这是骇客行为...

Nevertheless, you can achieve your goal by using alarm manager and set an alarm for every second or so, to check if your app is alive if it's not you can bring it back. 不过,您可以通过使用警报管理器来实现您的目标,并每隔一秒钟左右设置一个警报,以检查您的应用是否正常运行(如果不是),您可以将其恢复。

Also, pay attention: 另外,请注意:

Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. 从API 19(KITKAT)开始,警报传递是不准确的:操作系统将转移警报,以最大程度地减少唤醒和电池消耗。 There are new APIs to support applications which need strict delivery guarantees; 有一些新的API支持需要严格交付保证的应用程序。 see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). 请参见setWindow(int,long,long,PendingIntent)和setExact(int,long,PendingIntent)。 Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested. targetSdkVersion早于API 19的应用程序将继续看到以前的行为,在该行为中,所有警报均在请求时准确传递。

I strongly recommend to not use my solution, nor attempting to find one. 我强烈建议不要使用我的解决方案,也不要尝试寻找解决方案。

If the app is removed from recent apps by user then you can get a notification from OS by overriding onTaskRemoved method in your service and take respective action. 如果用户已将应用程序从最近的应用程序中删除,则您可以通过覆盖服务中的onTaskRemoved方法从OS收到通知,并采取相应的措施。 In general Android never kills any app unless otherwise in a low memory condition. 通常,除非内存不足,否则Android绝不会杀死任何应用程序。 In such case callbacks will be given to save the state of your application provided you handle all such callbacks. 在这种情况下,将提供回调以保存应用程序的状态,前提是您处理所有此类回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM