从网络获取图片,并缓存到SD卡
【摘要】
效果图:
图片存在bmob(http://www.bmob.com
)后台,所以下载Demo运行的话要到官网申请
Application ID。
先点击上传图片,再点击缓存图片,不然没数据。
代码:
paths=new String[5]; for(int...



图片存在bmob( )后台,所以下载Demo运行的话要到官网申请 Application ID。
先点击上传图片,再点击缓存图片,不然没数据。
代码: 上面的代码要改为自己的图片路径。
主要代码:
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();
}
}
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)