从网络获取图片,并缓存到SD卡

举报
再见孙悟空_ 发表于 2022/01/12 22:58:50 2022/01/12
【摘要】 效果图: 图片存在bmob(http://www.bmob.com )后台,所以下载Demo运行的话要到官网申请 Application ID。 先点击上传图片,再点击缓存图片,不然没数据。 代码: paths=new String[5]; for(int...







图片存在bmob( )后台,所以下载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();
              }
      }
  
 



  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);
                                      }
                              });
                      }
          
         





  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;
                      }
              }
          
         



  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);
                      }
              }
      }
  
 


文章来源: wukong.blog.csdn.net,作者:再见孙悟空_,版权归原作者所有,如需转载,请联系作者。

原文链接:wukong.blog.csdn.net/article/details/44936345

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。