我目前正在开发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
我也试过,但我忘了在帖子中提到它。我现在已经在底部完成了,请参阅**编辑**部分。 –