IntentService源码解读

一:用法

public class MyIntentService extends IntentService {

    /**
     * A constructor is required, and must call the super IntentService(String)
     * constructor with a name for the worker thread.
     */
    public MyIntentService() {
        super("ServiceName");
    }

    /**
     * The IntentService calls this method from the default worker thread with
     * the intent that started the service. When this method returns, IntentService
     * stops the service, as appropriate.
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        //在这里进行耗时操作,,和Service一样
    }
}

调用的时候:

   // 可以调用多次startService();
   Intent intent=new Intent(this,MyIntentService.class);
   startService(intent);
   startService(intent);
   startService(intent);

当然别忘了在AndroidManifest.xml里面进行注册。

二:用处

IntentService is a base class for {@link Service}s that handle asynchronous requests (expressed as {@link Intent}s) on demand. Clients send requests through {@link android.content.Context#startService(Intent)} calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.(IntentService是Service的子类,用来处理异步请求,客户端可以通startService(Intent)方法传递请求给IntentService,IntentService处理每个Intent通过一个工作线程,执行完所一个Intent请求对象所对应的工作之后,如果没有新的Intent请求达到,则自动停止Service;否则执行下一个Intent请求所对应的任务。)

IntentService做了以下几件事:

  • Creates a default worker thread that executes all intents delivered to onStartCommand()separate from your application’s main thread.
  • Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about multi-threading.
  • Stops the service after all start requests have been handled, so you never have to call stopSelf().
  • Provides default implementation of onBind() that returns null.
  • Provides a default implementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIntent() implementation.

三:HandlerThread

先说一下HandlerThread,因为IntentService将要使用这个类。

Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.

HandlerThreadThread的子类。
1构造方法:

//线程的名字
public HandlerThread(String name) {
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }

 @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll(); //唤醒所有的等待线程
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();//默认是死循环
        mTid = -1;
    }
public Looper getLooper() {
        if (!isAlive()) {
            return null;
        }

        // If the thread has been started, wait until the looper has been created.
        synchronized (this) {
            while (isAlive() && mLooper == null) {
                try {
                    wait(); //如果 isAlive() 和 mLooper没有准备好就让当前线程进行等待
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

这些还是比较好理解的,不理解的话说明对Hanlder Looper机制不是很理解,可以看这里

HandlerThread,使用方法:

//参数为Thread的名字
        HandlerThread handlerThread = new HandlerThread("WQH");
        handlerThread.start(); //必须调用 在run()方法里面创建了一个LooperThread 来处理消息
        // superHandler的创建需要一个Looper 将HandlerThread的Looper对象传递给superHandler 使superHandler在其他线程中进行消息处理
        // superHandler发送的Message将在HandlerThread中进行处理
        Handler superHandler = new Handler(handlerThread.getLooper()) {

            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                Log.d(TAG, Thread.currentThread().getName() + " HandlerThread is OK");
            }
        };
        superHandler.sendEmptyMessage(1);

四: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); 
        }
    }
    //构造方法  线程名字
    public IntentService(String name) {
        super();
        mName = name;
    }

    //Service 的onCreate()方法,
    @Override
    public void onCreate() {
        // TODO: It would be nice to have an option to hold a partial wakelock
        // during processing, and to have a static startService(Context, Intent)
        // method that would launch the service & hand off a wakelock.

        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        //mServiceHandler发送的消息将送至 thread进行处理
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }


@Override
    public void onStart(Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;  //ServiceHandler 中通过msg.arg1来stopSelf(msg.arg1);
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }

 @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

//在工作线程下被调用
//@param intent The value passed to {@link android.content.Context#startService(Intent)}.
 @WorkerThread
    protected abstract void onHandleIntent(Intent intent);

所以在使用IntentService只需要复写构造函数和onHandleIntent就OK了。最后调用的时候,IntentService将所用的Intent放在一个Work Thread下进行处理。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值