http://www.cnblogs.com/helloandroid/articles/2208154.html
关于继承IntentService,构造函数需要注意一个地方,Eclipse默认生成的构造函数是
public MyIntentService(String name) { super(name); }
而官方文档的示例中是没有参数的构造方法,使用Eclipse这个默认构造函数的话会报一个运行时错误: java.lang.InstantiationException,在Google Groups里找到了解决办法,继承IntentService的类必须有一个public的无参的构造函数,将上面Eclipse自动生成的构造函数改为下面这样的就可以了:
public MyIntentService() { super("someName"); }
为什么要这样改,看IntentService构造函数的源码:
public IntentService(String name) { super(); mName = name; }
SDK文档里说构造函数里面的服务名字只在调试时有用,可以随便写一个名字。
另一个需要特别指出的时,在onHandleIntent里不需要自己处理线程,或者新启线程,IntentService默认会为队列中的任务启动后台线程,源码中的实现是这样的:
private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { onHandleIntent((Intent)msg.obj); stopSelf(msg.arg1); } } @Override public void onCreate() { super.onCreate(); HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); }
看源码可以得知onHanldeIntent()是在新的后台线程HandlerThread里执行的,所以不需要要我们自己新开线程。