Android 销毁应用程序时执行自定义代码

Android 销毁应用程序时执行自定义代码,android,android-activity,android-service,Android,Android Activity,Android Service,我有一个磁盘缓存,我需要在应用程序关闭时关闭它。在哪里做这件事最好 -重写activities onDestroy方法并检查其是否为任务根: @Override protected void onDestroy () { if (this.isTaskRoot()) { //I only want to close it if this is the last activity of the app CloseCac

我有一个磁盘缓存,我需要在应用程序关闭时关闭它。在哪里做这件事最好

-重写activities onDestroy方法并检查其是否为任务根:

    @Override
    protected void onDestroy () {
        if (this.isTaskRoot()) {
            //I only want to close it if this is the last activity of the app
            CloseCache();
        }
        super.onDestroy();
    }
根据文档,当系统刚刚关闭应用程序时,可能不会调用Activity.onDestroy(),因此在这种情况下,这将使缓存保持打开状态

-使用在同一进程中运行的服务并从其onDestroy回调中关闭缓存?进程销毁时,系统是否总是调用Service.ondestory()


其他不知道的方式?

您可以考虑在OnStor()方法中执行这个步骤,该方法是在用户不再可见时调用的。您将在以后接收OnRealSead()、OnDebug(或),这取决于稍后的用户活动。“然后,在OnRealStEX()方法中,如果需要,可以回收缓存。