中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

Android中AsyncTask使用實(shí)例

2018-07-20    來(lái)源:open-open

容器云強(qiáng)勢(shì)上線!快速搭建集群,上萬(wàn)Linux鏡像隨意使用

MainActivity如下:

package com.example.asynctasktest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
    private Button satrtButton;
    private Button cancelButton;
    private ProgressBar progressBar;
    private TextView textView;
    private DownLoaderAsyncTask downLoaderAsyncTask;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initView();
    }
    public void initView() {
        satrtButton=(Button) findViewById(R.id.startButton);
        cancelButton=(Button) findViewById(R.id.cancelButton);
        satrtButton.setOnClickListener(new ButtonOnClickListener());
        cancelButton.setOnClickListener(new ButtonOnClickListener());
        progressBar=(ProgressBar) findViewById(R.id.progressBar);
        textView=(TextView) findViewById(R.id.textView);
    }
   private class ButtonOnClickListener implements OnClickListener{
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.startButton:
                //注意:
                //1 每次需new一個(gè)實(shí)例,新建的任務(wù)只能執(zhí)行一次,否則會(huì)出現(xiàn)異常
                //2 異步任務(wù)的實(shí)例必須在UI線程中創(chuàng)建
                //3 execute()方法必須在UI線程中調(diào)用。
                downLoaderAsyncTask=new DownLoaderAsyncTask();
                downLoaderAsyncTask.execute("http://www.baidu.com");
                break;
            case R.id.cancelButton:
                //取消一個(gè)正在執(zhí)行的任務(wù),onCancelled()方法將會(huì)被調(diào)用   
                downLoaderAsyncTask.cancel(true);
                break;
            default:
                break;
            }
        }

   }
   //構(gòu)造函數(shù)AsyncTask<Params, Progress, Result>參數(shù)說(shuō)明: 
   //Params   啟動(dòng)任務(wù)執(zhí)行的輸入?yún)?shù)
   //Progress 后臺(tái)任務(wù)執(zhí)行的進(jìn)度
   //Result   后臺(tái)計(jì)算結(jié)果的類(lèi)型
   private class DownLoaderAsyncTask extends AsyncTask<String, Integer, String>{
    //onPreExecute()方法用于在執(zhí)行異步任務(wù)前,主線程做一些準(zhǔn)備工作   
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        textView.setText("調(diào)用onPreExecute()方法--->準(zhǔn)備開(kāi)始執(zhí)行異步任務(wù)");
        System.out.println("調(diào)用onPreExecute()方法--->準(zhǔn)備開(kāi)始執(zhí)行異步任務(wù)");
    }

    //doInBackground()方法用于在執(zhí)行異步任務(wù),不可以更改主線程中UI 
    @Override
    protected String doInBackground(String... params) {
       System.out.println("調(diào)用doInBackground()方法--->開(kāi)始執(zhí)行異步任務(wù)");
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(params[0]);
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                long total = entity.getContentLength();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int count = 0;
                int length = -1;
                while ((length = is.read(buffer)) != -1) {
                    bos.write(buffer, 0, length);
                    count += length;
                    //publishProgress()為AsyncTask類(lèi)中的方法
                    //常在doInBackground()中調(diào)用此方法
                    //用于通知主線程,后臺(tái)任務(wù)的執(zhí)行情況.
                    //此時(shí)會(huì)觸發(fā)AsyncTask中的onProgressUpdate()方法
                    publishProgress((int) ((count / (float) total) * 100));
                    //為了演示進(jìn)度,休眠1000毫秒
                    Thread.sleep(1000);
                }
                return new String(bos.toByteArray(), "UTF-8");
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

    //onPostExecute()方法用于異步任務(wù)執(zhí)行完成后,在主線程中執(zhí)行的操作
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);    
        Toast.makeText(getApplicationContext(), "調(diào)用onPostExecute()方法--->異步任務(wù)執(zhí)行完畢", 0).show();
        //textView顯示網(wǎng)絡(luò)請(qǐng)求結(jié)果
        textView.setText(result);
        System.out.println("調(diào)用onPostExecute()方法--->異步任務(wù)執(zhí)行完畢");
    }

    //onProgressUpdate()方法用于更新異步執(zhí)行中,在主線程中處理異步任務(wù)的執(zhí)行信息   
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        //更改進(jìn)度條
        progressBar.setProgress(values[0]);
        //更改TextView
        textView.setText("已經(jīng)加載"+values[0]+"%");
    }

    //onCancelled()方法用于異步任務(wù)被取消時(shí),在主線程中執(zhí)行相關(guān)的操作 
    @Override
    protected void onCancelled() {
        super.onCancelled();
        //更改進(jìn)度條進(jìn)度為0
        progressBar.setProgress(0);
        //更改TextView
        textView.setText("調(diào)用onCancelled()方法--->異步任務(wù)被取消");
        System.out.println("調(diào)用onCancelled()方法--->異步任務(wù)被取消");
    }
   }
}

main.xml如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/startButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="開(kāi)始異步任務(wù)" />

    <Button
        android:id="@+id/cancelButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="取消異步任務(wù)" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="0" />

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="test test" />
    </ScrollView>

</LinearLayout>


標(biāo)簽: 網(wǎng)絡(luò)

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請(qǐng)聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請(qǐng)與原作者聯(lián)系。

上一篇:JS變量的類(lèi)型檢查方式

下一篇:Android掃描wifi熱點(diǎn)代碼