An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params
, Progress
and Result
, and 4 steps, called onPreExecute
, doInBackground
, onProgressUpdate
and onPostExecute
.
Params
, the type of the parameters sent to the task upon execution. //输入参数Progress
, the type of the progress units published during the background computation. //单元参数格式Result
, the type of the result of the background computation.//返回参数Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type
Void
:private class MyTask extends AsyncTask<Void, Void, Void> { ... }
package com.example.android_asynctask; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import com.example.android_asynctask.R.string; import android.R.id; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.app.ProgressDialog; import android.content.Entity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.Menu; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { private Button button; private ImageView imageView; private ProgressDialog progressDialog; private final String image_path="http://www.baidu.com/img/bdlogo.gif"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=(Button)this.findViewById(R.id.button1); imageView=(ImageView)this.findViewById(R.id.imageView1); progressDialog=new ProgressDialog(this); progressDialog.setTitle("提示!"); progressDialog.setCancelable(false); progressDialog.setMessage("正在下载图片,请耐心等候~~~"); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub new MyTast().execute(image_path); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } class MyTast extends AsyncTask<String, Integer, byte[]>{ @Override protected byte[] doInBackground(String... arg0) { // TODO Auto-generated method stub HttpClient httpClient=new DefaultHttpClient(); HttpGet httpGet =new HttpGet(arg0[0]); byte[] result=null; try { HttpResponse httpResponse=httpClient.execute(httpGet); if(httpResponse.getStatusLine().getStatusCode()==200){ result=EntityUtils.toByteArray(httpResponse.getEntity()); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ httpClient.getConnectionManager().shutdown(); } return result; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); progressDialog.show(); } //更新ui @Override protected void onPostExecute(byte[] result) { // TODO Auto-generated method stub super.onPostExecute(result); Bitmap bitmap=BitmapFactory.decodeByteArray(result, 0,result.length); imageView.setImageBitmap(bitmap); progressDialog.dismiss(); } } }
必须要添加访问授权<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.android_asynctask.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
跨线程更新UI的方法在onPostExecute中持行
onProgressUpdate使用AsyncTask的单元参数Progress
package com.example.android_asynctask; import java.io.ByteArrayOutputStream; import java.io.InputStream; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import com.example.android_asynctask.R.string; import android.R.id; import android.R.integer; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Entity; import android.database.DatabaseUtils; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.Menu; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { private Button button; private ImageView imageView; private ProgressDialog progressDialog; private final String image_path="http://www.baidu.com/img/bdlogo.gif"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=(Button)this.findViewById(R.id.button1); imageView=(ImageView)this.findViewById(R.id.imageView1); progressDialog=new ProgressDialog(this); progressDialog.setTitle("提示!"); progressDialog.setCancelable(false); progressDialog.setMessage("正在下载图片,请耐心等候~~~"); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub new MyTast().execute(image_path); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } class MyTast extends AsyncTask<String, Integer, byte[]>{ @Override protected byte[] doInBackground(String... arg0) { // TODO Auto-generated method stub HttpClient httpClient=new DefaultHttpClient(); HttpGet httpGet =new HttpGet(arg0[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 process_value=(int)((total_length/(float)file_length)*100); publishProgress(process_value);//发布刻度单位 outputStream.write(data,0,len); } } result=outputStream.toByteArray(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ httpClient.getConnectionManager().shutdown(); } return result; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); progressDialog.show(); } //更新ui @Override protected void onPostExecute(byte[] result) { // TODO Auto-generated method stub super.onPostExecute(result); Bitmap bitmap=BitmapFactory.decodeByteArray(result, 0,result.length); imageView.setImageBitmap(bitmap); progressDialog.dismiss(); } @Override protected void onProgressUpdate(Integer... values) { // TODO Auto-generated method stub super.onProgressUpdate(values); progressDialog.setProgress(values[0]); } } }