private ImageView imageView;
//handler更新UI界面
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
Bitmap bitmap = (Bitmap) msg.obj;
imageView.setImageBitmap(bitmap);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//调用onFindId()方法{里面写的是控件}
onFindId();
}
public void onCin(View view) {
//获取网络资源.做耗时操作
final String path = "http://04.imgmini.eastday.com/mobile/20180512/20180512_fe1bf1b6ec00098f9455c84dc81e6763_cover_mwpm_03200403.jpg";
final File file = new File(getCacheDir(), getFileName(path));
boolean exists = file.exists();
if (exists) {
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//给imageview设置图片
imageView.setImageBitmap(bitmap);
} else {
//获取绝对路径
new Thread() {
@Override
public void run() {
super.run();
try {
URL url = new URL(path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5000);
urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//图片资源进行缓存
InputStream inputStream = urlConnection.getInputStream();
byte[] bytes=new byte[1024];
int length;
FileOutputStream fileOutputStream = new FileOutputStream(file);
while ((length=inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,length);
}
fileOutputStream.close();
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Message obtain = new Message();
obtain.obj = bitmap;
obtain.what = 1;
handler.sendMessage(obtain);
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
private String getFileName(String path) {
int i = path.lastIndexOf("/");
String substring = path.substring(i + 1);
return substring;
}
private void onFindId() {
imageView = findViewById(R.id.image1);
}