【发布时间】:2017-11-05 01:26:10
【问题描述】:
谁能帮助我了解如何正确使用 Android Service 或 IntentService。文档在这里似乎自相矛盾:
Caution: A service runs in the same process as the application in which it is
declared and in the main thread of that application by default. If your service
performs intensive or blocking operations while the user interacts with an
activity from the same application, the service slows down activity performance.
To avoid impacting application performance, start a new thread inside the service.
这里
public class HelloIntentService extends IntentService {
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public HelloIntentService() {
super("HelloIntentService");
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
}
}
鉴于 Service 或 ServiceIntent 的全部目的是在后台运行长时间运行的作业而不影响 UI,为什么示例代码会完全按照 Caution 指示您不应该执行的操作 - 我假设调用 Thread .sleep() 会导致主线程阻塞。
我的以下理解是否正确:
- 服务本身仍然在主应用程序线程上运行,但没有 UI 组件(Activity),并且即使用户不使用应用程序也会继续运行,不像 Activity 不会
- 任何长时间运行的后台工作仍必须创建单独的线程以避免阻塞主应用程序线程
- AsyncTask 与一个 Activity 相关联,如果应用程序不再是活动应用程序(即,如果用户切换到另一个应用程序),该 Activity 可能会停止运行,这就是如果任务需要继续运行,人们会使用 Service 或 ServiceIntent 的原因。
- IntentService 将在与主线程不同的线程上运行任务,因此无需担心因长任务或调用 Thread.sleep() 时阻塞主线程。
我对 Android Service 或 ServiceIntents 的描述有什么误解吗?
【问题讨论】: