亚洲AVI,黑人巨茎大战欧美白妇,初高中生洗澡自慰高清网站,欧美日韩无砖专区一中文字

重慶分公司,新征程啟航

為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)

AsyncTask的用法

Android提供了幾種在其他線程中訪問(wèn)UI線程的方法。
Activity.runOnUiThread( Runnable )
View.post( Runnable )
View.postDelayed( Runnable, long )
Hanlder

成都創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比馬山網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫(kù),直接使用。一站式馬山網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋馬山地區(qū)。費(fèi)用合理售后完善,十余年實(shí)體公司更值得信賴。


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

     為了解決這個(gè)問(wèn)題,Android 1.5提供了一個(gè)工具類:AsyncTask,它使創(chuàng)建需要與用戶界面交互的長(zhǎng)時(shí)間運(yùn)行的任務(wù)變得更簡(jiǎn)單。相對(duì)來(lái)說(shuō)AsyncTask更輕量級(jí)一些,適用于簡(jiǎn)單的異步處理,不需要借助線程和Handler即可實(shí)現(xiàn)。
AsyncTask是抽象類.AsyncTask定義了三種泛型類型 Params,Progress和Result。
  Params 啟動(dòng)任務(wù)執(zhí)行的輸入?yún)?shù),比如HTTP請(qǐng)求的URL。
  Progress 后臺(tái)任務(wù)執(zhí)行的百分比。
  Result 后臺(tái)執(zhí)行任務(wù)最終返回的結(jié)果,比如String。

     AsyncTask的執(zhí)行分為四個(gè)步驟,每一步都對(duì)應(yīng)一個(gè)回調(diào)方法,這些方法不應(yīng)該由應(yīng)用程序調(diào)用,開發(fā)者需要做的就是實(shí)現(xiàn)這些方法。
  1) 子類化AsyncTask
  2) 實(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方法來(lái)更新實(shí)時(shí)的任務(wù)進(jìn)度。該方法是抽象方法,子類必須實(shí)現(xiàn)。
    onProgressUpdate(Progress...),在publishProgress方法被調(diào)用后,UI thread將調(diào)用這個(gè)方法從而在界面上展示任務(wù)的進(jìn)展情況,例如通過(guò)一個(gè)進(jìn)度條進(jìn)行展示。
    onPostExecute(Result), 在doInBackground 執(zhí)行完成后,onPostExecute 方法將被UI thread調(diào)用,后臺(tái)的計(jì)算結(jié)果將通過(guò)該方法傳遞到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)異常
      doInBackground方法和onPostExecute的參數(shù)必須對(duì)應(yīng),這兩個(gè)參數(shù)在AsyncTask聲明的泛型參數(shù)列表中指定,第一個(gè)為doInBackground接受的參數(shù),第二個(gè)為顯示進(jìn)度的參數(shù),第第三個(gè)為doInBackground返回和onPostExecute傳入的參數(shù)。


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

AsyncTask的用法

package test.list;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class NetworkActivity extends Activity{
    private TextView message;
    private Button open;
    private EditText url;

    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.network);
       message= (TextView) findViewById(R.id.message);
       url= (EditText) findViewById(R.id.url);
       open= (Button) findViewById(R.id.open);
       open.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {
              connect();
           }
       });

    }

    private void connect() {
        PageTask task = new PageTask(this);
        task.execute(url.getText().toString());
    }


    class PageTask extends AsyncTask {
        // 可變長(zhǎng)的輸入?yún)?shù),與AsyncTask.exucute()對(duì)應(yīng)
        ProgressDialog pdialog;
        public PageTask(Context context){
            pdialog = new ProgressDialog(context, 0);   
            pdialog.setButton("cancel", new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int i) {
              dialog.cancel();
             }
            });
            pdialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
             public void onCancel(DialogInterface dialog) {
              finish();
             }
            });
            pdialog.setCancelable(true);
            pdialog.setMax(100);
            pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pdialog.show();


        }
        @Override
        protected String doInBackground(String... params) {

            try{

               HttpClient client = new DefaultHttpClient();
               // params[0]代表連接的url
               HttpGet get = new HttpGet(params[0]);
               HttpResponse response = client.execute(get);
               HttpEntity entity = response.getEntity();
               long length = entity.getContentLength();
               InputStream is = entity.getContent();
               String s = null;
               if(is != null) {
                   ByteArrayOutputStream baos = new ByteArrayOutputStream();

                   byte[] buf = new byte[128];

                   int ch = -1;

                   int count = 0;

                   while((ch = is.read(buf)) != -1) {

                      baos.write(buf, 0, ch);

                      count += ch;

                      if(length > 0) {
                          // 如果知道響應(yīng)的長(zhǎng)度,調(diào)用publishProgress()更新進(jìn)度
                          publishProgress((int) ((count / (float) length) * 100));
                      }

                      // 讓線程休眠100ms
                      Thread.sleep(100);
                   }
                   s = new String(baos.toByteArray());              }
               // 返回結(jié)果
               return s;
            } catch(Exception e) {
               e.printStackTrace();

            }

            return null;

        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected void onPostExecute(String result) {
            // 返回HTML頁(yè)面的內(nèi)容
            message.setText(result);
            pdialog.dismiss(); 
        }

        @Override
        protected void onPreExecute() {
            // 任務(wù)啟動(dòng),可以在這里顯示一個(gè)對(duì)話框,這里簡(jiǎn)單處理
            message.setText(R.string.task_started);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            // 更新進(jìn)度
              System.out.println(""+values[0]);
              message.setText(""+values[0]);
              pdialog.setProgress(values[0]);
        }

     }

}
 

最后需要說(shuō)明AsyncTask不能完全取代線程,在一些邏輯較為復(fù)雜或者需要在后臺(tái)反復(fù)執(zhí)行的邏輯就可能需要線程來(lái)實(shí)現(xiàn)了。


當(dāng)前標(biāo)題:AsyncTask的用法
網(wǎng)頁(yè)鏈接:http://news.spvevtbd.cn/article/pghjii.html

其他資訊

在線咨詢
服務(wù)熱線
服務(wù)熱線:028-86922220
TOP