公海赌船网站凡时刻来读一下IntentService了.该类已经帮助咱创建好了线程供我们下。

总结

要学习到了:

  1. 好应用Handler去保护一个列,很粗略
  2. HandlerThread类
  3. Handler的handleMessage法所在的线程决定让她的Looper所在的线程

IntentService代码虽不见,但是很好.
除此以外,Android还有众多杀好之类需要自家去发现,去读!~
同时学了相同招,哈哈!~

除此以外欢迎关注:
我的Github
自之微博
自的微信公众号:

微信公众号

4 总结

IntentService是一个比较轻便的类,省了咱们以开立Thread,但是并无能够符合有的情事,它会创造一个线程,多独任务仍梯次执行,并且实施过程中无可知取消该任务。所以还是要依据事态开展以。

IntentService

眼前几乎天修了Service,此处是记,是下来读一下IntentService了.

仍然,先押下官网介绍:

IntentService is a base class for Services that handle asynchronous
requests (expressed as Intents) on demand. Clients send requests
through 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.
This “work queue processor” pattern is commonly used to offload tasks
from an application’s main thread. The IntentService class exists to
simplify this pattern and take care of the mechanics. To use it,
extend IntentService and implement onHandleIntent(Intent).
IntentService will receive the Intents, launch a worker thread, and
stop the service as appropriate.
All requests are handled on a single worker thread — they may take as
long as necessary (and will not block the application’s main loop),
but only one request will be processed at a time.

简总结一下:
service的子类,用于拍卖异步请求,并且在劳作线程按梯次处理要,工作完后自己停止.
使啊生简单,继承IntentService,实现onHandleIntent(Intent)方就是可.
特点:

  1. 以及Service不同,IntentService是从线程处理任务之
  2. 起带队列,每个请求都见面排队
  3. 职责完成好会调用stopSelf截止,无需我们担心

1 简介

IntentService概括

IntentService is a base class for Service that handle asynchronous
requests (expressed as Intents) on demand. Clients send requests
through 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.
This “work queue processor” pattern is commonly used to offload tasks
from an application’s main thread. The IntentService class exists to
simplify this pattern and take care of the mechanics. To use it,
extend IntentService and implement onHandleIntent(Intent).
IntentService will receive the Intents, launch a worker thread, and
stop the service as appropriate.
All requests are handled on a single worker thread — they may take as
long as necessary (and will not block the application’s main loop),
but only one request will be processed at a time.

IntentService是Service的子类,根据需要处理异步请求(以intent表示)。客户端通过调用startService(Intent)
发送请求,该Service根据需要启动,使用工作线程处理依次每个Intent,并在停工作时止自身。
这种“工作行列处理器”模式通常用于自应用程序的主线程中卸载任务。
IntentService类的存在是为着简化这种模式。
要使用她,扩展IntentService并落实onHandleIntent(Intent)。
IntentService将接收Intents,启动一个行事线程,并因需要停止该服务。
具请求都于单个工作线程处理 –
它们或用格外丰富之时空(并且不见面阻拦应用程序的主循环),但是同样不成就见面处理一个告。


相同试探究竟

IntentService源码不多,截取了一些:

public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;
    private String mName;
    private boolean mRedelivery;

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
          //调用onHandleIntent
            onHandleIntent((Intent)msg.obj);
            // 处理完自己停止
            stopSelf(msg.arg1);
        }
    }

    public IntentService(String name) {
        super();
        mName = name;
    }

    public void setIntentRedelivery(boolean enabled) {
        mRedelivery = enabled;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //开启个新的线程
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();
        //getLooper 来获取thread的looper
        mServiceLooper = thread.getLooper();
        //拿looper实例化 handler
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        //封装intent的请求 用handler发送
        mServiceHandler.sendMessage(msg);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
      //退出循环
        mServiceLooper.quit();
    }

    protected abstract void onHandleIntent(Intent intent);
}

成员变量不多,一个looper,一个handler,接下去分析一下:
在onCreate里,实例化一个HandlerThread(继承自Thread,HandlerThread后面再说)并且启动线程,并且采用该HandlerThread线程的looper实例化handler.
onStart里受之intent,封装成Message用handler发送,并在handleMessage中调用onHandleIntent((Intent)msg.obj);,再stopSelf.
另外在onDestroy里调用了looper.quit();退出looper.

这样intentService的体制原理为多看了了,其实不为难,但是也克学到众多事物:

  1. HandlerThread类–>合法材料

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.

惠及我们创建一个具备looper的线程,可以用来创造handler.注意: start()
必须让调用!

先前也未理解此近乎,这次索性来瞧HandlerThread的源码:

public class HandlerThread extends Thread {
    int mPriority;
    int mTid = -1;
    Looper mLooper;

    public HandlerThread(String name) {
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }

    public HandlerThread(String name, int priority) {
        super(name);
        mPriority = priority;
    }

    protected void onLooperPrepared() {
    }

    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

    /**
     * This method returns the Looper associated with this thread. If this thread not been started
     * or for any reason is isAlive() returns false, this method will return null. If this thread
     * has been started, this method will block until the looper has been initialized.  
     * @return The looper.
     */
    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();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

    public boolean quit() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quit();
            return true;
        }
        return false;
    }

    public boolean quitSafely() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quitSafely();
            return true;
        }
        return false;
    }

    public int getThreadId() {
        return mTid;
    }
}

咱俩都明白当线程里实例化handler要调用Looper.prepare();Looper.loop();,其实就算是以Looper
一旦HandlerThread有个分子变量mLooper,并且于run里面实例化了她,并且已也咱封装好了Looper相关的不二法门~

注意getLooper措施,当mLooper为null时会一直wait,直到run艺术里实例化mLooper并notifyAll,可以学学一下.

故法即以一下IntentService里的代码吧:

HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
  1. Handler类的handleMessage方所在的线程决定给它的Looper所在的线程,这个以前一直没留意.

demo下载地址:http://www.demodashi.com/demo/10627.html

接大家关注、评论、点赞
你们的支撑是本人坚持的动力。

接关注我之微信公众号

3 IntentService源码解析

路径:frameworks/base/core/java/android/app/IntentService.java
先期看下IntentService的构造方法和onCreate()。

public abstract class IntentService extends Service {
    //Creates an IntentService.  Invoked by your subclass's constructor.
    public IntentService(String name) {
        super();
            mName = name;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }
    。。。。
}

IntentService 是继往开来Service的一个抽象类,所以用持续IntentService
并须兑现该抽象方法onHandleIntent。
接轨IntentService需要贯彻一个空的构造器,并且调用IntentService的构造器。
当onCreate()方法被创造了一个HandlerThread,并允许该线程。HandlerThread
不极端明了的得参照我之直达同样篇文章Android
HandlerThread详解。
取子线程中之Looper实例,然后创建和子线程绑定的Handler对象。

接着看IntentService的onStart()。

public void onStart(Intent intent, int startId) {
    Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
}

以onStart方法中,创建Message对象,并以“消息”通过mServiceHandler发送及子线程中的消息队列中。
俺们掌握这些信息处理或会散发及Handler中。接着看mServiceHandler

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);
        }
}

消息会在handlerMessage中处理,该法被调用了onHandleIntent,所以我们得贯彻onHandleIntent,在该方法中召开我们只要开的职责。而信息处理到位后,调用stopSelf将自我Service销毁。这里或许会见生出问号,既然一个职责尽到位后虽见面实行stopSelf,那大多只任务是怎么处理的也罢?这里stopSelf(msg.arg1),会先行看行中是否发信息需要处理,如果出则连续处理后的音讯,没有才见面以Service销毁。
接着看IntentService的onDestroy方法

@Override
public void onDestroy() {
    mServiceLooper.quit();
}

以IntentService的onDestroy方法中见面调用looper的quit方法,将子线程的音讯循环停止,等待任务就后收子线程。


2 代码

每当IntentService中处理下载请求(模拟),并以速更新至Ui。
MyIntentService.java代码如下:

public class MyIntentService extends IntentService {
    private final static String TAG = "MyIntentService";

    public static final String ACTION_DOWN_IMG = "down.image";
    public static final String ACTION_DOWN_VID = "down.vid";
    public static final String ACTION_DOWN_PROGRESS = "com.zpengyong.down.progress";
    public static final String ACTION_SERVICE_STATE = "com.zpengyong.service.state";    
    public static final String PROGRESS = "progress";
    public static final String SERVICE_STATE = "service_state";

    //构造方法 一定要实现此方法否则Service运行出错。
    public MyIntentService() {
        super("MyIntentService");
    }

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

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i(TAG, "");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.i(TAG, "onHandleIntent thread:"+Thread.currentThread());
        String action = intent.getAction();
        if(action.equals(ACTION_DOWN_IMG)){
            for(int i = 0; i < 100; i++){
                try{ //模拟耗时操作
                    Thread.sleep(50);
                }catch (Exception e) {
                }
                sendProgress(i);
            }
        }else if(action.equals(ACTION_DOWN_VID)){
            for(int i = 0; i < 100; i++){
                try{ //模拟耗时操作
                    Thread.sleep(70);
                }catch (Exception e) {
                }
                sendProgress(i);
            }
        }
        Log.i(TAG, "onHandleIntent end");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");
        sendServiceState("onDestroy");
    }
    //发送Service的状态
    private void sendServiceState(String state){
        Intent intent = new Intent();
        intent.setAction(ACTION_SERVICE_STATE);
        intent.putExtra(SERVICE_STATE, state);
        sendBroadcast(intent);
    }

    //发送进度
    private void sendProgress(int progress){
        Intent intent = new Intent();
        intent.setAction(ACTION_DOWN_PROGRESS);
        intent.putExtra(PROGRESS, progress);
        sendBroadcast(intent);
    }
}

使用IntentService的方法:

  1. 继承IntentService。
  2. 心想事成不牵动参数的构造方法,并且调用父类IntentService的构造方法。
  3. 实现onHandleIntent方法。

以onHandleIntent方法被好因intent来分别任务,这里有少个任务,一个凡生充斥图片、一个是产载视频(模拟耗时操作)。
运行效果
1 只点击“启动任务一样”。

起先任务同样

打印:

07-15 03:07:24.589: I/MyIntentService(3186): onCreate
07-15 03:07:24.593: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:07:30.918: I/MyIntentService(3186): onHandleIntent end
07-15 03:07:31.017: I/MyIntentService(3186): onDestroy

IntentService启动后还onHandleIntent方法被施行任务(该办法工作以子线程中),任务履行了晚,IntentService销毁。

2 点击“启动任务同样”,任务不成功时点击“停止Service”。

停止Service

log

07-15 03:08:08.477: I/MyIntentService(3186): onCreate
07-15 03:08:08.478: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:08:12.203: I/MyIntentService(3186): onDestroy
07-15 03:08:14.253: I/MyIntentService(3186): onHandleIntent end

IntentService中线程执行任务时,stopService会让IntentService销毁,但是任务继续执行,直到执行就线程退出。

3 点击“启动任务同样”,任务到位后点击“启动任务二”。

职责成功还起步

log信息:

07-15 03:11:42.366: I/MyIntentService(3186): onCreate
07-15 03:11:42.367: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:11:48.285: I/MyIntentService(3186): onHandleIntent end
07-15 03:11:48.289: I/MyIntentService(3186): onDestroy
07-15 03:11:50.174: I/MyIntentService(3186): onCreate
07-15 03:11:50.205: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:11:58.446: I/MyIntentService(3186): onHandleIntent end
07-15 03:11:58.510: I/MyIntentService(3186): onDestroy

出于臻可知,任务尽就后,线程退出循环,Service销毁。重新被任务虽然更创设Service,执行任务。

4 点击“启动任务一样”,任务就前点击“启动任务二”。

起步两单任务

log信息

07-15 03:16:46.998: I/MyIntentService(3186): onCreate
07-15 03:16:46.998: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:16:52.980: I/MyIntentService(3186): onHandleIntent end
07-15 03:16:52.980: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:17:01.048: I/MyIntentService(3186): onHandleIntent end
07-15 03:17:01.053: I/MyIntentService(3186): onDestroy

正常startService启动两个任务,第一单不就前,将第二只任务放到队列中,等待第一个到位后实行第二单任务,第二只任务就后,Service自动销毁。

5
点击“启动任务一样”,任务成功前点击“停止Service”,然后又点击“启动任务二”。

启动 停止 启动

log信息

先是个任务没有结束时stopservice,IntentService销毁,其线程继续运行(tid
3691)。此时还startService会开启IntentService,其会晤再度创设一个线程运行任务(tid
3692)。两只任务在点滴独线程中运作,所以其实施完毕的先后顺序不确定。


转载请注明出处:http://www.jianshu.com/p/95e0ef1b81cb
近来正在加剧基础,看到个IntentService类,以前向不曾碰到了,更不知其用来涉及嘛的,所以便整了一个demo,看看这个怎么利用。
咱们常用到Service,并且在Service开启线程处理耗时操作,Android封装了一个IntentService类,该类已经帮助我们创建好了线程供我们用。

相关文章