最佳答案
如 Android 文档中所述,不保证退出应用程序时会调用 onDestroy()
。
"There are situations where the system will simply kill the activity's hosting process without calling this method"
https://developer.android.com/reference/android/app/Activity.html#onDestroy%28%29
相反,您可以创建一个服务,当您的 Activity 在其中运行的任务被销毁时,该服务将收到通知。
创建服务类:
public class ClosingService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
// Handle application closing
fireClosingNotification();
// Destroy the service
stopSelf();
}
}
在 list 中声明/注册您的服务(在应用程序标签内,但在任何 Activity 标签外):
<service android:name=".services.ClosingService"
android:stopWithTask="false"/>
指定 stopWithTask="false"
将导致当从 Process 中删除任务时在您的服务中触发 onTaskRemoved()
方法。
在调用 stopSelf()
销毁服务之前,您可以在此处运行关闭应用程序逻辑。
关于java - Android:当我从最近的应用程序按钮关闭应用程序时,不会调用 OnDestroy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41744933/