IntentService

package lan.activity;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class HelloIntentService extends IntentService {

    //传入父类构造方法的字符串将作为工作线程的名字,如IntentService[HelloIntentService]
    public HelloIntentService() {
        super("HelloIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.v("VERBOSE", Thread.currentThread().getName());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCreate() {
        Log.v("VERBOSE", "Create HelloIntentService");
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        Log.v("VERBOSE", "Destroy HelloIntentService");
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v("VERBOSE", "Start Command HelloIntentService");
        return super.onStartCommand(intent, flags, startId);
    }

}

 连续3次启动HelloService,输出如下图所示:


IntentService_第1张图片

 

1.IntentService会创建一个工作队列,启动服务时会有个intent传给onStartCommand()方法;

2.onStartCommand()方法的默认实现会把intent传递到工作队列中;

3.IntentService会创建一个工作线程一次从工作队列中获取intent,然后调用onHandleIntent()方法;

4.完成服务后会自动调用selfstop()方法;

 

因此IntentService不适合执行多个请求并发执行的情况。
 

你可能感兴趣的:(thread,android,工作)