以前觉得异步任务超级高大上啊,看书上的知识点都有恐惧感,一直没看,想开耗时任务的时候一直用的线程类,现在才发现,异步任务比工作线程简单多了~下面来一个例子,说明下异步任务的用法:
首先我们需要一个Interface:AsyncTask,这是一个接口,不能直接实例化的,所以需要自己创建一个它的子类,MyTask,然后重写父类接口中定义的四个函数。而AsyncTask本身带三个参数:<<span style=”background-color: rgb(247, 247, 247); color: rgb(34, 34, 34);”>Params, Progress, Result>,<>表示泛型,大家应该造哦,我这个小白白都造呢~然后Params参数表示传入这个异步任务待处理的数据,Progress表示进度条的进度值,Result表示处理结果;这里根据实际我将要完成的任务,我将这三个参数的具体类型设为。
下面是具体实现:
/************这个代码从Eclipse复制过来它就没了格式,小白我已经Tab无力了。。微博这个还不能好多行一起Tab。。整洁癖怎么忍。。忍忍吧,老板都忍了,微博这么可爱,干嘛不忍~~***************/
- package
com.example.android_asynctask; -
- public
class MainActivity extends Activity { - private
Button button ; - private
ImageView imageView;//这个放图片的~ - private
ProgressDialog dialog;//进度条对话框,认识哦~ -
- @Override
- protected
void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- button
= (Button)findViewById(R.id.button1); - imageView
= (ImageView)findViewById(R.id.imageView1); - //对话框参数
- dialog
= new ProgressDialog(this); - dialog.setTitle(“提示”);
- dialog.setMessage(“正在下载图片”);
- dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- //图片地址哦,是一件衣服嘿嘿~
- final
String IMAGE_PATH = “http://a.vpimg1.com/upload/merchandise/201408/2014082111114539470.jpg”; - button.setOnClickListener(new
View.OnClickListener() { - @Override
- public
void onClick(View arg0) { - //
TODO Auto-generated method stub - new
MyTask().execute(IMAGE_PATH); - }
- });
- }
- public
class MyTask extends AsyncTask<</span>String, Integer, byte[]> { -
- //最后被执行, 更新UI,不一定需要的
- @Override
- protected
void onPostExecute(byte[] result) { - super.onPostExecute(result);
- Bitmap
bitmap = BitmapFactory.decodeByteArray(result,0, result.length); - imageView.setImageBitmap(bitmap);
- dialog.dismiss();
- }
-
//这四个函数执行还是有顺序的,这是第一个被执行的,pre嘛,这里就是显示了一下进度条的对话框 - @Override
- protected
void onPreExecute() { - //
该函数用来显示提示框,如果没有需要,则不需要调用 - super.onPreExecute();
- dialog.show();
- }
-
//第三个被执行,更新进度条 - @Override
- protected
void onProgressUpdate(Integer… values) { - //
更新进度条 - super.onProgressUpdate(values);
- dialog.setProgress(values[0]);
- }
-
- //这是第二个,拿到待处理参数,这里就是String类型的Image地址啦
- @Override
- protected
byte[] doInBackground(String… params) { - // Http这个怎么个处理过程,我还母鸡:-(。。
- HttpClient
httpClient = new DefaultHttpClient(); - HttpGet
httpGet = new HttpGet(params[0]); - byte[]
result = null; - // 传输流
- InputStream
inputStream =null; - ByteArrayOutputStream
outputStream = new ByteArrayOutputStream(); - try
{ - HttpResponse
httpResponse = httpClient.execute(httpGet); - long
file_length = httpResponse.getEntity().getContentLength();//文件总长度 - int
total_length = 0; - byte[]
data = new byte[1024]; - int
len = 0; -
- if(httpResponse.getStatusLine().getStatusCode()==200){
- // result
= EntityUtils.toByteArray(httpResponse.getEntity()); -
- inputStream
= httpResponse.getEntity().getContent(); - while((len
= inputStream.read(data))!=-1){ - total_length
+= len; - int
progress_value = (int)(total_length/(float)file_length*100); - publishProgress(progress_value);
- outputStream.write(data,0,len);
- }
- }
- result
= outputStream.toByteArray(); -
- }
catch (Exception e) { - e.printStackTrace();
- }finally{
- httpClient.getConnectionManager().shutdown();
- }
- return
result; - }
- }
- }