我指的是 android design considerations: AsyncTask vs Service (IntentService?)
根据讨论,AsyncTask 不适合,因为它与您的 Activity 紧密“绑定(bind)”
所以,我启动了一个 Thread
(我假设 AsyncTask 和 Thread 属于同一类别),其中有一个无限运行循环并进行了以下测试。
- 我通过按住返回软键退出我的应用程序,直到我看到主屏幕。线程仍在运行。
- 我通过转到管理应用程序 -> 应用程序 -> 强制停止 来终止我的应用程序。线程已停止。
所以,我希望在我从 Thread
改变之后至 Service
, 我的 Service
即使在我退出 或终止 我的应用程序后,它仍会保持 Activity 状态。
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
是否应该继续运行,即使我终止了我的应用程序?
最佳答案
没有。当您终止应用程序时,服务将停止运行。当您终止应用程序时,它的所有组件( Activity 、服务等)都会被终止。
总的来说,线程和服务的行为是相似的。但是,如果您从 Activity 启动 Thread 然后关闭 Activity(即:退出您的应用程序),最终 Android 会注意到您的进程中没有 Activity 组件(因为 Android 不会将您的 Thread 识别为 Activity 组件)它只会杀死你的进程,从而杀死线程。
但是,如果您有一个正在运行的服务,那么 Android 会注意到您有一个正在运行的服务,而不会那么轻易地终止它。但是,如果它不是“正在使用”,Android 仍然有可能终止您的服务进程。
关于android - IntentService 将在我停止我的应用程序后被杀死,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11241302/