我目前正在開發Android應用程序。其中一個要求是大量記錄有關應用程序的使用方式。更具體地說,應該記錄關於何時用戶關閉該應用。此日誌記錄由服務器交互組成。對於特定要求我偶然發現:Android服務在應用關閉後執行AsyncTask
Detect Application Exit(1)和Detect application Exit (2)
這兩個問題有一個公認的答案依靠Service#onTaskRemoved(Intent)
。
然而,在我的情況下,這種解決方案似乎並不奏效,即以這種方法啓動的AsyncTask
只有偶爾會執行。更具體地說,onPreExecute
執行總是但doInBackground
不是。我在安裝了Android 6(Marshmallow)的Nexus 5上測試了它。
public class SomeService extends Service {
@Override
public IBinder onBind(Intent aIntent) {
return null;
}
@Override
public void onTaskRemoved(Intent aRootIntent) {
new DoSomethingTask().executeOnExecutor(Asyntask.THREAD_POOL_EXECUTOR);
}
private static final class DoSomethingTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
Log.e(DoSomethingTask.class.getName(), "This is executed always");
}
@Override
protected Void doInBackground(Void... aParams) {
Log.e(DoSomethingTask.class.getName(), "This appears to be executed only sometimes... ");
// here an actual call to a Rest API should be made to inform the server that the user has closed the application.
}
@Override
protected void onCancelled(Void result) {
super.onCancelled(result);
Log.e(DoSomethingTask.class.getName(), "Never invoked");
}
@Override
protected void onCancelled() {
super.onCancelled();
Log.e(DoSomethingTask.class.getName(), "Never invoked");
}
}
}
這裏是一切我試圖在除了上述代碼示例的概述:
- 我已經
onStartCommand
選項(START_STICKY,START_NOT_STICKY等)沒有成功嘗試過各種。 - 我也嘗試在
onTaskRemoved
方法中重新啓動服務,然後在onStartCommand中執行AsyncTask
。 - 在
onTaskRemoved
方法(它在onHandleIntent
方法中啓動AsyncTask
)中啓動IntentService
也解決了這個問題。 - 使用
BroadcastReceiver
結合本地廣播(LocalBroadcastManager#sendBroadcast
)也不起作用(我仔細檢查過廣播接收器是否被有效註冊爲發送廣播的接收器)。
編輯:
我也採取了看看在Application
類的回調: - onTerminate
:此方法只調用在仿真環境中,因此沒用 - onTrimMemory(int)
:這種方法可以用於檢測應用程序何時進入後臺,但應用程序退出時沒有明確的情況。
我可以保留一個活動堆棧(將在Activity#onPause()
等更新)。但是這需要在每個單獨的Activity
中進行相當多的工作,而不是上述Service
方法,其只涉及在單個地方的干擾。
您可以通過擴展Application類並重寫onTerminate()onDestroy()onLowMemory()和類似的東西來做到這一點。 – napkinsterror
我也試過,但我忘了在帖子中提到它。我現在已經在底部完成了,請參閱**編輯**部分。 –