Android 开发中用到的几个多线程解析(代码示例)

来源:互联网 发布:linux用usb无线网卡 编辑:程序博客网 时间:2024/05/22 02:10
 

Android 开发中用到的几个多线程解析(代码示例)

分类: Android 1543人阅读 评论(0) 收藏 举报
多线程androidtimerbuttonnullimage

在开发工程中线程可以帮助我们提高运行速度,Android开发中我知道的线程有四个一个是老生长谈的Thread,第二个是asyncTask,第三个:TimetTask,第四个是Looper,四个多线程各有个的有点,Thread的运行速度是最快的,AsyncTask的规范性是最棒的,其它两个也有自己的优点,下面先贴上三个列子

1.Thread与Handler组合,比较常见

Handler主要是帮助我们来时时更新UI线程

这里在后天加载100张图片,然后没加载完成一个用handler 返回给UI线程一张图片并显示

最后加载完成返回一个List给UI线程 ,Handler就是一个后台线程与UI线程中间的桥梁

[java] view plaincopy
  1. package com.android.wei.thread;  
  2.   
  3. import java.io.InputStream;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import android.app.Activity;  
  8. import android.content.Context;  
  9. import android.graphics.Bitmap;  
  10. import android.graphics.BitmapFactory;  
  11. import android.os.Bundle;  
  12. import android.os.Handler;  
  13. import android.os.Message;  
  14. import android.view.View;  
  15. import android.view.View.OnClickListener;  
  16. import android.widget.Button;  
  17. import android.widget.ImageView;  
  18. import android.widget.TextView;  
  19.   
  20. public class Activity01 extends Activity {  
  21.     /** Called when the activity is first created. */  
  22.     
  23.     /**读取进度**/  
  24.     public final static int LOAD_PROGRESS =0;  
  25.       
  26.     /**标志读取进度结束**/  
  27.     public final static int LOAD_COMPLETE = 1;  
  28.     /**开始加载100张图片按钮**/  
  29.     Button mButton = null;  
  30.       
  31.     /**显示内容**/  
  32.     TextView mTextView = null;  
  33.       
  34.     /**加载图片前的时间**/  
  35.     Long mLoadStart = 0L;  
  36.     /**加载图片完成的时间**/  
  37.     Long mLoadEndt = 0L;  
  38.       
  39.     Context mContext = null;  
  40.     /**图片列表**/  
  41.     private List<Bitmap> list;  
  42.     /**图片容器**/  
  43.     private ImageView mImageView;  
  44.     //接受传过来得消息  
  45.     Handler handler = new Handler(){  
  46.         public void handleMessage(Message msg){  
  47.             switch(msg.what){  
  48.             case LOAD_PROGRESS:  
  49.                 Bitmap bitmap = (Bitmap)msg.obj;  
  50.                 mTextView.setText("当前读取到第"+msg.arg1+"张图片");  
  51.                 mImageView.setImageBitmap(bitmap);  
  52.                 break;  
  53.             case LOAD_COMPLETE:   
  54.                 list = (List<Bitmap>) msg.obj;  
  55.                 mTextView.setText("读取结束一共加载"+list.size()+"图片");  
  56.                 break;  
  57.             }  
  58.             super.handleMessage(msg);  
  59.         }  
  60.     };  
  61.     public void onCreate(Bundle savedInstanceState) {  
  62.         super.onCreate(savedInstanceState);  
  63.         mContext = this;  
  64.         setContentView(R.layout.main);  
  65.         mButton =(Button) findViewById(R.id.button1);  
  66.         mTextView=(TextView) findViewById(R.id.textView1);  
  67.         mImageView =(ImageView) this.findViewById(R.id.imageview);  
  68.         mTextView.setText("点击按钮加载图片");  
  69.         mButton.setOnClickListener(new OnClickListener(){  
  70.             public void onClick(View v){  
  71.                 //调用方法  
  72.                 LoadImage();  
  73.             }  
  74.         });  
  75.               
  76.           
  77.     }  
  78.     public void LoadImage(){  
  79.         new Thread(){  
  80.             public void run(){  
  81.                 mLoadStart = System.currentTimeMillis();  
  82.                 List<Bitmap> list = new ArrayList<Bitmap>();  
  83.                 for(int i =0;i<100;i++){  
  84.                     Bitmap bitmap=ReadBitmap(mContext,R.drawable.icon);  
  85.                     Message msg = new Message();  
  86.                     msg.what = LOAD_PROGRESS;  
  87.                     msg.arg1 = i+1;  
  88.                     list.add(bitmap);  
  89.                     msg.obj = bitmap;  
  90.                     handler.sendMessage(msg);  
  91.                 }  
  92.                 mLoadEndt = System.currentTimeMillis();  
  93.                 Message msg = new Message();  
  94.                 msg.what = LOAD_COMPLETE;  
  95.                 msg.obj=list;  
  96.                 msg.arg1 = (int) (mLoadEndt - mLoadStart);  
  97.                 handler.sendMessage(msg);  
  98.                   
  99.             }  
  100.         }.start();  
  101.     }  
  102.     public Bitmap ReadBitmap(Context context,int resId){  
  103.         BitmapFactory.Options opt = new BitmapFactory.Options();  
  104.         opt.inPreferredConfig = Bitmap.Config.RGB_565;  
  105.         opt.inPurgeable = true;  
  106.         opt.inInputShareable = true;  
  107.         InputStream is = context.getResources().openRawResource(resId);  
  108.         return BitmapFactory.decodeStream(is, null, opt);  
  109.     }  
  110. }  

2. AsyncTask异步多线程

AsyncTask的规范型很强,能够时时反映更新的情况

它一般有这么几个方法

 * onPreExecute(), 该方法将在执行实际的后台操作前被UI 线程调用。可以在该方法中做一些准备工作,如在界面上显示一个进度条,或者一些控件的实例化,这个方法可以不用实现。
       * doInBackground(Params...), 将在onPreExecute 方法执行后马上执行,该方法运行在后台线程中。这里将主要负责执行那些很耗时的后台处理工作。可以调用 publishProgress方法来更新实时的任务进度。该方法是抽象方法,子类必须实现。
      * onProgressUpdate(Progress...),在publishProgress方法被调用后,UI 线程将调用这个方法从而在界面上展示任务的进展情况,例如通过一个进度条进行展示。
      * onPostExecute(Result), 在doInBackground 执行完成后,onPostExecute 方法将被UI 线程调用,后台的计算结果将通过该方法传递到UI 线程,并且在界面上展示给用户.

      * onCancelled(),在用户取消线程操作的时候调用。在主线程中调用onCancelled()的时候调用。

为了正确的使用AsyncTask类,以下是几条必须遵守的准则:

    1) Task的实例必须在UI 线程中创建

    2) execute方法必须在UI 线程中调用

    3) 不要手动的调用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)这几个方法,需要在UI线程中实例化这个task来调用。

    4) 该task只能被执行一次,否则多次调用时将会出现异常

[java] view plaincopy
  1. package com.android.wei.thread;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.InputStream;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7. import java.util.Timer;  
  8. import java.util.TimerTask;  
  9.   
  10. import android.app.Activity;  
  11. import android.content.Context;  
  12. import android.graphics.Bitmap;  
  13. import android.graphics.BitmapFactory;  
  14. import android.os.AsyncTask;  
  15. import android.os.Bundle;  
  16. import android.view.View;  
  17. import android.view.View.OnClickListener;  
  18. import android.widget.Button;  
  19. import android.widget.ImageView;  
  20. import android.widget.TextView;  
  21.   
  22. public class Activity02 extends Activity{  
  23.       
  24.     /**开始StartAsync按钮**/  
  25.     Button mButton = null;  
  26.       
  27.     Context mContext = null;  
  28.       
  29.     //内容显示出来  
  30.     TextView mTextView = null;  
  31.       
  32.     //Timer 对象  
  33.     Timer mTimer = null;  
  34.       
  35.     /** timerTask 对象**/  
  36.     TimerTask mTimerTask = null;  
  37.       
  38.     /**记录TimerId**/  
  39.     int mTimerId =0;  
  40.     /**图片列表**/  
  41.     private List<Bitmap> list;  
  42.     /**图片容器**/  
  43.     private ImageView mImageView;  
  44.     public void onCreate(Bundle s){  
  45.         super.onCreate(s);  
  46.         setContentView(R.layout.main);  
  47.         mContext = this;  
  48.         mButton =(Button) this.findViewById(R.id.button1);  
  49.         mImageView =(ImageView)this.findViewById(R.id.imageview);  
  50.         mTextView =(TextView) this.findViewById(R.id.textView1);  
  51.         mButton.setOnClickListener(new OnClickListener(){  
  52.             public void onClick(View v){  
  53.                 StartAsync();  
  54.             }  
  55.         });  
  56.           
  57.           
  58.     }  
  59.     public void StartAsync(){  
  60.         new AsyncTask<Object,Object,Object>(){  
  61.             protected void onPreExecute(){  
  62.                 //首先执行这个方法,它在UI线程中,可以执行一些异步操作  
  63.                 mTextView.setText("开始加载进度");  
  64.                 super.onPreExecute();  
  65.             }  
  66.             @Override  
  67.             protected Object doInBackground(Object... params) {  
  68.                 // TODO Auto-generated method stub  
  69.                 //异步后台执行,执行完毕可以返回出去一个结果 Object 对象  
  70.                 //得到开始加载得时间  
  71.                 list = new ArrayList<Bitmap>();  
  72.                 for(int i =0;i<100;i++){  
  73.                     Bitmap bitmap =ReadBitmap(mContext,R.drawable.icon);                      
  74.                     final ByteArrayOutputStream os = new ByteArrayOutputStream();  
  75.                     bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);  
  76.                     byte[] image = os.toByteArray();  
  77.                     Bundle bundle = new Bundle();  
  78.                     bundle.putInt("index", i);  
  79.                     bundle.putByteArray("image", image);  
  80.                     publishProgress(bundle);  
  81.                     list.add(bitmap);  
  82.                       
  83.                 }  
  84.                   
  85.                 return list;  
  86.             }  
  87.             protected void onPostExecute(Object result){  
  88.                 //doInBackground 执行之后在这里可以接受到返回结果的对象  
  89.                 List<Bitmap> list = (List<Bitmap>) result;  
  90.                 mTextView.setText("一共加载了"+list.size()+"张图片");  
  91.                super.onPostExecute(result);  
  92.             }  
  93.             protected void onProgressUpdate(Object... values){  
  94.                 //时时拿到当前的进度更新UI  
  95.                 Bundle bundle = (Bundle)values[0];  
  96.                 byte[] image = bundle.getByteArray("image");  
  97.                 Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);  
  98.                 int index = bundle.getInt("index");  
  99.                 mTextView.setText("当前加载进度"+index);  
  100.                 mImageView.setImageBitmap(bitmap);  
  101.                 super.onProgressUpdate(values);  
  102.             }  
  103.               
  104.         }.execute();  
  105.     }  
  106.     public Bitmap ReadBitmap(Context context,int resId){  
  107.         BitmapFactory.Options opt = new BitmapFactory.Options();  
  108.         opt.inPreferredConfig = Bitmap.Config.RGB_565;  
  109.         opt.inPurgeable = true;  
  110.         opt.inInputShareable = true;  
  111.         InputStream is = context.getResources().openRawResource(resId);  
  112.         return BitmapFactory.decodeStream(is, null, opt);  
  113.     }  
  114.       
  115. }  
3. TimerTask
可以根据我们的设置来间隔性的运行,可以很好的实现监听功能一般也跟handler一起

[java] view plaincopy
  1. package com.android.wei.thread;  
  2.   
  3. import java.util.Timer;  
  4. import java.util.TimerTask;  
  5.   
  6. import android.app.Activity;  
  7. import android.content.Context;  
  8. import android.os.Bundle;  
  9. import android.os.Handler;  
  10. import android.os.Message;  
  11. import android.view.View;  
  12. import android.view.View.OnClickListener;  
  13. import android.widget.Button;  
  14. import android.widget.TextView;  
  15.   
  16. public class TimerTaskActivity extends Activity{  
  17.     /**执行Timer进度**/  
  18.     public final static int LOAD_PROGRESS =0;  
  19.       
  20.     /**关闭TImer进度**/  
  21.     public final static int CLOSE_PROGRESS =1;  
  22.       
  23.     /**开始TIMERTASK按钮**/  
  24.     Button mButton0 = null;  
  25.       
  26.     /**关闭TIMERTASK按钮**/  
  27.     Button mButton1 =null;  
  28.       
  29.     /**显示内容**/  
  30.     TextView mTextView = null;  
  31.       
  32.     Context mContext = null;  
  33.       
  34.     /**timer对象**/  
  35.     Timer mTimer = null;  
  36.       
  37.     /**TimerTask对象**/  
  38.     TimerTask mTimerTask = null;  
  39.       
  40.     /**记录TimerID**/  
  41.     int mTimerID =0;  
  42.       
  43.     Handler handler = new Handler(){  
  44.         public void handleMessage(Message msg){  
  45.             switch(msg.what){  
  46.             case LOAD_PROGRESS:  
  47.                 mTextView.setText("当前得TimerID为:"+msg.arg1);  
  48.                 break;  
  49.             case CLOSE_PROGRESS:  
  50.                 mTextView.setText("当前Timer已经关闭请重新启动");  
  51.                 break;  
  52.             }  
  53.             super.handleMessage(msg);  
  54.         }  
  55.     };  
  56.     protected void onCreate(Bundle s){  
  57.         setContentView(R.layout.timer);  
  58.         mContext  = this;  
  59.         mButton0 = (Button) this.findViewById(R.id.button1);  
  60.         mButton1 = (Button) this.findViewById(R.id.button2);  
  61.         mTextView = (TextView) this.findViewById(R.id.textView1);  
  62.         mTextView.setText("点击按钮开始更新时间");  
  63.         mButton0.setOnClickListener(new OnClickListener(){  
  64.             public void onClick(View v){  
  65.                 StartTimer();  
  66.             }  
  67.         });  
  68.         mButton1.setOnClickListener(new OnClickListener(){  
  69.             public void onClick(View v){  
  70.                 CloseTimer();  
  71.             }  
  72.         });  
  73.         super.onCreate(s);  
  74.     }  
  75.    public void StartTimer(){  
  76.         if(mTimer == null){  
  77.             mTimerTask = new TimerTask(){  
  78.   
  79.                 @Override  
  80.                 public void run() {  
  81.                     mTimerID ++;  
  82.                     Message msg = new Message();  
  83.                     msg.what = LOAD_PROGRESS;  
  84.                     msg.arg1 =(int) (mTimerID);  
  85.                     handler.sendMessage(msg);  
  86.                       
  87.                 }             
  88.                   
  89.             };  
  90.             mTimer = new Timer();  
  91.             //第一个参数为执行的mTimerTask  
  92.             //第二个参数为延迟得事件,这里写1000得意思是 mTimerTask将延迟1秒执行  
  93.             //第三个参数为多久执行一次,这里写1000 表示没1秒执行一次mTimerTask的Run方法  
  94.             mTimer.schedule(mTimerTask, 1000,1000);  
  95.         }  
  96.    }  
  97.    public void CloseTimer(){  
  98.        if(mTimer !=null){  
  99.            mTimer.cancel();  
  100.            mTimer = null;  
  101.        }  
  102.        if(mTimerTask!= null){  
  103.            mTimerTask = null;  
  104.        }  
  105.        mTimerID =0;  
  106.        handler.sendEmptyMessage(CLOSE_PROGRESS);  
  107.    }  
  108. }  






0 0
原创粉丝点击