Android AsyncTack 异步任务实例详解(2)

/** * Created by Lulu on 2016/8/31. * 图片网络加载器 * 下载成功返回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, 测试Activity

注意: 看如何解决大图在webView中不左右滑动的问题!

public class Main2Activity extends AppCompatActivity implements NetWorkTask.Callback<Entry>{ private WebView web; private ImageView image; //解决大图在webView中不左右滑动的问题 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); } }

5.效果图:

Android AsyncTack 异步任务实例详解

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/f770d013028b6e7df5ce768629f743c3.html