android非同步任務學習筆記

來源:互聯網
上載者:User

標籤:非同步   android   線程   使用者體驗   

android非同步任務可以很方便的完成耗時操作並更新UI,不像多線程還要利用訊息佇列,子線程發訊息給主線程,主線程才能更新UI。總之,android非同步任務把多線程的互動進行進一步的封裝,用起來跟方便。

如下是非同步任務demo代碼:

完成非同步下載圖片,更新介面。

package com.example.android_async_task2;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import android.app.Activity;import android.app.ProgressDialog;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.AsyncTask;import android.os.Bundle;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;public class MainActivity extends Activity {private Button btn=null;private ImageView image=null;private String image_path="http://f2.sjbly.cn/m13/0729/1459/6947edn_690x459_b.jpg";private ProgressDialog dialog;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn=(Button)this.findViewById(R.id.button1);dialog=new ProgressDialog(this);dialog.setTitle("提示資訊");dialog.setMessage("下載中,請稍等......");//設定進度條的樣式dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//螢幕不失去焦點dialog.setCancelable(false);image=(ImageView)this.findViewById(R.id.imageView1);btn.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {new MyTask().execute(image_path);}});}public class MyTask extends AsyncTask<String,Integer,Bitmap>{@Overrideprotected void onPreExecute() {dialog.show();super.onPreExecute();}@Overrideprotected Bitmap doInBackground(String... params) {//定義一個記憶體流,不需要關閉ByteArrayOutputStream out= new ByteArrayOutputStream();//定義一個輸入資料流InputStream in=null;Bitmap bitmap=null;//通過HttpClient類擷取網路資源HttpClient httpClient=new DefaultHttpClient();//佈建要求方式(注意請求地址URL要寫入!!!)HttpGet httpGet=new HttpGet(params[0]);try {//獲得請求狀態HttpResponse httpResponse=httpClient.execute(httpGet);//判斷請求狀態結果碼if(httpResponse.getStatusLine().getStatusCode()==200){/*//通過一個實體類獲得響應的實體HttpEntity httpEntity=httpResponse.getEntity();//通過一個實體工具類獲得實體的位元組數組byte[]data=EntityUtils.toByteArray(httpEntity);//通過工廠類建立Bitmap對象BitmapFactory.decodeByteArray(data, 0, data.length);*///獲得輸入資料流in=httpResponse.getEntity().getContent();//獲得檔案的總長度long file_length=httpResponse.getEntity().getContentLength();//計算總長度int total_len=0;int len=0;byte[] buffer=new byte[1024];try{while((len=in.read(buffer))!=-1){total_len+=len;<span style="color:#ff0000;">//刻度計算公式</span>int value=(int)(total_len/((float)file_length)*100);<span style="color:#ff6666;">//發布進度條的刻度</span>publishProgress(value);//寫入輸出資料流out.write(buffer, 0, len);}//記憶體輸出資料流轉換成位元組數組bitmap=BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.toByteArray().length);}catch(Exception e){}finally{if(in!=null){in.close();}}}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return bitmap;}@Overrideprotected void onPostExecute(Bitmap result) {super.onPostExecute(result);image.setImageBitmap(result);dialog.dismiss();}@Overrideprotected void onProgressUpdate(Integer... values) {super.onProgressUpdate(values);dialog.setProgress(values[0]);}}@Overridepublic 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;}}
其中
publishProgress(value);
是可以發送幾個對象給
onProgressUpdate()方法的。

DEMO下載:http://download.csdn.net/detail/u014600432/8175337

android非同步任務學習筆記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.