package com.example.administrator.imageviewer01;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity{
// 子线程里不能刷新UI
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
ImageView iv= (ImageView) findViewById(R.id.iv);
iv.setImageBitmap((Bitmap) msg.obj);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button= (Button) findViewById(R.id.imageviewer);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String path="http://pic71.nipic.com/file/20150610/13549908_104823135000_2.jpg";
final File file=new File(getCacheDir(),getNameFromPath(path));
// 判断file(缓存)是否存在
if(file.exists()){
// 如果存在,就直接从缓存中获取
Bitmap bm=BitmapFactory.decodeFile(file.getAbsolutePath());
}
else {
// 由于主线程里面不能进行耗时操作,故开启子线程进行网络申请
Thread t = new Thread() {
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
// conn.connect();
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
int len;
// 缓存到getCacheDir()文件夹下。getNameFromPath(path)的目的是获取到从服务器里下载下来的13549908_104823135000_2.jpg文件名
FileOutputStream fos = new FileOutputStream(file);
while ((len = is.read(b)) != -1) {
fos.write(b, 0, len);
}
fos.close();
// 由于缓存时已经把流里的数据读取完了,此时流里已经没有数据了,所以下面这个直接读取图片的代码已经没有用了
// 需要注释掉,需要新的API
// Bitmap bm=BitmapFactory.decodeStream(is);
// 缓存前把本地图片构造成一个试图
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
Message msg = new Message();
msg.obj = bm;
handler.sendMessage(msg);
} else {
Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}
});
}
//这个方法是截取13549908_104823135000_2.jpg字符串
private String getNameFromPath(String path) {
int index=path.lastIndexOf("/");
// 不加1的话会带最后一个斜杠加进来
return path.substring(index+1);
}
}
android网络申请,添加缓存
猜你喜欢
转载自blog.csdn.net/qq_41320857/article/details/79644524
今日推荐
周排行