简体   繁体   English

Android:当应用关闭时执行某些操作

[英]Android : When app close do something

I want when user close my app it update SQLite data then close app. 我想在用户关闭我的应用程序时先更新SQLite数据,然后关闭应用程序。 I used onPause() , onStop() and onDestroy() method in different time on MainActivity . 我在MainActivity的不同时间使用了onPause()onStop()onDestroy()方法。 All methods work when app close. 应用关闭时,所有方法均有效。

But The problem is , onStop() , onPause() and onDestroy() are called when I change activity. 但是问题是当我更改活动时,会调用onStop()onPause()onDestroy() But I don't want to do it when I change activity, only when I close my app. 但是我不想在更改活动时这样做,仅当我关闭应用程序时才这样做。

How I can do that? 我该怎么做?

Thank you for your response. 感谢您的答复。

The app will be closed 该应用程序将关闭

1.When user pressed back button in Main activity 1.当用户在主要活动中按下返回按钮时

2.When you call finish() method programmatically 2.当您以编程方式调用finish()方法时

Hence, You can use onBackPressed() method , 因此,您可以使用onBackPressed()方法,

 @Override
    public void onBackPressed() {
        //do your action
        finish();

    }

If you are finishing main activity programmatically, Then do your task before calling finish() 如果您正在以编程方式完成主要活动,则在调用finish()之前执行任务

Edit 编辑

As you mentioned, 就像你提到的

3.when the app is closed from recent activities, 3.当应用程序因近期活动而关闭时,

Activity will be closed instantly. 活动将立即关闭。 Activity Life cycle is not considered. 不考虑活动生命周期。 Even onDestroy() method will not be invoked. 即使onDestroy()方法也不会被调用。 Hence You can use service to detect that. 因此,您可以使用服务进行检测

There is a method called onTaskRemoved() which can be used in your service 有一个名为onTaskRemoved()的方法可以在您的服务中使用

 @Override
    public void onTaskRemoved(Intent rootIntent) {
        //do your task;
    }

You can get more info from this source 您可以从此来源获取更多信息

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

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