整理:多线程+计时器(TimerTask、Timer、Handler、Message、Thread、Runnable、HandlerThread)

new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent=new Intent(xxx.this,yyy.class);
                            startActivity(intent);
                            finish();
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

多线程之HandlerThread 完全详解

转载于:Android 多线程之HandlerThread 完全详解 - zejian的博客 - CSDN博客
之前对线程也写过几篇文章,不过倒是没有针对android,因为java与android在线程方面大部分还是相同,不过本篇我们要介绍的是android的专属类HandlerThread,因为HandlerThread在设置思想上还是挺值得我们学习的,那么我们下面来就了解它吧,我们先来看看HandlerThread有那些特点:

  • HandlerThread本质上是一个线程类,它继承了Thread;
  • HandlerThread有自己的内部Looper对象,可以进行looper循环;
  • 通过获取HandlerThread的looper对象传递给Handler对象,可以在handleMessage方法中执行异步任务。
  • 创建HandlerThread后必须先调用HandlerThread.start()方法,Thread会先调用run方法,创建Looper对象。

1.创建实例对象

HandlerThread handlerThread = new HandlerThread("downloadImage");

传入参数的作用主要是标记当前线程的名字,可以任意字符串。

2.启动HandlerThread线程

//必须先开启线程
handlerThread.start();

到此,我们创建完HandlerThread并启动了线程。那么我们怎么将一个耗时的异步任务投放到HandlerThread线程中去执行呢?接下来看下面步骤:

3.构建循环消息处理机制

  /**
     * 该callback运行于子线程
     */
    class ChildCallback implements Handler.Callback {
        @Override
        public boolean handleMessage(Message msg) {
            //在子线程中进行相应的网络请求

            //通知主线程去更新UI
            mUIHandler.sendMessage(msg1);
            return false;
        }
    }

4.构建异步handler

//子线程Handler
Handler childHandler = new Handler(handlerThread.getLooper(),new ChildCallback());

第3步和第4步是构建一个可以用于异步操作的handler,并将前面创建的HandlerThread的Looper对象以及Callback接口类作为参数传递给当前的handler,这样当前的异步handler就拥有了HandlerThread的Looper对象,由于HandlerThread本身是异步线程,因此Looper也与异步线程绑定,从而handlerMessage方法也就可以异步处理耗时任务了,这样我们的Looper+Handler+MessageQueue+Thread异步循环机制构建完成。

完整例子

private Handler mUIHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            //8、更新UI
            Log.d("Test","次数:" + msg.what);
        }
    };
    
   /**
     * 开始创建并使用线程
     */
private  void startUseThread() {
  
        //1、创建异步HandlerThread,取名为"downloadImage"
        HandlerThread handlerThread = new HandlerThread("downloadImage");
        //2、必须先开启线程
        handlerThread.start();
        //3、子线程Handler:Looper, Handler.Callback
        Handler childHandler = new Handler(handlerThread.getLooper(),new ChildCallback());
        //4、隔一定时间去更新UI:int what, long delayMillis
        childHandler.sendEmptyMessageDelayed(1,1000*3);
    }

    /**
     * 该callback运行于子线程
     */
class ChildCallback implements Handler.Callback {
        @Override
        public boolean handleMessage(Message msg) {
            // 5、在子线程中进行网络请求
            // 6、获取到数据后,放入Message中
            // 比如:把网络请求到的数据转成model模型,放入Message的obj中
            // 在主线程Handler的handleMessage中取出数据,进行UI更新操作
            Message msg1 = new Message();
            msg1.what = msg.what;
//            msg1.obj =  model模型;
            //7、通知主线程去更新UI
            mUIHandler.sendMessage(msg1);
            return false;
        }
    }

==================================================================================
转载于:Android实现计时与倒计时的几种方法 - CSDN博客 https://blog.csdn.net/lanxingfeifei/article/details/51769740

方法一、Timer与TimerTask(Java实现)

public class timerTask extends Activity{  
 
    private int recLen = 11;  
    private TextView txtView;  
    Timer timer = new Timer();  
 
    public void onCreate(Bundle savedInstanceState){  
        super.onCreate(savedInstanceState);  
          
        setContentView(R.layout.timertask);  
        txtView = (TextView)findViewById(R.id.txttime);  
          
        timer.schedule(task, 1000, 1000);       // timeTask  
    }     
 
    TimerTask task = new TimerTask() {  
        @Override  
        public void run() {  
 
            runOnUiThread(new Runnable() {      // UI thread  
                @Override  
                public void run() {  
                    recLen--;  
                    txtView.setText(""+recLen);  
                    if(recLen < 0){  
                        timer.cancel();  
                        txtView.setVisibility(View.GONE);  
                    }  
                }  
            });  
        }  
    };  
}  

方法二 、TimerTask与Handler(不用Timer的改进型)

public class timerTask extends Activity{  
    private int recLen = 11;  
    private TextView txtView;  
    Timer timer = new Timer();  
 
    public void onCreate(Bundle savedInstanceState){  
        super.onCreate(savedInstanceState);  
 
        setContentView(R.layout.timertask);  
        txtView = (TextView)findViewById(R.id.txttime);  
 
        timer.schedule(task, 1000, 1000);       // timeTask  
    }     
 
    final Handler handler = new Handler(){  
        @Override  
        public void handleMessage(Message msg){  
            switch (msg.what) {  
            case 1:  
                txtView.setText(""+recLen);  
                if(recLen < 0){  
                    timer.cancel();  
                    txtView.setVisibility(View.GONE);  
                }  
            }  
        }  
    };  
 
    TimerTask task = new TimerTask() {  
        @Override  
        public void run() {  
            recLen--;  
            Message message = new Message();  
            message.what = 1;  
            handler.sendMessage(message);  
        }  
    };  
}

方法三、Handler与Message(不用TimerTask)

public class timerTask extends Activity{  
    private int recLen = 11;  
    private TextView txtView;  
 
    public void onCreate(Bundle savedInstanceState) {    
        super.onCreate(savedInstanceState);    
 
        setContentView(R.layout.timertask);   
        txtView = (TextView)findViewById(R.id.txttime);  
 
        Message message = handler.obtainMessage(1);     // Message  
        handler.sendMessageDelayed(message, 1000);  
    }    
 
    final Handler handler = new Handler(){  
 
        public void handleMessage(Message msg){         // handle message  
            switch (msg.what) {  
            case 1:  
                recLen--;  
                txtView.setText("" + recLen);  
 
                if(recLen > 0){  
                    Message message = handler.obtainMessage(1);  
                    handler.sendMessageDelayed(message, 1000);      // send message  
                }else{  
                    txtView.setVisibility(View.GONE);  
                }  
            }  
 
            super.handleMessage(msg);  
        }  
    };  
}  

方法四 、Handler与Thread(不占用UI线程)

public class timerTask extends Activity{  
    private int recLen = 0;  
    private TextView txtView;  
 
    public void onCreate(Bundle savedInstanceState){  
        super.onCreate(savedInstanceState);  
 
        setContentView(R.layout.timertask);  
        txtView = (TextView)findViewById(R.id.txttime);  
          
        new Thread(new MyThread()).start();         // start thread  
    }     
 
    final Handler handler = new Handler(){          // handle  
        public void handleMessage(Message msg){  
            switch (msg.what) {  
            case 1:  
                recLen++;  
                txtView.setText("" + recLen);  
            }  
            super.handleMessage(msg);  
        }  
    };  
 
    public class MyThread implements Runnable{      // thread  
        @Override  
        public void run(){  
            while(true){  
                try{  
                    Thread.sleep(1000);     // sleep 1000ms  
                    Message message = new Message();  
                    message.what = 1;  
                    handler.sendMessage(message);  
                }catch (Exception e) {  
                } 

方法五、Handler与Runnable(最简单型)

Handler与Runnable(最简单型)  
 
public class timerTask extends Activity{  
    private int recLen = 0;  
    private TextView txtView;  
 
    public void onCreate(Bundle savedInstanceState){  
        super.onCreate(savedInstanceState);  
 
        setContentView(R.layout.timertask);  
        txtView = (TextView)findViewById(R.id.txttime);  
          
        handler.postDelayed(runnable, 1000);  
    }     
 
    Handler handler = new Handler();  
    Runnable runnable = new Runnable() {  
        @Override  
        public void run() {  
            recLen++;  
            txtView.setText("" + recLen);  
            handler.postDelayed(this, 1000);  
        }  
    };  
}  

计时与倒计时
方法1,方法2和方法3,都是倒计时
方法4,方法5,都是计时
计时和倒计时,都可使用上述方法实现(代码稍加改动)

UI线程比较
方法1,方法2和方法3,都是在UI线程实现的计时;
方法4和方法5,是另开Runnable线程实现计时

实现方式比较
方法1,采用的是Java实现,即Timer和TimerTask方式;
其它四种方法,都采用了Handler消息处理

推荐使用
如果对UI线程交互要求不很高,可以选择方法2和方法3
如果考虑到UI线程阻塞,严重影响到用户体验,推荐使用方法4,另起线程单独用于计时和其它的逻辑处理
方法5,综合了前几种方法的优点,是最简的

你可能感兴趣的:(Android之路,整理)