【发布时间】:2012-06-28 09:04:23
【问题描述】:
我指的是android design considerations: AsyncTask vs Service (IntentService?)
根据讨论,AsyncTask 不适合,因为它与您的 Activity 紧密“绑定”
所以,我启动了一个Thread(我假设 AsyncTask 和 Thread 属于同一类别),其中有一个无限运行循环并进行了以下测试。
- 我退出我的应用程序,按住返回软键,直到看到主屏幕。线程仍在运行。
- 我杀死我的应用程序,方法是转到管理应用程序 -> 应用程序 -> 强制停止。线程已停止。
所以,我希望在我从 Thread 更改为 Service 之后,即使在我退出或杀死我的应用程序之后,我的 Service 仍将保持活动状态。
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>
但是,我的发现是,
- 我退出我的应用程序,按住返回软键,直到看到主屏幕。服务仍在运行。
- 我杀死我的应用程序,方法是转到管理应用程序 -> 应用程序 -> 强制停止。服务已停止。
看来Service 和Thread 的行为是一样的。那么,为什么我应该使用Service 而不是Thread?有什么我错过的吗?我以为我的Service 会继续运行,即使我杀死了我的应用程序?
【问题讨论】:
标签: android