【IntentService】IntentService的java.lang.InstantiationException错误

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里执行的,所以不需要要我们自己新开线程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值