应用程序关闭时调用方法

时间:2021-06-12 13:37:27

标签: java android android-studio

我知道这个问题被问了很多次,但我想弄清楚

我应该将 onDestroy() 放在哪个活动中?假设我在 MainActivity A 中,然后转到活动 B。但是我在活动 B 上关闭了应用程序。onDestroy() A 中的 MainActivity 方法是否被调用?还是应该为应用程序中的每个 Activity 放置一个 onDestroy() 方法?或者有其他方法可以解决这个问题吗?

我曾尝试阅读文档和阅读其他答案,但它们对我没有帮助。

1 个答案:

答案 0 :(得分:0)

多种方法,这里我提到了我在开发载体时发现的最可靠的方法。您需要创建一个可以保留 eye whether application got closed or not 的服务,所以这里我提到了代码!

1.创建服务,正如你在下面看到的,有一个名为的新类 MyService,这需要扩展到服务< /strong>。

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

public class MyService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.d(getClass().getName(), "App just got removed from Recents!");
    }


}

2.添加这个entry to Manifest.xml如下...

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.TestApplication">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService" />
    </application>

</manifest>

3.这只是一个将在后台运行的服务,但我们需要在应用程序启动后启动它,因此在您的 launcher activity start就像下面一样。

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Intent stickyService = new Intent(this, MyService.class);
        startService(stickyService);

    }
}

4.服务将启动,每当用户从最近刷出应用程序时,函数onTaskRemoved自动调用 strong>,在这个函数中你可以把你需要的工作或代码放到应用端执行!