1. 程式人生 > >圖片二級取樣,三級快取

圖片二級取樣,三級快取

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