IntentService学习

204 阅读1分钟

IntentService 继承自 Service,是API里封装好的简单的处理异步请求的service类,在 IntentService 内有一个工作线程来处理耗时操作,这也是为什么intentService不用单独写线程。 当异步任务执行完后,IntentService 会自动停止,不用手动结束。

如果启动 IntentService 多次,那么所有的 耗时操作会以工作队列的方式在 IntentService 的 onHandleIntent 回调方法中被依次去执行,直至自动结束。

<service android:name=".server.SampleService"/>
public class SampleService extends IntentService {

    private boolean isRunning;
    private int num;

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public SampleService(String name) {
        super(name);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("service", "onCreate");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.i("service", "onHandleIntent");
        try {
            Thread.sleep(1000);
            Log.d("service", "ThreadName--------" + Thread.currentThread().getId());
            isRunning = true;
            num = 0;
            while (isRunning) {
                num++;
                if (num >= 10) {
                    isRunning = false;
                }
                Log.i("service", "num======================" + num);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("service", "onDestroy");
    }
}

执行结果

连续两次执行后,没有重复创建线程,而是以队列形式依次执行完