Android10--Android之异步任务加载网页和图片

今天介绍的是一个简单的从网上获取网页和图片,我们将其做成工具类,再使用时只需要传入相应的参数即可.

首先我们定义一个要获取的一个类型Entry:因为设计到Gson解析,我们不要忘记给没个属性加上注解.

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
}

图片加载类工具类:通用
这里对图片的加载做了三种处理:加载之前 加载完成 加载失败


public class ImageLoader extends AsyncTask<String, Void, Bitmap> {
    private ImageView image;

    public ImageLoader(ImageView image) {
        this.image = image;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        image.setImageResource(R.mipmap.coming);
    }

    @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.ic_launcher);
        }
    }
}

解析一个网页工具类:通用
只需传入要解析的网址,和要解析成的Class,之后再去开启这个异步线程

public class NetworkTask<T> extends AsyncTask<NetworkTask.Callback<T>, Void, Object> {

    private Callback<T> callback;
    private String url;
    private Class<T> t;
    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();
                int length;
                byte[] buffer = new byte[102400];
                while ((length = is.read(buffer)) != -1){
                    bos.write(buffer, 0, length);
                }
                Gson gson = new Gson();
                return gson.fromJson(bos.toString("UTF-8"), t);
            } else {
                return new RuntimeException("ResponseCode: " + code);
            }
        } catch (IOException e) {
            return e;
        }
    }

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        if (t.isInstance(o)) {
            callback.onSuccess((T) o);
        } else if (o instanceof Exception) {
            callback.onFail((Exception) o);
        }
    }

    public interface Callback<S> {
        void onSuccess(S text);
        void onFail(Exception e);
    }
}

为了让加载之后的图片显示和网页内容一起滑动:我们使用的ScrollView,但是要注意ScrollView中只能放置一个控件.一般是一个布局

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

测试类:
用webView承载一个网页的内容时,如果是图文混排,里面的图片可能会超出屏幕的宽度,我们可以加上:
private static final String CSS = "<style>img{max-width:100%}</style>";


public class Main2Activity extends AppCompatActivity implements NetworkTask.Callback<Entry>{

    private WebView web;
    private ImageView image;
    private static final String CSS = "<style>img{max-width:100%}</style>";
    @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 entry) {
        setTitle(entry.getTitle());
        new ImageLoader(image).execute("http://tnfs.tngou.net/img" + entry.getImage());
        web.loadDataWithBaseURL("http://www.tngou.net", CSS + entry.getMessage(), "text/html; charset=utf-8", "UTF-8", null);
    }

    @Override
    public void onFail(Exception e) {
        e.printStackTrace();
        Toast.makeText(Main2Activity.this, "网络错误", Toast.LENGTH_SHORT).show();
    }
}

这里写图片描述

下一篇讲引入动态接口:将之中的工具类打包为另一个Liabray,在喜爱次使用时只要import即可..
http://blog.csdn.net/u012954720/article/details/52398370

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值