AsyncTask:是Android提供的輕量級的異步類,能夠直接繼承AsyncTask,在類中實現異步操做,並提供接口反饋當前異步執行的程度(能夠經過接口實現UI進度更新),最後反饋執行的結果給UI主線程。html
AsyncTask (異步任務),從字面上來講,就是在咱們的UI主線程運行的時候,異步的完成一些操做。AsyncTask容許咱們的執行一個異步的任務在後臺。咱們能夠將耗時的操做放在異步任務當中來執行,並隨時將任務執行的結果返回給咱們的UI線程來更新咱們的UI控件。經過AsyncTask咱們能夠輕鬆的解決多線程之間的通訊問題。java
4個步驟:當咱們執行一個異步任務的時候,其須要按照下面的4個步驟分別執行android
一個超簡單的理解 AsyncTask 的例子:AsyncTask來從網絡上加載一張圖片git
Activity代碼:github
private Button btn; private ImageViewimageView; privateProgressDialog progressDialog; private final String IMGURL= "http://img0.pconline.com.cn/pconline/1206/18/2829090_3867bd63fd673471aa184c02_500.jpg"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.asynctask_img); btn=(Button)findViewById(R.id.buttonOnClicksAsyncTask); imageView =(ImageView)findViewById(R.id.imageViewss); progressDialog = newProgressDialog(this); progressDialog.setTitle("提示信息"); progressDialog.setMessage("正在下載中,請稍後......"); progressDialog.setCancelable(false); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); btn.setOnClickListener(newView.OnClickListener() { @Override public voidonClick(View v) { // 在UI Thread當中實例化AsyncTask對象,並調用execute方法 newMAsyncTask().execute(IMGURL); } }); } public class MAsyncTask extends AsyncTask<String, Integer, byte[]> { @Override protected voidonPreExecute() { super.onPreExecute(); progressDialog.show(); } @Override protected byte[]doInBackground(String... params) { HttpClient httpClient = newDefaultHttpClient(); HttpGet httpGet = newHttpGet(params[0]); byte[] image =new byte[]{}; try { HttpResponse httpResponse =httpClient.execute(httpGet); HttpEntity httpEntity =httpResponse.getEntity(); if(httpEntity!= null &&httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { image = EntityUtils.toByteArray(httpEntity); } } catch(Exception e) { e.printStackTrace(); } finally { httpClient.getConnectionManager().shutdown(); } return image; } @Override protected voidonProgressUpdate(Integer... values) { super.onProgressUpdate(values); } @Override protected voidonPostExecute(byte[] result) { super.onPostExecute(result); // 將doInBackground方法返回的byte[]解碼成要給Bitmap Bitmap bitmap = BitmapFactory.decodeByteArray(result,0, result.length); // 更新咱們的ImageView控件 imageView.setImageBitmap(bitmap); progressDialog.dismiss(); } } }
一個ImageView控件和一個Button控件,當點擊Button控件時,彈出一個ProgressDialog,而後開啓一個異步任務,從網絡中下載一張圖片,並更新到咱們的ImageView上。這裏還要注意一點,若是咱們要訪問網絡,必須還要給其受權才行網絡
AndroidManifest.xml文件:多線程
<uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".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>
效果圖:app
源碼下載:異步
AndroidStudio下載: https://github.com/DickyQie/AsynTaskDemo.gitasync