Android的线程利器之AsyncTask


java自带的线程已经慢不错的了,在Android里又进了一步。一开始,在java传统的Thread和Runnable里加上了handler就已经蛮不错的了,handler作为信息调配的中转站,让人用的很输入,线程就只管去计算,分配的事就不要你做了。我写的东西有点杂乱无章,呵呵。再后来就到了高级一点的HandlerThread,把资源费配的Handler和线程Thread放在了一起,我比较喜欢的是,重新启动一个线程非常的方便。

  1. new HandlerThread().start();  

这样一下就可以了,线程已经被启动,而且可以调用HandlerThread类自带的。然后调用getLooper调取线程里的消息循环,送入handleMessage来处理。

getLooper是HandlerThread也是帮我们封装好了的。

如果要自己打包消息循环就可以这样做,JDK文档上就是这么写的:

  1. class LooperThread extends Thread {   
  2.   public Handler mHandler;  
  3.   public void run() {  
  4.   Looper.prepare();   
  5.   mHandler = new Handler() {  
  6.    public void handleMessage(Message msg)  
  7.     {  // process incoming messages here    
  8.     }  
  9.    };  
  10.     Looper.loop();   
  11.  }  
  12. }  

Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped

线程默认是不会有一个与之相关的消息队列,你必须调用prepare()方法来创建,然后用静态方法loop()来将消息加入进去,知道循环的结束。

以上"传统"的方式还是比较的负责,当我们拥有了HandlerThread后一切边的比较的简单了:

  1. HandlerThread ht = new HandlerThread("thread");  
  2. ht.start();  
  3. //ht.getLooper():从名字为thread的线程读取消息循环   
  4. //然后,new myHandler将该消息循环调入Handler中处理,handler读取消息循环里面的消息,handleMessage来分配出来消息   
  5. myHandler h = new myHandler(ht.getLooper());  
  6.           
  7. private class myHandler extends Handler{  
  8.    public myHandler(Looper looper){  
  9.         //super:Use the provided queue instead of the default one.   
  10. //将从“thread”得到的队列来替换默认的队列,应该是加入到替换UI队列,因为这里的handler主线程中的      
  11.         super(looper);  
  12.        }  
  13.         int i = 0 ;  
  14.         @Override  
  15.         public void handleMessage(Message msg){         super.handleMessage(msg);  
  16.                 //do something   
  17.           }  
  18.         }  
  19.         //将线程progressThread添加如线程消息队列   
  20. //这里我理解是将改线程加入整个进程的线程队列中   
  21.         h.post(progressThread);//Causes the Runnable r to be added to the message queue.   
  22. Runnable progressThread = new Runnable(){  
  23.         @Override  
  24.         public void run() {  
  25.             Bundle b =new Bundle();  
  26.             Message msg = h.obtainMessage();  
  27.             b.putInt("a",11);  
  28.             b.putString("b""bbb");  
  29.             msg.setData(b);  
  30.             msg.sendToTarget();  
  31.             try {  
  32.                 Thread.sleep(2000);  
  33.                 h.post(progressThread);  
  34.             } catch (InterruptedException e) {  
  35.                 // TODO Auto-generated catch block   
  36.                 e.printStackTrace();  
  37.             }  
  38.         }  
  39.     };   

一般,情况下这里的东西已经很适用,但是google就是技术届的大哥大,非要把技术更上一层楼,所有有出现了:AsyncTask

这个东西非常的好,比HandlerThread封装的还要厉害。先看代码

  1. package com.test;  
  2.   
  3. import android.app.Activity;  
  4. import android.app.AlertDialog;  
  5. import android.app.AlertDialog.Builder;  
  6. import android.content.DialogInterface;  
  7. import android.os.AsyncTask;  
  8. import android.os.Bundle;  
  9. import android.util.Log;  
  10. import android.view.View;  
  11. import android.view.View.OnClickListener;  
  12. import android.widget.Button;  
  13. import android.widget.EditText;  
  14. import android.widget.LinearLayout;  
  15. import android.widget.TextView;  
  16.   
  17. public class CopyOfAsyncTaskTestActivity extends Activity {  
  18.      
  19.  /** Called when the activity is first created. */  
  20.       
  21.     private TextView ctext ;  
  22.     private Button startButton;  
  23.     private Button endButton;  
  24.       
  25.     @Override  
  26.     public void onCreate(Bundle savedInstanceState) {  
  27.         super.onCreate(savedInstanceState);  
  28.         setContentView(R.layout.main);  
  29.         findViews();  
  30.         ctext.setText("原来是这个");  
  31.         Log.i("System.out""onCreate-->" + Thread.currentThread().getName());  
  32.         startButton.setOnClickListener(new View.OnClickListener() {  
  33.             public void onClick(View v) {  
  34.                 openDialog();  
  35.                 Log.i("System.out""onClick-->" + Thread.currentThread().getName());  
  36.                   
  37.             }  
  38.         });  
  39.     }  
  40.       
  41.       
  42.     private class myAsyncTask extends AsyncTask<String,Void,String>{  
  43.   
  44.         @Override  
  45.         protected String doInBackground(String... params) {  
  46.             // TODO Auto-generated method stub   
  47.               
  48.             Log.i("System.out""doInBackground-->" + Thread.currentThread().getName());  
  49.             return params[0];  
  50.         }  
  51.       
  52.   
  53.         @Override  
  54.         protected void onCancelled() {  
  55.             // TODO Auto-generated method stub   
  56.             super.onCancelled();  
  57.         }  
  58.   
  59.         @Override  
  60.         protected void onPostExecute(String result) {  
  61.             // TODO Auto-generated method stub   
  62.             ctext.setText(result);  
  63.             Log.i("System.out""onPostExecute-->" + Thread.currentThread().getName());  
  64.             super.onPostExecute(result);  
  65.         }  
  66.   
  67.         @Override  
  68.         protected void onPreExecute() {  
  69.             Log.i("System.out""onPreExecute-->" + Thread.currentThread().getName());  
  70.             // TODO Auto-generated method stub   
  71.             super.onPreExecute();  
  72.         }  
  73.   
  74.         @Override  
  75.         protected void onProgressUpdate(Void... values) {  
  76.             // TODO Auto-generated method stub   
  77.             Log.i("System.out""onProgressUpdate-->" + Thread.currentThread().getName());  
  78.             super.onProgressUpdate(values);  
  79.         }  
  80.           
  81.     }  
  82.       
  83.       
  84.     private void openDialog(){  
  85.         final String dialogstr=null;  
  86.         AlertDialog.Builder alert = new AlertDialog.Builder(CopyOfAsyncTaskTestActivity.this);   
  87.         alert.setTitle("请输入");  
  88.         final EditText input = new EditText(CopyOfAsyncTaskTestActivity.this);   
  89.         alert.setView(input);   
  90.         alert.setPositiveButton("Ok",   
  91.                 new DialogInterface.OnClickListener() {   
  92.                 public void onClick(DialogInterface dialog, int whichButton) {   
  93.                     String value = input.getText().toString();   
  94.                     Log.i("System.out""value-->" + value);  
  95.                     new myAsyncTask().execute(value);  
  96.                 }  
  97.         });  
  98.           
  99.         alert.setNegativeButton("Cancel",   
  100.                 new DialogInterface.OnClickListener() {   
  101.                     public void onClick(DialogInterface dialog,int whichButton){  
  102.                           
  103.                     }  
  104.             }  
  105.         );  
  106.         alert.show();   
  107.     }  
  108.       
  109.   
  110.     private void findViews(){  
  111.         ctext=(TextView)findViewById(R.id.ctext);  
  112.         startButton=(Button)findViewById(R.id.startButton);  
  113.         endButton=(Button)findViewById(R.id.endButton);  
  114.     }  
  115.       
  116. }  
  • 1
  • 2
  • 下一页

相关内容