溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Android中怎么利用AsyncTack 實(shí)現(xiàn)異步任務(wù)

發(fā)布時(shí)間:2021-06-28 16:12:29 來(lái)源:億速云 閱讀:165 作者:Leah 欄目:開發(fā)技術(shù)

Android中怎么利用AsyncTack 實(shí)現(xiàn)異步任務(wù),針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。

1, 繼承AsyncTask

public class MyTask extends AsyncTask<Params, Progrss, Result>

我們來(lái)說(shuō)一下這三個(gè)泛型的作用:

Params: 調(diào)用異步任務(wù)時(shí)傳入的類型 ;

Progress : 字面意思上說(shuō)是進(jìn)度條, 實(shí)際上就是動(dòng)態(tài)的由子線程向主線程publish數(shù)據(jù)的類型

Result : 返回結(jié)果的類型

2, 重寫這個(gè)類的抽象方法doInBackground, 當(dāng)然它也有幾個(gè)方法需要重寫, 我們一一看來(lái)

doInBackground(抽象方法, 必須實(shí)現(xiàn))

/* 唯一執(zhí)行在子線程中的方法
 *  所以不可以進(jìn)行UI的更新
 * @param params
 * @return
 */
@Override//返回值: Result    參數(shù): Param
protected String doInBackground(TextView... params) {
  text = params[0];
  Random random = new Random();
  for (int i = 0; i < 50; i++) {
    //要進(jìn)行進(jìn)度的更新
    publishProgress(i);
    //不能直接調(diào)用onProgressUpdate方法,
    //這樣會(huì)使得onProgressUpdate在子線程中運(yùn)行
    try {
      Thread.sleep(random.nextInt(10) * 10);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
  return "已完成";
}

下面三個(gè)方法根據(jù)具體情況選擇使用

 //執(zhí)行doInBackground之前調(diào)用
  @Override
  protected void onPreExecute() {
    super.onPreExecute();
  }
  @Override//與publishProgress(i)對(duì)應(yīng)
  protected void onProgressUpdate(Integer... values) {
    super.onProgressUpdate(values);
    text.setText(String.valueOf(values[0]));
  }
 //在doInBackground之后執(zhí)行
  @Override // 參數(shù)s為 Result
  protected void onPostExecute(String s) {
    super.onPostExecute(s);
    text.setText(s);
  }

3, 執(zhí)行異步任務(wù)

有兩種方式, 我已經(jīng)把區(qū)別寫在了注釋中
/*
 直接execute異步任務(wù), 都是同一線程去執(zhí)行
*/

text = (TextView) findViewById(R.id.main_text1);
new MyTask().execute(text);
text = (TextView) findViewById(R.id.main_text2);
new MyTask().execute(text);
text = (TextView) findViewById(R.id.main_text3);
new MyTask().execute(text);
text = (TextView) findViewById(R.id.main_text4);
new MyTask().execute(text);
/*
  啟動(dòng)多條線程來(lái)執(zhí)行異步任務(wù)
  API11以上可以使用
*/
 ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(4);
 text = (TextView) findViewById(R.id.main_text1);
 new MyTask().executeOnExecutor(executor, text);
 text = (TextView) findViewById(R.id.main_text2);
 new MyTask().executeOnExecutor(executor, text);
 text = (TextView) findViewById(R.id.main_text3);
 new MyTask().executeOnExecutor(executor, text);
 text = (TextView) findViewById(R.id.main_text4);
 new MyTask().executeOnExecutor(executor, text);

注意: 如果我們直接去execute我們的任務(wù), 它(任務(wù)) 只會(huì)在同一個(gè)子線程中運(yùn)行, 所以上述第一種方式啟動(dòng)時(shí), 四個(gè)任務(wù)順次執(zhí)行(就是一個(gè)任務(wù)執(zhí)行完了再執(zhí)行另一個(gè)); 而第二種方式, 給它創(chuàng)建了線程池, 這樣會(huì)自動(dòng)給它創(chuàng)建新的子線程, 所有的任務(wù)不是順序執(zhí)行, 而是幾個(gè)線程”同時(shí)執(zhí)行”

獲取網(wǎng)絡(luò)數(shù)據(jù)呈現(xiàn)在Webview和下載圖片和其共存的案例

1, 首先我們要來(lái)一個(gè)布局, 具體需求是這樣的, 在WebView之上有個(gè)ImageView, 并且, ImageView可以隨WebView滾動(dòng), 所以這個(gè)時(shí)候我們想到了用ScrollView, 但是大家一定不要忘記, ScrollView只能包含一個(gè)控件, 所以我們可以用LinearLayout包裹一下即可

<ScrollView
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
      android:id="@+id/main2_image"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
    <WebView
      android:id="@+id/main2_web"
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>
  </LinearLayout>
</ScrollView>

2, 接下來(lái)我們要有一個(gè)實(shí)體類, 用來(lái)存放從網(wǎng)頁(yè)上下載的內(nèi)容(這里加注解原因在于我們要使用GSON解析來(lái)自網(wǎng)頁(yè)的內(nèi)容)

public class Entry {
  @SerializedName("title")
  private String title;
  @SerializedName("message")
  private String message;
  @SerializedName("img")
  private String image;

  public String getTitle() {
    return title;
  }
  ...//省略其余getter和setter方法
  public void setImage(String image) {
    this.image = image;
  }
}

3, 那我們接下解決的問(wèn)題就是 如何下載圖片? 如何下載web內(nèi)容? , 那我們寫兩個(gè)通用的工具類

下載工具類(通用型)

/**
 * Created by Lulu on 2016/8/31.
 * <p/>
 * 通用下載工具類
 */
public class NetWorkTask<T> extends AsyncTask<NetWorkTask.Callback<T>, Void, Object> {

  private NetWorkTask.Callback<T> callback;
  private Class<T> t;
  private String url;

  public NetWorkTask(String url, Class<T> t) {
    this.url = url;
    this.t = t;
  }
  @Override
  protected Object doInBackground(Callback<T>... params) {
    callback = params[0];

    try {

      HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
      connection.setRequestMethod("GET");
      connection.setDoInput(true);
      int code = connection.getResponseCode();
      if (code == 200) {
        InputStream is = connection.getInputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[102400];
        int length;
        while ((length = is.read(buffer)) != -1) {
          bos.write(buffer, 0, length);
        }
        return bos.toString("UTF-8");
      } else {
        return new RuntimeException("服務(wù)器異常");
      }

    } catch (Exception e) {
      e.printStackTrace();
      return e;
    }

  }

  @Override
  protected void onPostExecute(Object o) {
    super.onPostExecute(o);
    if(o instanceof String) {
      String str = (String) o;
      Gson gson = new Gson();
      T t = gson.fromJson(str, this.t);
      callback.onSuccess(t);
    }
    if( o instanceof Exception) {
      Exception e = (Exception) o;
      callback.onFailed(e);
    }
  }
  public interface Callback<S> {
    void onSuccess(S t);
    void onFailed(Exception e);
  }
}

圖片加載器(通用型)

/**
 * Created by Lulu on 2016/8/31.
 * 圖片網(wǎng)絡(luò)加載器
 * 下載成功返回Bitmap
 * 否則返回null
 */
public class ImageLoader extends AsyncTask<String, Void, Bitmap>{

  private ImageView image;

  public ImageLoader(ImageView image) {
    this.image = image;
    image.setImageResource(R.mipmap.ic_launcher);
  }

  @Override
  protected void onPreExecute() {
    super.onPreExecute();

  }

  @Override
  protected Bitmap doInBackground(String... params) {
    String url = params[0];
    try {
      HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
      connection.setRequestMethod("GET");
      connection.setDoInput(true);
      int code = connection.getResponseCode();
      if (code == 200) {
        InputStream is = connection.getInputStream();
        return BitmapFactory.decodeStream(is);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }


  @Override
  protected void onPostExecute(Bitmap bitmap) {
    super.onPostExecute(bitmap);
    if (bitmap != null) {
      image.setImageBitmap(bitmap);
    } else {
      image.setImageResource(R.mipmap.failed);
    }
  }
}

4, 測(cè)試Activity

注意: 看如何解決大圖在webView中不左右滑動(dòng)的問(wèn)題!

public class Main2Activity extends AppCompatActivity implements NetWorkTask.Callback<Entry>{
  private WebView web;
  private ImageView image;
  //解決大圖在webView中不左右滑動(dòng)的問(wèn)題
  private static final String CSS = "<style>img{max-width:100%} </style>";
  private String title;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    web = (WebView) findViewById(R.id.main2_web);
    image = (ImageView) findViewById(R.id.main2_image);
    new NetWorkTask<>("http://www.tngou.net/api/top/show?id=13122", Entry.class).execute(this);
  }
  @Override
  public void onSuccess(Entry t) {
    web.loadDataWithBaseURL("", t.getMessage(), "text/html; charset=utf-8", "UTF-8", null);
    new ImageLoader(image).execute("http://img.blog.csdn.net/20160829134937003");
  }
  @Override
  public void onFailed(Exception e) {
    web.loadDataWithBaseURL("", "加載失敗", "text/html; charset=utf-8", "UTF-8", null);
  }
}

關(guān)于Android中怎么利用AsyncTack 實(shí)現(xiàn)異步任務(wù)問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI