基於Android 下載檔案時,更新UI簡單協助類

來源:互聯網
上載者:User

標籤:下載   工具   

由於在項目開發時,有這樣的簡單需求,問Google,網路上也有好多Utils工具類,但是比較冗餘。自己就簡單的寫了一個簡單協助類。

/** * 下載檔案,更新UI簡單協助類 *  * @author jarlen *  */public class DownLoadHelper{    private static final int DOWN_BEGIN = 0;    private static final int DOWN_UPDATA = 1;    private static final int DOWN_FINISH = 2;    private static final int DOWN_ERROR = 3;    private Context mContext;    private TextView mTextView;    private ProgressBar mBar;    private Handler handler = new Handler()    {        public void handleMessage(Message msg)        {            if (!Thread.currentThread().isInterrupted())            {                switch (msg.what)                {                case DOWN_BEGIN:                    if (mTextView != null)                    {                        mTextView.setText("開始下載");                    }                    if(mBar != null)                    {                        mBar.setProgress(0);                    }                    break;                case DOWN_UPDATA:                    int factor = msg.arg1;                    if (mTextView != null)                    {                        mTextView.setText(factor + "%");                    }                    if(mBar != null)                    {                        mBar.setProgress(factor);                    }                    break;                case DOWN_FINISH:                    if (mTextView != null)                    {                        mTextView.setText("下載完成");                    }                    if(mBar != null)                    {                        mBar.setProgress(100);                    }                    break;                case DOWN_ERROR:                    if (mTextView != null)                    {                        mTextView.setText("下載錯誤");                    }                    if(mBar != null)                    {                        mBar.setProgress(0);                    }                    break;                default:                    break;                }            }        };    };    public DownLoadHelper(Context context)    {        this.mContext = context;    }    /**     * 設定下載時,需要更新的UI TextView     * @param view     */    public void setUpdataView(TextView view)    {        this.mTextView = view;    }    /**     * 設定下載時,需要更新的UI,ProgressBar     * @param bar     */    public void setUpdataBar(ProgressBar bar)    {        this.mBar = bar;    }    /**     * 開始下載     * @param url     * 檔案     * @param path     * 檔案儲存地址     */    public void startDownLoad(final String url, final String path)    {        new Thread()        {            public void run()            {                sendMsg(DOWN_BEGIN, 0);                try                {                    long downloadSize = downloadUpdateFile(url, path);                    if (downloadSize > 0)                    {                        sendMsg(DOWN_FINISH, 0);                    }                } catch (Exception e)                {                    e.printStackTrace();                    sendMsg(DOWN_ERROR, 0);                }            };        }.start();    }    private long downloadUpdateFile(String down_url, String path)            throws Exception    {        int down_step = 1;// 提示step        int totalSize;// 檔案總大小        int downloadCount = 0;// 已經下載好的大小        int updateCount = 0;// 已經上傳的檔案大小        InputStream inputStream;        OutputStream outputStream;        URL url = new URL(down_url);        HttpURLConnection httpURLConnection = (HttpURLConnection) url                .openConnection();        httpURLConnection.setConnectTimeout(30 * 1000);        httpURLConnection.setReadTimeout(30 * 1000);        // 擷取下載檔案的size        totalSize = httpURLConnection.getContentLength();        if (httpURLConnection.getResponseCode() == 404)        {            sendMsg(DOWN_ERROR, 0);            throw new Exception("fail!");        }        inputStream = httpURLConnection.getInputStream();        File dir = new File(path);        if (!dir.exists())        {            dir.mkdir();        }        String name = down_url.substring(down_url.lastIndexOf("/") + 1,                down_url.length());        File updateFile = new File(dir, name);        outputStream = new FileOutputStream(updateFile, false);// 檔案存在則覆蓋掉        byte buffer[] = new byte[1024];        int readsize = 0;        while ((readsize = inputStream.read(buffer)) != -1)        {            outputStream.write(buffer, 0, readsize);            downloadCount += readsize;// 時時擷取下載到的大小            // 每次增長1%            if (updateCount == 0                    || (downloadCount * 100 / totalSize - down_step) >= updateCount)            {                updateCount += down_step;                sendMsg(DOWN_UPDATA, updateCount);            }        }        if (httpURLConnection != null)        {            httpURLConnection.disconnect();        }        inputStream.close();        outputStream.close();        return downloadCount;    }    private void sendMsg(int flag, int factor)    {        Message msg = new Message();        switch (flag)        {        case DOWN_BEGIN:// 開始        case DOWN_FINISH:// 完成        case DOWN_ERROR:// 失敗            break;        case DOWN_UPDATA:// 更新進度條            msg.arg1 = factor;            break;        default:            break;        }        msg.what = flag;        handler.sendMessage(msg);    }}

使用時簡單說明下;

DownLoadHelper helper1 = new DownLoadHelper(this);helper1.setUpdataView(tv1);helper1.startDownLoad("http://img1.2345.com/appsimg/wallpaper/4/139460306960.jpg", path);

/********************************************/

Demo源碼
http://download.csdn.net/detail/jarlen/8552443

沒有認真地檢查,可能有bug,使用的夥伴請自己debug下,並通知我一下,謝謝

基於Android 下載檔案時,更新UI簡單協助類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.