IntentService的使用

来源:互联网 发布:2017年淘宝客好做吗 编辑:程序博客网 时间:2024/04/29 19:02

使用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