文档章节

网络判断异步加载图片与SD卡缓存

Volkssturm
 Volkssturm
发布于 2017/05/03 21:34
字数 1029
阅读 9
收藏 0

public class Myapplication extends Application { @Override public void onCreate() { super.onCreate();

    File cacheDir = StorageUtils.getOwnCacheDirectory(this,
            Environment.getExternalStorageDirectory().getPath());
    Log.e(" 22222222222", "onCreate: 缓存路径-------------------》"+Environment.getExternalStorageDirectory().getPath());
    ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)
            .threadPoolSize(3)//配置线程数量
            .memoryCache(new LruMemoryCache(2 * 1024 * 1024))//内存缓存图片 2M
            .diskCache(new UnlimitedDiskCache(cacheDir))//配饰sdcard缓存路径
            .diskCacheSize(50 * 1024 * 1024)//sdcard上缓存50M的图片
            .diskCacheFileCount(100)//缓存文件的数量   100个
            .diskCacheFileNameGenerator(new Md5FileNameGenerator())
            .build();


    //配置缓存选项
    ImageLoader.getInstance().init(configuration);
}

}

/**

  • com.example.text2.Fragment
  • 徐世辉 1503A
  • <p>

  • 2017/5/3 */

public class ImageAsy extends AsyncTask<String,Void,Bitmap> { public interface ImageCallback{

    void claaback(Bitmap bitmap);

}

private ImageCallback imageCallback;

public ImageAsy(ImageCallback imageCallback) {
    this.imageCallback = imageCallback;
}

[@Override](https://my.oschina.net/u/1162528)
protected Bitmap doInBackground(String... params) {

    try {
        String path = params[0];
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5*1000);
        connection.setReadTimeout(5*1000);
        //服务器响应
        int code = connection.getResponseCode();
        if(code == HttpURLConnection.HTTP_OK){//判断服务器是否连接成功并相应
            //图片流
            InputStream is = connection.getInputStream();
            //将图片流转化成Bitmap位图,返回
            return BitmapFactory.decodeStream(is);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}


[@Override](https://my.oschina.net/u/1162528)
protected void onPostExecute(Bitmap bitmap) {
    super.onPostExecute(bitmap);
    if (bitmap!=null){
    imageCallback.claaback(bitmap);
}}

}

/**

  • com.example.text2.Fragment
  • 徐世辉 1503A
  • <p>

  • 2017/5/3 */

public class MyAdapter extends BaseAdapter{ private Context context; private List<Bean1.DataBean> data; private final DisplayImageOptions displayImageOptions;

public MyAdapter(Context context, List<Bean1.DataBean> data) {
    this.context = context;
    this.data = data;

    //是否内存缓存

//是否sdcard缓存 //构建图片缓存的选项 displayImageOptions = new DisplayImageOptions.Builder() .cacheInMemory(true)//是否内存缓存 .cacheOnDisk(true)//是否sdcard缓存 .build(); }

[@Override](https://my.oschina.net/u/1162528)
public int getCount() {
    return data.size();
}

[@Override](https://my.oschina.net/u/1162528)
public Object getItem(int position) {
    return data.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHandler viewHandler;
    if (convertView==null){
        viewHandler=new ViewHandler();
        convertView=View.inflate(context, R.layout.item,null);
        viewHandler.imageView= (ImageView) convertView.findViewById(R.id.item_image);
        viewHandler.textView= (TextView) convertView.findViewById(R.id.item_text);
        viewHandler.textView1= (TextView) convertView.findViewById(R.id.item_text2);
        convertView.setTag(viewHandler);
    }else {
        viewHandler= (ViewHandler) convertView.getTag();
    }
   viewHandler.textView.setText(data.get(position).getTITLE());
   viewHandler.textView1.setText(data.get(position).getSUBTITLE());
    if (data.get(position).getIMAGEURL()!=null) {
        //viewHandler.getimage(data.get(position).getIMAGEURL());
        ImageLoader.getInstance().displayImage(data.get(position).getIMAGEURL(),viewHandler.imageView,displayImageOptions);
    }else {
        viewHandler.imageView.setVisibility(View.GONE);
    }
    return convertView;
}
class ViewHandler{
    private ImageView imageView;
    private TextView textView,textView1;


public void getimage(String url){

    ImageAsy imageAsy=new ImageAsy(new ImageAsy.ImageCallback() {
        @Override
        public void claaback(Bitmap bitmap) {

            if (bitmap!=null){
             imageView.setImageBitmap(bitmap);
            }
        }
    });
    imageAsy.execute(url);
}}

}

/**

  • com.example.text2.Fragment
  • 徐世辉 1503A
  • <p>

  • 2017/5/3 */

public class Getitem { public String getitems(String url,int channelId,int startNum) { try { URL url1=new URL(url); HttpURLConnection httpURLConnection= (HttpURLConnection) url1.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setReadTimeout(5000); httpURLConnection.setConnectTimeout(5000);

        // 要发送给服务器的请求的实体内容
        OutputStream os = httpURLConnection.getOutputStream();
        os.write(("channelId="+channelId+"&startNum="+startNum).getBytes());
        PrintWriter writer = new PrintWriter(os);
        //把数据刷出去
        writer.flush();

       int code= httpURLConnection.getResponseCode();
        if (code==200){
            InputStream inputStream= httpURLConnection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
            byte[] b =new byte[1024];
            int read = 0;
            while ((read = inputStream.read(b))!= -1){
                byteArrayOutputStream.write(b,0,read);
            }
            return byteArrayOutputStream.toString();
        }


    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


    return "";
}

/**
 * 获取当前的网络状态 :没有网络0:WIFI网络1:移动数据2
 *
 * @param context
 * @return
 */
public static int getAPNType(Context context) {
    int netType = 0;
    ConnectivityManager connMgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo == null) {
        return netType;
    }
    int nType = networkInfo.getType();
    if (nType == ConnectivityManager.TYPE_WIFI) {
        netType = 1;// wifi
    } else if (nType == ConnectivityManager.TYPE_MOBILE) {
        //有移动数据
        //int nSubType = networkInfo.getSubtype();
        /*TelephonyManager mTelephony = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
                && !mTelephony.isNetworkRoaming()) {
            netType = 2;// 3G
        } else {
            netType = 3;// 2G
        }*/
        netType = 2;
    }
    return netType;
}

}

/**

  • com.example.text2.Fragment
  • 徐世辉 1503A
  • <p>

  • 2017/5/3 */

public class Fr1 extends Fragment {

private ListView listView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fr1,container,false);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    listView = (ListView) getView().findViewById(R.id.fr1_lv);
    int connType = Getitem.getAPNType(getActivity());
    if (connType == 1){
        Log.e("onActivityCreated: ","是wifi网络" );
        getids("http://www.93.gov.cn/93app/data.do");
    }else if (connType >1){
        Log.e("onActivityCreated: ","是移动网络" );
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                .setTitle("移动网络继续访问")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getids("http://www.93.gov.cn/93app/data.do");
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getActivity(),"将不再移动数据下访问",Toast.LENGTH_SHORT).show();
                    }
                }).show();
    }else {
        Log.e("onActivityCreated: ","没有网络" );
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                .setTitle("没有网络")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getActivity(),"等待网络链接",Toast.LENGTH_SHORT).show();
                        try {
                            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                            {
                                File file = new File(Environment.getExternalStorageDirectory(),"66.txt");
                                if(file.exists())
                                    try {
                                        FileInputStream fileInputStream= new FileInputStream(file);
                                        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
                                        byte[] b =new byte[1024];
                                        int read = 0;
                                        while ((read = fileInputStream.read(b))!= -1){
                                            byteArrayOutputStream.write(b,0,read);
                                        }
                                       String ll= byteArrayOutputStream.toString();
                                        Gson gson=new Gson();

                                        Bean1 bean=gson.fromJson(ll, Bean1.class);
                                        List<Bean1.DataBean> data1= bean.getData();

                                        MyAdapter m= new MyAdapter(getActivity(),data1);
                                        listView.setAdapter(m);


                                    } catch (FileNotFoundException e1) {
                                        e1.printStackTrace();
                                    }



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

                    }
                }).show();
    }


}

public void  getids(String url){

    new AsyncTask<String,Void,String>(){
        @Override
        protected String doInBackground(String... params) {
            String p=params[0];
            return new Getitem().getitems(p,0,0);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.e( "onPostExecute: ","发那个地方公开就爱看上到几点"+s );

            Gson gson=new Gson();
            try {
                if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
            {
                File file = new File(Environment.getExternalStorageDirectory(),"66.txt");
                if(file.exists())
                {file.createNewFile();
                }
               FileOutputStream fileOutputStream= new FileOutputStream(file);
                fileOutputStream.write(s.getBytes());

                fileOutputStream.close();
            } }
            catch (IOException e) {
            e.printStackTrace();
        }
            Bean1 bean=gson.fromJson(s, Bean1.class);
            List<Bean1.DataBean> data= bean.getData();

           MyAdapter m= new MyAdapter(getActivity(),data);
            listView.setAdapter(m);


        }
    }.execute(url);
}

}

© 著作权归作者所有

共有 人打赏支持
Volkssturm
粉丝 0
博文 22
码字总数 11462
作品 0
海淀
程序员
Android开源中国客户端学习 异步加载图片

这次的内容又是很简单 异步加载图片大家可能做的也很多了 通过阅读osc的源码 也算是 学习人家的一种架构吧,好歹作者的经验也比我丰富。 其实osc的图片异步加载也是使用了两级结构,即 内存缓...

SuShine
2013/06/23
0
3
android之图片异步加载并缓存到本地

在android项目中访问网络图片是非常普遍性的事情,如果我们每次请求都要访问网络来获取图片,会非常耗费流量,而且图片占用内存空间也比较大,图片过多且不释放的话很容易造成内存溢出。针对...

感觉太煽情
2015/09/24
443
0
SDWebImage源码解读(一)

SDWebImage 是目前最流行、使用最广泛的第三方图片处理框架,它不仅能够异步加载网络图片,还提供了一套图片缓存管理机制(内存缓存+磁盘缓存),功能非常强大。 SD内部已经帮我们把请求回来...

honey缘木鱼
07/05
0
0
【OSC手机App技术解析】- 列表异步线程加载图片

手机客户端以列表形式展示数据是非常常见的一种方式。然而列表中要显示图片(比如:头像)就要采用异步线程加载的方式,这样做是为了防止加载图片数据的时候,花费时间过长,阻塞UI线程,从而...

迷途d书童
2012/06/29
1K
5
Universal-ImageLoader

Universal-ImageLoader是一个第三方开源库,主要用来异步加载图片、缓存图片、和图片显示。(获取图片显示在相应的控件上) 官网地址:https://github.com/nostra13/Android-Universal-Image-...

Taian
2016/01/11
120
0

没有更多内容

加载失败,请刷新页面

加载更多

关于组件化的最初步

一个工程可能会有多个版本,有国际版、国内版、还有针对各种不同的渠道化的打包版本、这个属于我们日常经常见到的打包差异化版本需求。 而对于工程的开发,比如以前的公司,分成了有三大块业...

DannyCoder
31分钟前
1
0
Spring的Resttemplate发送带header的post请求

private HttpHeaders getJsonHeader() { HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); ......

qiang123
昨天
2
0
Spring Cloud Gateway 之 Only one connection receive subscriber allowed

都说Spring Cloud Gateway好,我也来试试,可是配置了总是报下面这个错误: java.lang.IllegalStateException: Only one connection receive subscriber allowed. 困扰了我几天的问题,原来...

ThinkGem
昨天
25
0
学习设计模式——观察者模式

1. 认识观察者模式 1. 定义:定义对象之间一种一对多的依赖关系,当一个对象状态发生变化时,依赖该对象的其他对象都会得到通知并进行相应的变化。 2. 组织结构: Subject:目标对象类,会被...

江左煤郎
昨天
2
0
emoji

前言:随着iOS系统版本的升级,对原生emoji表情的支持也越来越丰富。emoji表情是unicode码中为表情符号设计的一组编码,当然,还有独立于unicode的另一套编码SBUnicode,在OS系统中,这两种编...

HeroHY
昨天
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部