android 进程/线程管理(三)----Thread,Looper / HandlerThread / IntentService_weixin_30405421的博客-程序员宅基地

技术标签: java  ui  移动开发  

Thread,Looper的组合是非常常见的组合方式。

Looper可以是和线程绑定的,或者是main looper的一个引用。

下面看看具体app层的使用。

首先定义thread:

package com.joyfulmath.androidstudy.thread;

import com.joyfulmath.androidstudy.TraceLog;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

public class MyLoopThread extends Thread {
        
    private Looper myLooper = null;
    private MyHandler mHandler = null;
    public MyLoopThread()
    {
        super();
    }
    
    @Override
    public void run() {
        TraceLog.i("MyLoopThread looper prepare");
        Looper.prepare();
//        myLooper = Looper.getMainLooper(); /*using this can be set as main handler*/
        myLooper = Looper.myLooper();
        mHandler =  new MyHandler(myLooper);
        TraceLog.i("MyLoopThread looper loop");
        Looper.loop();
    }
    
    
    public void doAction(int index,String params)
    {
        if(index>0 && index <=3)
        {
            Message msg = mHandler.obtainMessage(index);
            Bundle bundle = new Bundle();
            bundle.putString("key", params);
            msg.setData(bundle);
            mHandler.sendMessage(msg);
        }
        else
        {
            TraceLog.w(index+"");
        }
    }
    
    public static  class MyHandler extends Handler{
        
        public MyHandler()
        {
            super();
        }
        
        public MyHandler(Looper loop)
        {
            super(loop);
        }
        
        /*make sure that the looper is main or not
         *so you can update UI or send main handler to do it. 
         * */
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            String params = bundle.getString("key");
            TraceLog.i(params);
            switch(msg.what)
            {
            case ThreadConstant.INDEX_1:
                TraceLog.d("INDEX_1");
                break;
            case ThreadConstant.INDEX_2:
                TraceLog.d("INDEX_2");
                break;
            case ThreadConstant.INDEX_3:
                TraceLog.d("INDEX_3");
                break;    
            }
        }
    }
}

上面这个MyLoopThread类把,hangler,looper,thread融合在一起了,我们看看关键的地方:

    @Override
    public void run() {
        TraceLog.i("MyLoopThread looper prepare");
        Looper.prepare();
//        myLooper = Looper.getMainLooper(); /*using this can be set as main handler*/
        myLooper = Looper.myLooper();
        mHandler =  new MyHandler(myLooper);
        TraceLog.i("MyLoopThread looper loop");
        Looper.loop();
    }

 

如上,Thread只在说一件是,消息循环。而且可以发送消息到主线程来处理。

如果MyLoopThread里面定义两个handler,会不会有冲突呢?

我们用代码试试看。

我们修改下run以及添加doaction2:

@Override
    public void run() {
        TraceLog.i("MyLoopThread looper prepare");
        Looper.prepare();
//        myLooper = Looper.getMainLooper(); /*using this can be set as main handler*/
        myLooper = Looper.myLooper();
        mHandler =  new MyHandler(myLooper);
        mHandler2 = new Handler(myLooper){

            @Override
            public void handleMessage(Message msg) {
                Bundle bundle = msg.getData();
                String params = bundle.getString("key");
                TraceLog.i("Handler2 "+params);
                switch(msg.what)
                {
                case ThreadConstant.INDEX_1:
                    TraceLog.d("Handler2 INDEX_1");
                    break;
                case ThreadConstant.INDEX_2:
                    TraceLog.d("Handler2 INDEX_2");
                    break;
                case ThreadConstant.INDEX_3:
                    TraceLog.d("Handler2 INDEX_3");
                    break;    
                }
            }
            
            
        };
        TraceLog.i("MyLoopThread looper loop");
        Looper.loop();
    }
    public void doAction2(int index,String params)
    {
        if(index>0 && index <=3)
        {
            Message msg = mHandler2.obtainMessage(index);
            Bundle bundle = new Bundle();
            bundle.putString("key", params);
            msg.setData(bundle);
            mHandler2.sendMessage(msg);
        }
        else
        {
            TraceLog.w(index+"");
        }
    }
08-03 17:04:40.679: I/MyLoopThread(25483): run: MyLoopThread looper prepare [at (MyLoopThread.java:22)]
08-03 17:04:40.679: I/MyLoopThread(25483): run: MyLoopThread looper loop [at (MyLoopThread.java:50)]
08-03 17:04:40.769: I/Timeline(25483): Timeline: Activity_idle id: android.os.BinderProxy@224def46 time:141675759
08-03 17:04:42.709: I/MyLoopThread$MyHandler(25483): handleMessage: time millseconds one [at (MyLoopThread.java:107)]
08-03 17:04:42.709: D/MyLoopThread$MyHandler(25483): handleMessage: INDEX_2 [at (MyLoopThread.java:114)]
08-03 17:04:47.299: I/MyLoopThread$1(25483): handleMessage: Handler2 time millseconds two [at (MyLoopThread.java:33)]
08-03 17:04:47.299: D/MyLoopThread$1(25483): handleMessage: Handler2 INDEX_2 [at (MyLoopThread.java:40)]
08-03 17:04:52.829: I/MyLoopThread$MyHandler(25483): handleMessage: time millseconds one [at (MyLoopThread.java:107)]
08-03 17:04:52.829: D/MyLoopThread$MyHandler(25483): handleMessage: INDEX_3 [at (MyLoopThread.java:117)]
08-03 17:04:53.479: I/MyLoopThread$MyHandler(25483): handleMessage: time millseconds one [at (MyLoopThread.java:107)]
08-03 17:04:53.479: D/MyLoopThread$MyHandler(25483): handleMessage: INDEX_3 [at (MyLoopThread.java:117)]
08-03 17:04:54.909: I/MyLoopThread$1(25483): handleMessage: Handler2 time millseconds two [at (MyLoopThread.java:33)]
08-03 17:04:54.909: D/MyLoopThread$1(25483): handleMessage: Handler2 INDEX_1 [at (MyLoopThread.java:37)]
08-03 17:04:56.309: I/MyLoopThread$1(25483): handleMessage: Handler2 time millseconds two [at (MyLoopThread.java:33)]
08-03 17:04:56.309: D/MyLoopThread$1(25483): handleMessage: Handler2 INDEX_3 [at (MyLoopThread.java:43)]

查看消息可以看到, handler很好的处理了消息,没有出现错乱的问题。

我们知道,对于每个thread,looper,messagequeue都是唯一的,那为什么没有出错呢?

我们看看之前在《android 进程/线程管理(一)----消息机制的框架》http://www.cnblogs.com/deman/p/4688054.html

中的looper.loop()

里面有一句:

msg.target.dispatchMessage(msg);

是的,这就是分发和处理消息。而target就是我们的handler。

 

HandlerThread:

对于上面的例子,google提供了一个更方便的解决方案:HandlerThread。

下面是HandlerThread的源码:

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

可以看到,handlerThread自己把looper给启动了。

下面是使用handlerthread的代码,比thread,looper更为简单。

package com.joyfulmath.androidstudy.thread;

import com.joyfulmath.androidstudy.TraceLog;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

public class MyHandlerThread extends HandlerThread{

    MyHandler myHandler = null;
    
    public MyHandlerThread(String name) {
        super(name);
    }
    
        
    @Override
    protected void onLooperPrepared() {
        super.onLooperPrepared();
        myHandler = new MyHandler(getLooper());
    }

    public void doAction(int index,String params)
    {
        if(index>0 && index <=3)
        {
            Message msg = myHandler.obtainMessage(index);
            Bundle bundle = new Bundle();
            bundle.putString("key", params);
            msg.setData(bundle);
            myHandler.sendMessage(msg);
        }
        else
        {
            TraceLog.w(index+"");
        }
    }

    public static  class MyHandler extends Handler{
        
        public MyHandler()
        {
            super();
        }
        
        public MyHandler(Looper loop)
        {
            super(loop);
        }
        
        /*make sure that the looper is main or not
         *so you can update UI or send main handler to do it. 
         * */
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            String params = bundle.getString("key");
            TraceLog.i(params);
            switch(msg.what)
            {
            case ThreadConstant.INDEX_1:
                TraceLog.d("INDEX_1");
                break;
            case ThreadConstant.INDEX_2:
                TraceLog.d("INDEX_2");
                break;
            case ThreadConstant.INDEX_3:
                TraceLog.d("INDEX_3");
                break;    
            }
        }
    }
}
    private void initView() {
        ...
        
        btnStart3 = (Button) findViewById(R.id.thread_start_id3);
        btnStart3.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                myHandlerThread.doAction((int)(Math.random()*3)+1, "handlerthread time millseconds");
            }
        });
    }

以上是启动handlerthread的代码。

 

IntentService:

我们可以看看源码:

intentservice 本质上就是 service + handlerthread的组成方式!

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((Intent)msg.obj);
            stopSelf(msg.arg1);
        }
    }

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

    /**
     * Sets intent redelivery preferences.  Usually called from the constructor
     * with your preferred semantics.
     *
     * <p>If enabled is true,
     * {
      @link #onStartCommand(Intent, int, int)} will return
     * {
      @link Service#START_REDELIVER_INTENT}, so if this process dies before
     * {
      @link #onHandleIntent(Intent)} returns, the process will be restarted
     * and the intent redelivered.  If multiple Intents have been sent, only
     * the most recent one is guaranteed to be redelivered.
     *
     * <p>If enabled is false (the default),
     * {
      @link #onStartCommand(Intent, int, int)} will return
     * {
      @link Service#START_NOT_STICKY}, and if the process dies, the Intent
     * dies along with it.
     */
    public void setIntentRedelivery(boolean enabled) {
        mRedelivery = enabled;
    }

    @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 = new ServiceHandler(mServiceLooper);
    }

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

    /**
     * You should not override this method for your IntentService. Instead,
     * override {
      @link #onHandleIntent}, which the system calls when the IntentService
     * receives a start request.
     * @see android.app.Service#onStartCommand
     */
    @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();
    }

    /**
     * Unless you provide binding for your service, you don't need to implement this
     * method, because the default implementation returns null. 
     * @see android.app.Service#onBind
     */
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * This method is invoked on the worker thread with a request to process.
     * Only one Intent is processed at a time, but the processing happens on a
     * worker thread that runs independently from other application logic.
     * So, if this code takes a long time, it will hold up other requests to
     * the same IntentService, but it will not hold up anything else.
     * When all requests have been handled, the IntentService stops itself,
     * so you should not call {
      @link #stopSelf}.
     *
     * @param intent The value passed to {
      @link
     *               android.content.Context#startService(Intent)}.
     */
    protected abstract void onHandleIntent(Intent intent);
}
IntentService

我们首先看onCreate:

    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 = new ServiceHandler(mServiceLooper);
    }

开启了一个handlerthread,并且初始化mServiceHandler,

mServiceHandler就是一个普通的handler,只是把消息处理给了onHandleIntent

        public void handleMessage(Message msg) {
            onHandleIntent((Intent)msg.obj);
            stopSelf(msg.arg1);
        }

所以intentservice实例就需要实现onHandleIntent方法,来处理消息。

一下是intentservice使用的一个demo:

package com.joyfulmath.androidstudy.thread;

import com.joyfulmath.androidstudy.TraceLog;

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

public class MyIntentService extends IntentService {

    public MyIntentService() {
        super("MyIntentService");
    }
    
    
    
    @Override
    public void onCreate() {
        super.onCreate();
        TraceLog.i();
    }



    @Override
    protected void onHandleIntent(Intent intent) {
        TraceLog.i();
        doAction(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        TraceLog.i();
    }
    
    private void doAction(Intent intent)
    {
        String params = intent.getStringExtra("key");
        TraceLog.i(params);
        int index = intent.getIntExtra("index", -1);
        TraceLog.i(index+"");
    }
}
MyIntentService

可以看下log:

导出的log,没有tid,所以上传了图片。可以看到onHandleIntent运行在工作线程里面。

IntentService会在处理完了以后,直接destory掉。

 

android 进程/线程管理(一)----消息机制的框架

 

转载于:https://www.cnblogs.com/deman/p/4699977.html

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_30405421/article/details/96159110

智能推荐

电脑硬件组成_huaweihaha的博客-程序员宅基地

一、计算机硬件五大功能部分 1.运算器 运算器又称算术逻辑单元(Arithmetic Logic Unit简称ALU)。它是计算机对数据进行加工处理的部件,包括算术运算(加、减、乘、除等)和逻辑运算(与、或、非、异或、比较等)。 2.控制器 控制器负责从存储器中取出指令,并对指令进行译码;根据指令的要求,按时间的先后顺序,负责向其它各部件发出控制信号,保证各部件协调一致地工作,一步一步地完成各种操

树莓派4b新手烧录解决问题(ip找不到,putty连接失败)_树莓派4b烧录完不能连接-程序员宅基地

树莓派4b新手烧录解决问题(ip找不到,putty连接失败)_树莓派4b烧录完不能连接

unp源码的编译与使用_unpv13e 编译_惜暮的博客-程序员宅基地

一.unp源码编译与使用1. 进入源码目录~/unpv13e/下 执行#./configure 在~/unpv13e/下就产生了config.h文件。2. 执行命令#cd lib 然后执行#make 就在~/unpv13e/下产生了libunp.a3. ~/unpv13e/下执行#cd libfree再执行#make 还是在~/unpv13e/下产生了libunp.a4_unpv13e 编译

SetWindowPos && FindWindowA_Newtown-Gao的博客-程序员宅基地

SetWindowPosSetWindowPos函数改变一个子窗口,弹出式窗口或顶层窗口的尺寸,位置和Z序。子窗口,弹出式窗口,及顶层窗口根据它们在屏幕上出现的顺序排序、顶层窗口设置的级别最高,并且被设置为Z序的第一个窗口。函数原型BOOL SetWindowPos(HWND hWnd, const CWnd* pWndInsertAfter, int x, int y,int c_findwindowa

java 流 base64 大文件_base64编码处理大文件_未央 繁华的博客-程序员宅基地

在做项目的时候遇到需要将文件转为base64编码,并存储在文件中。在将文件转为base64编码是会将文件读入内存,进行base64编码,输出到文件中。代码入下:FileInputStream stream = new FileInputStream("D:\\桌面\\程序员-第4版.pdf");ByteArrayOutputStream out = new ByteArrayOutputStrea...

随便推点

MATLAB与数学建模:变量与文件存取_存贮模型数学建模matlab代码_热带鱼啊的博客-程序员宅基地

以下内容为个人笔记,部分图片来源于郭老师课件或课程截图。笔记汇总:MATLAB基础教程课程视频:MATLAB基础教程-台大郭彦甫(14课全-高清-含课件)文章目录变量类型StringStructcell多维数组数据存取save() 和 [load()](https://ww2.mathworks.cn/help/matlab/ref/load.html)向 Excel 中读写数据xlsread() 的替代品:[readmatrix()](https://ww2.mathworks.cn/help/m_存贮模型数学建模matlab代码

判断字符串中的中文字符_char能否用isdbcsleadbyte判断是否还有汉字_headmaster110的博客-程序员宅基地

中文字符是按照双字节编码的;也就是说一个中文字符占两个字节;通过判断当前字符是否是双字节边个的前一个字节就可以判断字符串中是否有中文汉字;函数: BOOL IsDBCSLeadByte( BYTE TestChar );功能: 判断TestChar是否是双字节编码的前一个字节;代码如下: void main(){ char ch[] = "I am 校_char能否用isdbcsleadbyte判断是否还有汉字

几句话阐述清楚log4j、slf4j、logback、tinylog之间的区别_tinylog与log4j哪个好_菜鸟爪哇爪的博客-程序员宅基地

1.早期,jdk不提供日志功能,所以程序员要想输出相关信息,基本上都使用 System.out.println( );2.在这个背景下,一位伟大的程序员,暂且称呼为 伟员, 设计了一套系统的日志功能代码,也就是log4j,广受程序员欢迎3.在这之后,log4j表示jdk可以把log4j功能纳入其中,但是jdk竟然碍于脸面,拒绝了。4.虽然拒绝了,但是这个功能还是要有的啊,于是也开发了一..._tinylog与log4j哪个好

编译原理(6):中间代码生成_类型表达式_逢青丶的博客-程序员宅基地

声明:本系列文章,是根据中国大学MOOC网 哈工大的编译原理 这门课学习而成的学习笔记。一、类型表达式 (Type Expressions)类型表达式基本类型是类型表达式integerrealcharbooleantype_error (出错类型)void (无类型)可以为类型表达式命名,类型名也是类型表达式将类型构造符(type constructor)作用于..._类型表达式

[Java基础]StringUtils.join()方法与String.join()方法的使用_鲨鱼辣椒灬的博客-程序员宅基地

StringUtils.join()和String.join()用途:将数组或集合以某拼接符拼接到一起形成新的字符串。1.StringUtils.join()方法:(1)使用前需先引入common-lang3的jar包,可去官网下载:apache官网下载页面(2)方法如下图:(3)基本上此方法需传入2个参数,第一个参数是传入一个任意类型数组或集合,第二个参数是拼接符。 ...

centos7.4安装高可用(haproxy+keepalived实现)kubernetes1.6.0集群(开启TLS认证)_weixin_30583563的博客-程序员宅基地

目录目录前言集群详情环境说明安装前准备提醒一、创建TLS证书和秘钥安装CFSSL创建 CA (Certificate Authority)创建 CA 配置文件创建 CA 证书签名请求生成 CA 证书和私钥创建 kubernetes 证书生成 kubernetes 证书和私钥创建 admin 证...