我指的是android 设计注意事项:AsyncTask 与 Service(IntentService?) https://stackoverflow.com/questions/3817272/android-design-considerations-asynctask-vs-service-intentservice
根据讨论,AsyncTask 不适合,因为它与您的 Activity 紧密“绑定”
所以,我启动了一个Thread
(我假设 AsyncTask 和 Thread 属于同一类别),其中有一个无限运行循环并进行了以下测试。
- I quit我的应用程序,按住后退软键,直到看到主屏幕。线程仍在运行。
- I kill我的申请,前往管理应用程序 -> 应用程序 -> 强制停止。线程已停止。
所以,我期望在我改变之后Thread
to Service
, my Service
即使在我之后也会继续活着quit or kill我的应用程序。
Intent intent = new Intent(this, SyncWithCloudService.class);
startService(intent);
public class SyncWithCloudService extends IntentService {
public SyncWithCloudService() {
super("SyncWithCloudService");
}
@Override
protected void onHandleIntent(Intent intent) {
int i = 0;
while (true) {
Log.i("CHEOK", "Service i is " + (i++));
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Log.i("CHEOK", "", ex);
}
}
}
}
// Doesn't matter whether I use "android:process" or not.
<service
android:name="com.xxx.xml.SyncWithCloudService"
android:process=".my_process" >
</service>
然而,我的发现是,
- I quit我的应用程序,按住后退软键,直到看到主屏幕。服务仍在运行。
- I kill我的申请,前往管理应用程序 -> 应用程序 -> 强制停止。服务已停止。
看来,的行为Service
and Thread
是相同的。那么,为什么我应该使用Service
代替Thread
?我有什么遗漏的吗?我以为我的Service
即使我终止了我的应用程序,仍想继续运行吗?