IntentService
IntentService是Service的一个子类,在收到开始请求时会立马开启一个工作线程。如果你的Service不需要同时处理多请求,那么你可以选择使用它。你需要实现onHandleIntent()方法,当它收到开始请求时,它就会在后台开始工作。
IntentService好处
1.创建一个默认的工作线程处理所有的Intent传递给onStartCommon()方法,与应用的主线程分离。
2.创建一个工作队列,每次传递一个Intent给你的onHandleIntent()实现方法。这样当你有多个运行的线程时不会混乱。
3.当所有的请求处理完时它会自己停止,不需要调用stopSelf();
4.提供默认的onBind()实现方法,返回null;
5.提供默认的onStartCommon方法,它会发送Intent到工作队列,然后再将Intent传递给你实现的onHandlerIntent方法。
简单例子
public
class HelloIntentService
extends IntentService
{
public HelloIntentService()
{
super("HelloIntentService");
}
@Override
protected voidonHandleIntent(Intent intent)
{
// Normally we would do some work here, likedownload a file.
// For our sample, we just sleep for 5 seconds.
long endTime
= System.currentTimeMillis()
+ 5*1000;
while (System.currentTimeMillis()
< endTime)
{
synchronized
(this)
{
try
{
wait(endTime
- System.currentTimeMillis());
} catch
(Exception e)
{
}
}
}
}
}