package com.lidaochen.test; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.util.Base64; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class MainActivity extends AppCompatActivity { private EditText et_path; private ImageView iv_pic; // 建立handler對象 public Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bitmap bitmap = (Bitmap)msg.obj; // 設置圖片到ImageView iv_pic.setImageBitmap(bitmap); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 找到 ImageView 和 EditText控件 et_path = (EditText)findViewById(R.id.et_path); iv_pic = (ImageView)findViewById(R.id.iv_pic); } public void click(View v) { new Thread() { public void run() { try { // 獲取圖片路徑 String path = et_path.getText().toString().trim(); File file = new File(getCacheDir(), Base64.encodeToString(path.getBytes(), Base64.DEFAULT)); if (file.exists() && file.length() > 0) { // 使用緩存圖片 System.out.println("使用緩存圖片!"); final Bitmap cacheBitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); // 把cacheBitmap顯示到ImageView上 Message msg = Message.obtain(); // 使用Message的靜態方法,能夠減小對象的建立 msg.obj = cacheBitmap; handler.sendMessage(msg); } else { // Toast.makeText(getApplicationContext(), "第一次鏈接網絡!", Toast.LENGTH_SHORT).show(); System.out.println("第一次鏈接網絡!"); // 建立url對象 URL url = new URL(path); // 獲取HttpURLConnection對象 HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); // 設置請求方式 httpURLConnection.setRequestMethod("GET"); // 設置超時時間 httpURLConnection.setReadTimeout(5000); // 獲取服務器返回的狀態碼 int code = httpURLConnection.getResponseCode(); if (code == 200) { // 獲取圖片數據,無論什麼數據,都是以流的形式返回 InputStream in = httpURLConnection.getInputStream(); // 緩存圖片 谷歌給咱們提供了一個緩存目錄 FileOutputStream fos = new FileOutputStream(file); int len = -1; byte buffer[] = new byte[1024]; // 1kB while((len = in.read(buffer)) != -1) { fos.write(buffer, 0, len); } // 關閉流 fos.close(); in.close(); // 經過位圖工廠,獲取位圖 final Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); // 建立MSG 對象 // Message msg = new Message(); Message msg = Message.obtain(); // 使用Message的靜態方法,能夠減小對象的建立 msg.obj = bitmap; handler.sendMessage(msg); } } } catch (Exception e) { e.printStackTrace(); } } }.start(); } }