Android AsyncTack 异步任务实例详解

2019-05-02 16:33:33刘景俊

注意: 如果我们直接去execute我们的任务, 它(任务) 只会在同一个子线程中运行, 所以上述第一种方式启动时, 四个任务顺次执行(就是一个任务执行完了再执行另一个); 而第二种方式, 给它创建了线程池, 这样会自动给它创建新的子线程, 所有的任务不是顺序执行, 而是几个线程”同时执行”

获取网络数据呈现在Webview和下载图片和其共存的案例

1, 首先我们要来一个布局, 具体需求是这样的, 在WebView之上有个ImageView, 并且, ImageView可以随WebView滚动, 所以这个时候我们想到了用ScrollView, 但是大家一定不要忘记, ScrollView只能包含一个控件, 所以我们可以用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, 接下来我们要有一个实体类, 用来存放从网页上下载的内容(这里加注解原因在于我们要使用GSON解析来自网页的内容)

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, 那我们接下解决的问题就是 如何下载图片? 如何下载web内容? , 那我们写两个通用的工具类

下载工具类(通用型)

/**
 * 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("服务器异常");
      }

    } 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);
  }
}

								 
			 
相关文章 大家在看