android對網狀圖片保留緩衝 隨時載入

來源:互聯網
上載者:User

實現原理就是從網上下載圖片資料,一邊將資料轉成drawable並載入到指定的imageview

一邊儲存成download_image.jpg,在點擊imageview時候用intent將圖片開啟


我將處理圖片的過程寫成了類

package com.example.downloadandopenimage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class LoadAndSaveImage {
    ImageView view;
    Context mContext;

    public LoadAndSaveImage() {
        // TODO Auto-generated constructor stub
    }

    public LoadAndSaveImage(Context context, String str, ImageView view) {
        // TODO Auto-generated constructor stub
        this.view = view;
        mContext = context;
        new Load_and_save_image().execute(str);
    }

    void release() {
        File file = new File("file://"
                + Environment.getExternalStorageDirectory().toString()
                + "/download_image.jpg");
        if (file.exists()) {
            boolean deleted = file.delete();
        }
    }

    class Load_and_save_image extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... sUrl) {
            // TODO Auto-generated method stub
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                // download the file
                input = connection.getInputStream();
                File checker = new File("file://"
                        + Environment.getExternalStorageDirectory().toString()
                        + "/download_image.jpg");
                if (checker.exists()) {
                    boolean deleted = checker.delete();
                }
                output = new FileOutputStream(Environment
                        .getExternalStorageDirectory().toString()
                        + "/download_image.jpg");

                byte data[] = new byte[4096];
                int count;
                while ((count = input.read(data)) != -1) {
                    output.write(data, 0, count);
                }
            } catch (Exception e) {
            } finally {
                try {
                    if (input != null)
                        input.close();
                    if (output != null) {
                        output.close();
                    }
                } catch (IOException ignored) {
                }

                if (connection != null)
                    connection.disconnect();
            }
            return null;
        }

        protected void onPostExecute(Void result) {
            Drawable d = Drawable.createFromPath(Environment
                    .getExternalStorageDirectory().toString()
                    + "/download_image.jpg");
            view.setImageDrawable(d);
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setDataAndType(Uri.parse("file://"
                            + Environment.getExternalStorageDirectory()
                                    .toString() + "/download_image.jpg"),
                            "image/*");
                    mContext.startActivity(intent);
                }
            });
        };
    }

}


只要在activity中這樣寫:

    image = (ImageView) findViewById(R.id.image);
        new LoadAndSaveImage(getApplicationContext(), "http://toolongdidntread.com/wp-content/uploads/2011/06/upload.png", image);


三個參數分別是content,圖片的url,你要載入的imageview

BTW,由於這裡設定的儲存的jpg檔案名稱字是固定的,載入多張圖片時請用隨機數或者自行命名

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.