日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Android開發(fā)中AsyncTask實(shí)現(xiàn)異步處理任務(wù)的方法

我們報(bào)道過Android單線程模型相關(guān)概念詳解,在開發(fā)Android應(yīng)用時(shí)必須遵守單線程模型的原則:Android UI操作并不是線程安全的并且這些操作必須在UI線程中執(zhí)行。

在單線程模型中始終要記住兩條法則:

不要阻塞UI線程

確保只在UI線程中訪問Android UI工具包

當(dāng)一個(gè)程序第一次啟動(dòng)時(shí),Android會(huì)同時(shí)啟動(dòng)一個(gè)對應(yīng)的主線程(Main Thread),主線程主要負(fù)責(zé)處理與UI相關(guān)的事件,如:用戶的按鍵事件,用戶接觸屏幕的事件以及屏幕繪圖事件,并把相關(guān)的事件分發(fā)到對應(yīng)的組件進(jìn)行處理。所以主線程通常又被叫做UI線程。

比如說從網(wǎng)上獲取一個(gè)網(wǎng)頁,在一個(gè)TextView中將其源代碼顯示出來,這種涉及到網(wǎng)絡(luò)操作的程序一般都是需要開一個(gè)線程完成網(wǎng)絡(luò)訪問,但是在獲得頁面源碼后,是不能直接在網(wǎng)絡(luò)操作線程中調(diào)用TextView.setText()的.因?yàn)槠渌€程中是不能直接訪問主UI線程成員

Android提供了幾種在其他線程中訪問UI線程的方法。

 
 
 
  1. Activity.runOnUiThread( Runnable ) 
  2. View.post( Runnable ) 
  3. View.postDelayed( Runnable, long ) 
  4. Hanlder 

這些類或方法同樣會(huì)使你的代碼很復(fù)雜很難理解。然而當(dāng)你需要實(shí)現(xiàn)一些很復(fù)雜的操作并需要頻繁地更新UI時(shí)這會(huì)變得更糟糕。

為了解決這個(gè)問題,Android 1.5提供了一個(gè)工具類:AsyncTask,它使創(chuàng)建需要與用戶界面交互的長時(shí)間運(yùn)行的任務(wù)變得更簡單。不需要借助線程和Handler即可實(shí)現(xiàn)。

AsyncTask是抽象類.AsyncTask定義了三種泛型類型 Params,Progress和Result。

◆Params 啟動(dòng)任務(wù)執(zhí)行的輸入?yún)?shù),比如HTTP請求的URL。

◆Progress 后臺(tái)任務(wù)執(zhí)行的百分比。

◆Result 后臺(tái)執(zhí)行任務(wù)最終返回的結(jié)果,比如String。

AsyncTask的執(zhí)行分為四個(gè)步驟,每一步都對應(yīng)一個(gè)回調(diào)方法,這些方法不應(yīng)該由應(yīng)用程序調(diào)用,開發(fā)者需要做的就是實(shí)現(xiàn)這些方法。

子類化AsyncTask

實(shí)現(xiàn)AsyncTask中定義的下面一個(gè)或幾個(gè)方法

onPreExecute(), 該方法將在執(zhí)行實(shí)際的后臺(tái)操作前被UI thread調(diào)用。可以在該方法中做一些準(zhǔn)備工作,如在界面上顯示一個(gè)進(jìn)度條。

doInBackground(Params...), 將在onPreExecute 方法執(zhí)行后馬上執(zhí)行,該方法運(yùn)行在后臺(tái)線程中。這里將主要負(fù)責(zé)執(zhí)行那些很耗時(shí)的后臺(tái)計(jì)算工作??梢哉{(diào)用 publishProgress方法來更新實(shí)時(shí)的任務(wù)進(jìn)度。該方法是抽象方法,子類必須實(shí)現(xiàn)。

onProgressUpdate(Progress...),在publishProgress方法被調(diào)用后,UI thread將調(diào)用這個(gè)方法從而在界面上展示任務(wù)的進(jìn)展情況,例如通過一個(gè)進(jìn)度條進(jìn)行展示。

onPostExecute(Result), 在doInBackground 執(zhí)行完成后,onPostExecute 方法將被UI thread調(diào)用,后臺(tái)的計(jì)算結(jié)果將通過該方法傳遞到UI thread.

為了正確的使用AsyncTask類,以下是幾條必須遵守的準(zhǔn)則:

1) Task的實(shí)例必須在UI thread中創(chuàng)建

2) execute方法必須在UI thread中調(diào)用

3) 不要手動(dòng)的調(diào)用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)這幾個(gè)方法

4) 該task只能被執(zhí)行一次,否則多次調(diào)用時(shí)將會(huì)出現(xiàn)異常

從網(wǎng)上獲取一個(gè)網(wǎng)頁,在一個(gè)TextView中將其源代碼顯示出來

 
 
 
  1. package test.list;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.InputStream;
  4. import java.util.ArrayList;
  5. import org.apache.http.HttpEntity;
  6. import org.apache.http.HttpResponse;
  7. import org.apache.http.client.HttpClient;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.impl.client.DefaultHttpClient;
  10. import android.app.Activity;
  11. import android.app.ProgressDialog;
  12. import android.content.Context;
  13. import android.content.DialogInterface;
  14. import android.os.AsyncTask;
  15. import android.os.Bundle;
  16. import android.os.Handler;
  17. import android.os.Message;
  18. import android.view.View;
  19. import android.widget.Button;
  20. import android.widget.EditText;
  21. import android.widget.TextView;
  22. public class NetworkActivity extends Activity{
  23.  private TextView message;
  24.     private Button open;
  25.     private EditText url;
  26.     @Override
  27.     public void onCreate(Bundle savedInstanceState) {
  28.        super.onCreate(savedInstanceState);
  29.        setContentView(R.layout.network);
  30.        message= (TextView) findViewById(R.id.message);
  31.        url= (EditText) findViewById(R.id.url);
  32.        open= (Button) findViewById(R.id.open);
  33.        open.setOnClickListener(new View.OnClickListener() {
  34.            public void onClick(View arg0) {
  35.               connect();
  36.            }
  37.        });
  38.     }
  39.     private void connect() {
  40.      PageTask task = new PageTask(this);
  41.         task.execute(url.getText().toString());
  42.     }
  43.     class PageTask extends AsyncTask, Integer, String> {
  44.         // 可變長的輸入?yún)?shù),與AsyncTask.exucute()對應(yīng)
  45.      ProgressDialog pdialog;
  46.         public PageTask(Context context){
  47.          pdialog = new ProgressDialog(context, 0);   
  48.          pdialog.setButton("cancel", new DialogInterface.OnClickListener() {
  49.           public void onClick(DialogInterface dialog, int i) {
  50.            dialog.cancel();
  51.           }
  52.          });
  53.          pdialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
  54.           public void onCancel(DialogInterface dialog) {
  55.            finish();
  56.           }
  57.          });
  58.          pdialog.setCancelable(true);
  59.          pdialog.setMax(100);
  60.          pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  61.          pdialog.show();
  62.         }
  63.         @Override
  64.         protected String doInBackground(String... params) {
  65.             try{
  66.                HttpClient client = new DefaultHttpClient();
  67.                // params[0]代表連接的url
  68.                HttpGet get = new HttpGet(params[0]);
  69.                HttpResponse response = client.execute(get);
  70.                HttpEntity entity = response.getEntity();
  71.                long length = entity.getContentLength();
  72.                InputStream is = entity.getContent();
  73.                String s = null;
  74.                if(is != null) {
  75.                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
  76.                    byte[] buf = new byte[128];
  77.                    int ch = -1;
  78.                    int count = 0;
  79.                    while((ch = is.read(buf)) != -1) {
  80.                       baos.write(buf, 0, ch);
  81.                       count += ch;
  82.                       if(length > 0) {
  83.                           // 如果知道響應(yīng)的長度,調(diào)用publishProgress()更新進(jìn)度
  84.                           publishProgress((int) ((count / (float) length) * 100));
  85.                       }
  86.                       // 讓線程休眠100ms
  87.                       Thread.sleep(100);
  88.                    }
  89.                    s = new String(baos.toByteArray());              }
  90.                // 返回結(jié)果
  91.                return s;
  92.             } catch(Exception e) {
  93.                e.printStackTrace();
  94.             }
  95.             return null;
  96.         }
  97.         @Override
  98.         protected void onCancelled() {
  99.             super.onCancelled();
  100.         }
  101.         @Override
  102.         protected void onPostExecute(String result) {
  103.             // 返回HTML頁面的內(nèi)容
  104.             message.setText(result);
  105.             pdialog.dismiss(); 
  106.         }
  107.         @Override
  108.         protected void onPreExecute() {
  109.             // 任務(wù)啟動(dòng),可以在這里顯示一個(gè)對話框,這里簡單處理
  110.             message.setText(R.string.task_started);
  111.         }
  112.         @Override
  113.         protected void onProgressUpdate(Integer... values) {
  114.             // 更新進(jìn)度
  115.               System.out.println(""+values[0]);
  116.               message.setText(""+values[0]);
  117.               pdialog.setProgress(values[0]);
  118.         }
  119.      }
  120. }

名稱欄目:Android開發(fā)中AsyncTask實(shí)現(xiàn)異步處理任務(wù)的方法
網(wǎng)頁URL:http://www.5511xx.com/article/cogiihs.html