簡體   English   中英

應用程序關閉時調用方法

[英]Call method when Application Closes

我知道這被問了很多次,但我想澄清一下

我應該將onDestroy()放在哪個活動中? 假設我在MainActivity A 中,我移至活動 B。但隨后我在活動 B 上關閉應用程序。 MainActivity A 中的onDestroy()方法是否被調用? 或者我應該為應用程序中的每個活動放置一個onDestroy()方法? 或者有沒有其他方法可以解決這個問題?

我曾嘗試閱讀文檔並閱讀其他答案,但它們並不能清楚地幫助我。

多種方法可以做到這一點,這里我提到了我在開發載體中找到的最可靠的方法 你需要創建一個服務eye whether application got closed or not ,所以我在這里提到了代碼!

1.創建 Service ,如下圖所示有一個新的 class 命名為MyService ,這需要擴展為 Service

 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中啟動它,如下所示。

 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.服務將啟動,每當用戶從最近刷出應用程序時,將自動調用function onTaskRemoved ,在此function中,您可以將所需的工作或代碼放在應用程序端執行!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM