java Android:当我从最近的应用程序按钮关闭应用程序时,不会调用 OnDestroy

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41744933/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:07:44  来源:igfitidea点击:

Android: OnDestroy isn't called when I close the app from the recent apps button

javaandroidondestroyclose-application

提问by Curio

When we press this button

当我们按下这个按钮

We see the apps which we didn't close, like this

我们看到我们没有关闭的应用程序,像这样

But when we want to close an app from this screen (below image), the method onDestroy() isn't called, however the app is closed. I need to call onDestroy() when the app is closed in this way. How can I do this?

但是,当我们想从此屏幕(下图)关闭应用程序时,不会调用 onDestroy() 方法,但是应用程序已关闭。当应用程序以这种方式关闭时,我需要调用 onDestroy()。我怎样才能做到这一点?

回答by Charlie

As specified in the Android documentation, it is not guaranteed that onDestroy()will be called when exiting your application.

如 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

https://developer.android.com/reference/android/app/Activity.html#onDestroy%28%29

Instead, you can create a service which will be notified when the Task your activities are running inside is destroyed.

相反,您可以创建一个服务,当您的活动在其中运行的任务被销毁时,该服务将收到通知。

Create the service class:

创建服务类:

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();
    }
}

Declare / register your service in the manifest (within the application tag, but outside any activity tags):

在清单中声明/注册您的服务(在应用程序标签内,但在任何活动标签外):

<service android:name=".services.ClosingService"
             android:stopWithTask="false"/>

Specifying stopWithTask="false"will cause the onTaskRemoved()method to be triggered in your service when the task is removed from the Process.

当任务从进程中删除时,指定stopWithTask="false"将导致onTaskRemoved()在您的服务中触发该方法。

Here you can run your closing application logic, before calling stopSelf()to destroy the Service.

在调用stopSelf()销毁服务之前,您可以在此处运行关闭应用程序逻辑。

回答by Neeraj Sewani

More promising approach than using a bound servicewould be using activity lifecycle callbacksin the Application. Though the approach shown in the accepted answer would work but the service would be running in the background until the activity is terminated which is expensive. Instead, I would suggest the use of your implementation of Application.

比使用绑定服务更有前景的方法是在Application 中使用活动生命周期回调。尽管已接受的答案中显示的方法可行,但该服务将在后台运行,直到活动终止,这很昂贵。相反,我建议使用您的Application实现。

1) Make a class extending Application, then use it by providing its name in the name attribute of Application tag in Manifest file

1)创建一个扩展Application的类,然后通过在Manifest文件的Application标签的name属性中提供它的名字来使用它

class MusicPlayerApplication: Application() {
    private val TAG = MusicPlayerApplication::class.java.simpleName

    override fun onCreate() {
        super.onCreate()

        registerActivityLifecycleCallbacks(object: ActivityLifecycleCallbacks {
            override fun onActivityPaused(activity: Activity?) {

            }

            override fun onActivityResumed(activity: Activity?) {
            }

            override fun onActivityStarted(activity: Activity?) {
            }

            override fun onActivityDestroyed(activity: Activity?) {
                Log.d(TAG, "onActivityDestroyed: ")
                val activityName = activity!!.localClassName
            }

            override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {
            }

            override fun onActivityStopped(activity: Activity?) {
            }

            override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
            }
        })
    }
}

AndroidManifest.xml

AndroidManifest.xml

<application
            android:name=".MusicPlayerApplication"
....

I have tested this approach using logcat, my onDestoryis not getting called but onActivityDestroyedin the callback is getting called every time I kill the activity from RAM but this docsays that onActivityDestroyedwould be called when onDestoryof an activity is called but that doesn't seem to happen. However, I find this approach better than using services.

我已经使用 logcat 测试了这种方法,我onDestory没有被调用,但是onActivityDestroyed每次我从 RAM 中终止活动时都会调用回调,但是这个文档onActivityDestroyed在调用onDestory活动时会调用它,但这似乎没有发生. 但是,我发现这种方法比使用services更好。

回答by Ekalips

You should read some info about Activity lifecycle. There is one thing about onDestroy method, it doesn't get called all time. You mustn't rely on it.

您应该阅读一些有关 Activity 生命周期的信息。onDestroy 方法有一件事,它不会一直被调用。你不能依赖它。

Specify please what are you trying to achive and I'll try to offer better solution.

请指定您想要达到的目标,我会尽力提供更好的解决方案。

Suggestion

建议

So, if I understood you right, I can suggest one thing. Start a Servicethat will fire LocalBroadcastevery N seconds (it's not really heavy to system). Register and BroadcastReceiverfor this broadcast in Activities. This way you'll get trueor falsedepending on if there is any BroadcastReceiverthat can catch your LocalBroadcast. And if no receivers than check for some SharedPreferencesvalue that indicates if Buttonwas pressed.

所以,如果我理解正确,我可以建议一件事。启动一个每 N 秒Service触发LocalBroadcast一次(它对系统来说并不是很重)。注册并BroadcastReceiver对该广播Activities。通过这种方式,您将获得truefalse取决于是否有任何BroadcastReceiver可以捕获您的LocalBroadcast. 如果没有接收器,则检查一些SharedPreferences指示是否Button被按下的值。

回答by user6765242

Your problem is that onDestroy is only called in aService. In an Activitythe called method is onPause()Put simply in your Activity the field:

您的问题是 onDestroy 仅在Service. 在Activity被调用的方法中,onPause()只需将字段放在您的 Activity 中:

@Override
public void onPause()
{
//Put your Code here
}