简体   繁体   English

Android:从最近使用的应用程序按钮关闭应用程序时未调用OnDestroy

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

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. 但是,当我们想从该屏幕关闭一个应用程序(下图)时,不会调用onDestroy()方法,但是该应用程序已关闭。 I need to call onDestroy() when the app is closed in this way. 以这种方式关闭应用程序时,我需要调用onDestroy()。 How can I do this? 我怎样才能做到这一点?

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): 在清单中声明/注册您的服务(在application标签内,但在任何活动标签之外):

<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()销毁服务之前运行关闭的应用程序逻辑。

You should read some info about Activity lifecycle. 您应该阅读有关活动生命周期的一些信息。 There is one thing about onDestroy method, it doesn't get called all time. 关于onDestroy方法,有一点是,它不会一直被调用。 You mustn't rely on it. 您一定不要依赖它。

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 Service that will fire LocalBroadcast every N seconds (it's not really heavy to system). 启动一个Service ,该Service每N秒LocalBroadcast一次LocalBroadcast (这对系统而言并不算太重)。 Register and BroadcastReceiver for this broadcast in Activities . Activities注册并BroadcastReceiver此广播的接收器。 This way you'll get true or false depending on if there is any BroadcastReceiver that can catch your LocalBroadcast . 这样,根据是否存在可以捕获LocalBroadcast BroadcastReceiver ,您将得出truefalseLocalBroadcast And if no receivers than check for some SharedPreferences value that indicates if Button was pressed. 如果没有接收者,则检查一些SharedPreferences值,该值指示是否已按下Button

More promising approach than using a bound service would be using activity lifecycle callbacks in the Application . 与使用绑定服务相比,更有希望的方法是在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的实现。

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的类,然后通过在清单文件中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 onDestory is not getting called but onActivityDestroyed in the callback is getting called every time I kill the activity from RAM but this doc says that onActivityDestroyed would be called when onDestory of an activity is called but that doesn't seem to happen. 我已经使用logcat测试了这种方法,每次我从RAM中杀死活动时,不会调用我的onDestory但是在回调中会调用onActivityDestroyed ,但是此文档说,在调用活动的onDestory时将调用onActivityDestroyed ,但这并没有。似乎没有发生。 However, I find this approach better than using services . 但是,我发现这种方法比使用services更好。

Your problem is that onDestroy is only called in a Service . 您的问题是onDestroy仅在Service调用。 In an Activity the called method is onPause() Put simply in your Activity the field: 在一个Activity ,被调用的方法是onPause()只需在您的Activity中输入以下字段:

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

暂无
暂无

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

相关问题 从Android中的最新应用中刷出应用后,服务停止 - Service stopped when app is swiped out from recent apps in Android 当应用程序从android中的最新应用程序列表中删除时,服务停止 - Service stopped when the app removes from recent apps list in android Android - 从最近的应用程序中滑动应用程序时停止服务 - Android - Service stops when swiping app from recent apps 我希望我的应用程序在(线程或作为服务)中运行,即使 onDestroy() 被调用(用户从后台删除) - I want my app to be running in a (Thread or as a service) even when onDestroy() is called (user removed from background) 在一加3t移动设备上杀死应用程序或从最近使用的应用程序中刷出应用程序时,Android FCM推送通知不起作用 - Android FCM Push Notification Not Working When App is being Killed or Swipe Out from Recent Apps on One plus 3t Mobile 在android生命周期中,当从最近的应用列表中滑动应用时,是否会调用任何独特的方法? - In android lifecycle, is there any unique method gets called when app is swiped from recent app list? 从最近的应用程序中删除应用程序后,IntentService停止工作 - IntentService stops working when app is removed from recent apps 即使应用程序被杀死,我怎样才能让我的应用程序运行? 从最近的应用程序中删除时在某种意义上被杀死 - How can i make my app run even when app is killed? killed in the sense when it is removed from recent apps 为什么当我关闭我的应用程序时,我的 android 应用程序活动会重新打开 - Why does my android apps activitie reopen when I close my app 按下最近的应用程序按钮时清除EditText - Clearing an EditText when the recent apps button is pressed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM