在项目中遇到加载网络gif的情况,上网找了一些,但是都写的不是那么清楚,所有打算整合一下,加上自己写一些
这了我用一个网络库(AsyncHttpClient)和一个加载gif库(Glide)
网络AsyncHttpClient点击打开链接
gif-Glide点击打开链接
把这两个jar导入项目的libs中
网络请求类
public class HClient { private static AsyncHttpClient client = new AsyncHttpClient(); static{ client.setTimeout(50000); } public static void get(String url,JsonHttpResponseHandler handler){ client.get(url, handler); } public static void get(String url,BinaryHttpResponseHandler handler){ client.get(url, handler); } }发起网络请求,获取到gif的地址
HClient.get(CommonUrl.getSatel_URL, new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); try { <span style="white-space:pre"> </span>//获取gif的网络地址 } catch (JSONException e) { e.printStackTrace(); } } });这里得到了gif的地址,显示gif就分为两种情况,一个是直接加载网络地址
Glide.with(this).load(gif_url).centerCrop() //图片在加载期间显示的图片 .placeholder(R.drawable.ic_launcher).crossFade().into(your_imageview);
一种是下载gif,加载byte(也可以下载到sd卡,再加载sd卡的gif文件,小于1M的很快,大于的2M的就会很慢,亲自测试了)
private final static String ALBUM_PATH = Environment.getExternalStorageDirectory()+""; byte[] bytes = new byte[1024]; private void saveGif(String path){ HClient.get(path, new BinaryHttpResponseHandler(){ @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) { try { bytes = arg2; if (isFileExist(ALBUM_PATH+"/YT/") == false) { Log.d("TAG", ALBUM_PATH); File file = new File(ALBUM_PATH+"/YT/"); file.mkdir(); } File file2 = new File(ALBUM_PATH+"/YT/yt.gif"); file2.createNewFile(); FileOutputStream fileOutputStream = new FileOutputStream(file2); fileOutputStream.write(arg2); fileOutputStream.close();//handler加载gif } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) { } }); }
public boolean isFileExist(String fileName){ File file = new File(fileName); file.delete(); return file.exists(); }加载
Glide.with(this).load(bytes).centerCrop().placeholder(R.drawable.ic_launcher).crossFade().into(your_imageview);
@Override protected void onDestroy() { super.onDestroy(); Glide.clear(your_imageview); Glide.with(this).onDestroy(); }这里就完成了gif的加载,使用起来还是比较方便