IntentService的使用

39 篇文章 0 订阅

使用Service需注意

Service 是在主线程中执行的,所以不能再Service中直接执行网络加载等耗时操作,应该开启子线程进行加载。

使用IntentService

IntentService会自动开起一个工作线程,在此工作线程中执行耗时操作,不会引发ANR异常.
IntentService必须重写onHandleIntent(),并在此方法中执行耗时操作.
IntentService自动重写了onBind()和onStartCommand()方法
IntentService 使用队列来管理请求的Intent,新来的Intent将被加入队列中等待执行,每次IntentService会开启一个新的work线程执行请求 ,该线程只保证同一时刻只处理一个Intent。

继承自IntentService类

public class MyService extends IntentService {

    public MyService(String name) {
        super(name);
    }

    public MyService() {
        super("");
    }

    // 此方法会在工作线程中执行,不会阻塞子线程
    @Override
    protected void onHandleIntent(Intent arg0) {
        try {
            synchronized (this) { //  wait()让当前线程等待10秒
                this.wait(10 * 1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.v("LOG", "finished!!!");
    }

}

执行此IntentService 时,不会产生异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值