从网络获取图片,并缓存到SD卡_第1张图片



效果图:

从网络获取图片,并缓存到SD卡_第2张图片 从网络获取图片,并缓存到SD卡_第3张图片 从网络获取图片,并缓存到SD卡_第4张图片

图片存在bmob(http://www.bmob.com )后台,所以下载Demo运行的话要到官网申请 Application ID。
先点击上传图片,再点击缓存图片,不然没数据。


代码:
  1. paths=new String[5];
  2. for(int i=0;i<5;i++){
  3. //图片路径
  4. paths[i]=Environment.getExternalStorageDirectory()+"/"+i+".jpg";
  5. }
复制代码 上面的代码要改为自己的图片路径。

主要代码:

IndexActivity

public class IndexActivity extends Activity {        private String[] paths;        private int j;        private File cache;        private String appid="";  //你的Application ID        protected void onCreate(Bundle savedInstanceState) {                super.onCreate(savedInstanceState);                Bmob.initialize(this, appid);                setContentView(R.layout.activity_index);                ///创建缓存目录                cache=new File(Environment.getExternalStorageDirectory(),"cache");                   if(!cache.exists()){                        cache.mkdirs();                }        }        public void skip(View v){                Intent intent=new Intent(this,MainActivity.class);                startActivity(intent);        }        public void upload(View v){                paths=new String[5];                for(int i=0;i<5;i++){                        //图片路径                        paths[i]=Environment.getExternalStorageDirectory()+"/"+i+".jpg";                        }                //批量上传图片                Bmob.uploadBatch(this, paths, new UploadBatchListener() {                        @Override                        public void onSuccess(List<BmobFile> arg0, List<String> arg1) {                                // TODO Auto-generated method stub                                String strurl="";                                for(String url:arg1){                                        strurl=url;                                }                                Person p=new Person();                                p.setIcPath(strurl);                                p.setStr("s"+j);                                p.save(IndexActivity.this);                                j++;                                toast("第"+j+"个上传成功!");                        }                        @Override                        public void onProgress(int curIndex, int curPercent, int total, int totalPercent) {                                // TODO Auto-generated method stub                                //1、curIndex--表示当前第几个文件正在上传                                //2、curPercent--表示当前上传文件的进度值(百分比)                                //3、total--表示总的上传文件数                                //4、totalPercent--表示总的上传进度(百分比)                                MyUtil.logI(curIndex+" "+curPercent+" "+total+" "+totalPercent);                                                        }                        @Override                        public void onError(int arg0, String arg1) {                                // TODO Auto-generated method stub                                toast("error "+arg1);                                MyUtil.logI("errer "+arg1);                        }                });        }                // 清理缓存        public void clear(View v){                if(cache.length()!=0){                        File[] files=cache.listFiles();                        for(File file:files){                                file.delete();                        }                        cache.delete();                        toast("缓存清理成功");                }else{                        toast("暂无缓存");                }        }        public void toast(String msg){                Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();        }}


MainActivity
  1. public class MainActivity extends Activity {        private ListView lv;        private MyAdapter adapter;        private File cache;        private List<Person> list;        protected void onCreate(Bundle savedInstanceState) {                super.onCreate(savedInstanceState);                setContentView(R.layout.activity_main);                initView();        }        private void initView() {                // TODO Auto-generated method stub                lv=(ListView)findViewById(R.id.listView1);                list=new ArrayList<Person>();                                cache=new File(Environment.getExternalStorageDirectory(),"cache");                if(!cache.exists()){                        cache.mkdirs();                }                                getData();        }        private void getData() {                // TODO Auto-generated method stub                //查询数据                BmobQuery<Person> bq=new BmobQuery<Person>();                bq.setCachePolicy(CachePolicy.CACHE_ELSE_NETWORK);        //缓存查询                bq.findObjects(this, new FindListener<Person>() {                                                @Override                        public void onSuccess(List<Person> arg0) {                                // TODO Auto-generated method stub                                list=arg0;                                adapter=new MyAdapter(MainActivity.this, list, cache);                                lv.setAdapter(adapter);                        }                                                @Override                        public void onError(int arg0, String arg1) {                                // TODO Auto-generated method stub                                MyUtil.logI("errer "+arg1);                        }                });        }




MyAdapter
  1. public class MyAdapter extends BaseAdapter {        private Context context;        private List<Person> list;        private File cache;        public MyAdapter(Context context, List<Person> list, File cache) {                this.context = context;                this.list = list;                this.cache = cache;        }        @Override        public int getCount() {                // TODO Auto-generated method stub                return list.size();        }        @Override        public Object getItem(int position) {                // TODO Auto-generated method stub                return list.get(position);        }        @Override        public long getItemId(int position) {                // TODO Auto-generated method stub                return position;        }        @Override        public View getView(int position, View convertView, ViewGroup parent) {                // TODO Auto-generated method stub                ViewHolder vh;                if(convertView==null){                        convertView=LayoutInflater.from(context).inflate(R.layout.item, null);                        vh=new ViewHolder();                        vh.tv=(TextView)convertView.findViewById(R.id.tv);                        vh.iv=(ImageView)convertView.findViewById(R.id.iv);                        convertView.setTag(vh);                }else{                        vh=(ViewHolder)convertView.getTag();                }                                final Person p=list.get(position);                vh.tv.setText(p.getStr());                                // 异步的加载图片                MyUtil mu=new MyUtil();                AsyncImageTask as=new AsyncImageTask(mu,vh.iv,cache);                if(p.getIcPath()!=null){                        as.execute(p.getIcPath());                }else{                        vh.iv.setImageResource(R.drawable.ic_launcher);                }                                return convertView;        }        class ViewHolder{                TextView tv;                ImageView iv;        }        }


MyUtil
  1. public class MyUtil {        /**         * 从网络上获取图片,如果图片在本地存在的话就直接拿,如果不存在再去服务器上下载图片         * */        public Uri getImageURI(String path,File cache) throws Exception{                String name=MD5.getMD5(path)+path.substring(path.lastIndexOf("."));                logI("name"+name);                File file=new File(cache, name);                // 如果图片存在本地缓存目录,则不去服务器下载                if(file.exists()){                        logI("cache");                        return Uri.fromFile(file);                }else{                        URL url=new URL(path);                        HttpURLConnection conn=(HttpURLConnection)url.openConnection();                        conn.setConnectTimeout(5000);                        conn.setRequestMethod("GET");                        conn.setDoInput(true);                        if(conn.getResponseCode()==200){                                InputStream is=conn.getInputStream();                                FileOutputStream fos=new FileOutputStream(file);                                byte[] b=new byte[2*1024];                                int len=0;                                while((len=is.read(b))!=-1){                                        fos.write(b,0,len);                                }                                is.close();                                fos.close();                                return Uri.fromFile(file);                        }                }                return null;        }                        public static void logI(String msg){                Log.i("-------", msg);        }}





AsyncImageTask

public class AsyncImageTask extends AsyncTask<String, Integer, Uri> {        private ImageView ivIcon;        private MyUtil mu;        private File cache;        public AsyncImageTask(MyUtil mu,ImageView ivIcon,File cache) {                this.mu=mu;                this.ivIcon = ivIcon;                this.cache=cache;        }        @Override        protected Uri doInBackground(String... arg0) {                // TODO Auto-generated method stub                try {                        return mu.getImageURI(arg0[0], cache);                } catch (Exception e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                }                return null;        }        @Override        protected void onPostExecute(Uri result) {                // TODO Auto-generated method stub                super.onPostExecute(result);                if(ivIcon!=null && result!=null){                        ivIcon.setImageURI(result);                }        }}


更多相关文章

  1. 通过Android的okhttp接口访问网络接口
  2. ionic3 图片选取imagepicker以及camera汉化
  3. LiveData+Retrofit 网络请求实战
  4. Android修改图片颜色-转成灰度图
  5. Android 首选网络模式默认值的修改方法
  6. Android ImageView设置长度高度为wrap_content时高度根据图片比

随机推荐

  1. 【前端 · 面试 】HTTP 总结(六)—— HTTP
  2. 计算器作业
  3. 0805 一.将数组的偶数去出, 二.尝试实现
  4. 数组循环取模及代码实现计算器
  5. 入门php变量和常量
  6. php 求数组中的偶数成员
  7. 0805 PHP编程作业
  8. 请实例演绎php遍历数组与js遍历数组的区
  9. 数组、计算器
  10. 16期8月5日作业