IntentService教给自家啊

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央,无需我们担心

(以下才代表个人观感,仅供参考,软件亲测)

同诈究竟

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所在的线程,这个以前一直尚未留下意.

1、首推动电脑软件 — updated in 2017-6-4 by 吕浪

压缩:7zip
  管家与杀毒:腾讯电脑管家
  社交软件:QQ、微信电脑版
  浏览器:chrome、360浏览器、firefox
  资源管理器:clover
  Git:git-bash
  命令行:git-bash、cmder
  代码编辑器:Sublime Text、gVim
  文本编辑器:Notepad++
  markdown编辑器:Haroopad、MarkdownPad
  office:MS office
  ftp:Filezilla
  文件搜索:Listary、everything
  邮件:Foxmail
  视频播放器:potplayer
  下载器:迅雷极速版
  网络视频下充斥:维棠FLV视频下载
  音乐:网易云、酷狗、QQ音乐、foobar2000
  网盘:百度网盘
  驱动:驱动人生
  密码管理:keepass
  云笔记:为理解笔记
  图片编辑:美图秀秀
  科学上网:XX-Net、shadowsocks
  远程连接:putty
  翻译词典:网易有道词典
  右下角弹窗拦截:CloseADs
  pdf阅读器:极速pdf
  编译器:python、mingw、java
  敲键盘声:tickeys
  Windows和office激活:小马激活、网搜找到激活密钥
  输入法:搜狗输入法
  浏览器广告拦截插件:adblock(plus)
  wifi共享:猎豹wifi
  分区备份还原:onekey一键还原
  硬盘文件修复:DiskGenius(带硬盘分区等功用)
  微软官方纯净版软件下充斥(Windows/office等):“MSDN,我报您”网站
  钉住窗口:window on top
  截屏:shareX、QQ自带、系统自带
  文库下载:冰点文库下载器
  刻录iso文件到U盘:软碟通(注意要无毒的)
  电脑使用提示:fadetop、腾讯电脑管小的动时提醒作用
  RSS阅读器:foxmail、MS outlook
  流程图:MS visio、processOn(在线)
  U盘装系统:软碟通(注意下无毒的)
  虚拟机:VirtualBox
  pdf转word:极速pdf转word、smallPDF(在线:https://smallpdf.com/)


总结

第一学习及了:

  1. 可以运用Handler去维护一个列,很粗略
  2. HandlerThread类
  3. Handler的handleMessage艺术所在的线程决定给它们的Looper所在的线程

IntentService代码虽不见,但是好好.
另外,Android还有为数不少不行好之好像需要自我失去发现,去学!~
以学了同样造成,哈哈!~

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

微信公众号

2、首推进手机软件 — updated in 2017-6-4 by 吕浪

周旋软件:QQ、微信、Twitter
  应用市场:APKPure
  科学上网:VPN-Master(APKPure下载)、cloudVPN
  音乐:网易云音乐
  地图:高德地图
  支付:支付宝
  资讯整合:Zaker新闻、简书、豆瓣、reddit(需是上网)
  问答社区:知乎、Qoura
  记账:网易有钱
  输入法:搜狗输入法
  QQ安全:QQ安全中心
  云笔记:为理解笔记
  电子邮件:MIUI自带、QQ邮箱
  K歌:全民K歌、唱吧
  浏览器:QQ浏览器
  便签:MIUI自带
  密码管理:keepass
  电脑文件远程共享:ES文件浏览器
  FM和听书:喜马拉雅电台、蜻蜓FM、凤凰FM


3、程序员效率工具 — updated in 2017-6-4 by 吕浪

引用自Quora问答:
  What are the best productivity tools for
programmers?

Answer Wiki:
1.Lots of RAM / Fast Internet / SSDs
2.Good headphones(一契合好耳机)
3.Scheduled meetings
4.A good issue tracker (+reporting tools for your team members:
Usersnap to get all necessary meta infos and a screenshot
automatically for every reported bug)
5.Distributed version control (Git, Mercurial (software), Darcs)
6.Google / Stack overflow / Quora
7.Pen and Paper
8.Count down timer (focusalot.com is a task planner and time tracking
app that helps programmers be more productive)
9.Dropbox
10.IDEs
11.Code generation tools
12.Dual screens(双显示器)
13.ProofHub
14.Workflowy as an Outliner
15.Orgzit – Orgzit – Organize, Analyze, and Collaborate on any
business related information

Retina macbook pro高配版


4、网站、浏览器相关

找寻:Google、Google学术搜索
  技术问答神器:stackOverflow(https://stackoverflow.com/)
  代码托管:GitHub葡京在线开户(https://github.com)
  图片存储和CDN:七牛云
  NBA:NBA直播吧(https://www.zhibo8.cc/)
  pdf在线转word:smallPDF(https://smallpdf.com/)

and so on…