1. 程式人生 > >Android下載網路圖片並儲存在本地相簿中

Android下載網路圖片並儲存在本地相簿中

package com.thfund.bigtree.StarCounselor.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.thfund.bigtree.R;
import com.thfund.bigtree.base.BaseActivity;
import com.thfund.bigtree.utils.ToastUtil;

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

public class StarWeChatQRActivity extends BaseActivity implements View.OnClickListener {
    private ImageView showImageView;//顯示圖片ImageView
    private Button mSaveBtn;//儲存圖片按鈕
    private String imgURl;//圖片的URL地址
    private static final int SAVE_SUCCESS = 0;//儲存圖片成功
    private static final int SAVE_FAILURE = 1;//儲存圖片失敗
    private static final int SAVE_BEGIN = 2;//開始儲存圖片
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SAVE_BEGIN:
                    ToastUtil.showMsg("開始儲存圖片...");
                    mSaveBtn.setClickable(false);
                    break;
                case SAVE_SUCCESS:
                    ToastUtil.showMsg("圖片儲存成功,請到相簿查詢");
                    mSaveBtn.setClickable(true);
                    break;
                case SAVE_FAILURE:
                    ToastUtil.showMsg("圖片儲存失敗,請稍後再試...");
                    mSaveBtn.setClickable(true);
                    break;
            }
        }
    };

    /**
     * 開啟該Activity的一種靜態方式
     *
     * @param context
     * @param imgURl
     */
    public static void startActivity(Context context, String imgURl) {
        Intent intent = new Intent(context, StarWeChatQRActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("imgURl", imgURl);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_star_we_chat_qr);
        initViews();
        initData();
    }

    /**
     * 初始化控制元件
     */
    private void initViews() {
        showImageView = (ImageView) findViewById(R.id.image_view);
        mSaveBtn = (Button) findViewById(R.id.save_btn);
        mSaveBtn.setOnClickListener(this);
    }

    /**
     * 初始化資料
     */
    private void initData() {
        //我的ImageURL是上一級傳參過來的
        imgURl = getIntent().getStringExtra("imgURl");
        //用Glide將圖片加載出來
        Glide.with(mContext).load(imgURl).fitCenter().crossFade().into(showImageView);
    }

    /**
     * 點選事件處理
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.save_btn://儲存圖片
                mSaveBtn.setClickable(false);//不可重複點選
                //儲存圖片必須在子執行緒中操作,是耗時操作
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mHandler.obtainMessage(SAVE_BEGIN).sendToTarget();
                        Bitmap bp = returnBitMap(imgURl);
                        saveImageToPhotos(mContext, bp);
                    }
                }).start();
                break;
        }
    }

    /**
     * 儲存二維碼到本地相簿
     */
    private void saveImageToPhotos(Context context, Bitmap bmp) {
        // 首先儲存圖片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 其次把檔案插入到系統圖庫
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            mHandler.obtainMessage(SAVE_FAILURE).sendToTarget();
            return;
        }
        // 最後通知相簿更新
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        context.sendBroadcast(intent);
        mHandler.obtainMessage(SAVE_SUCCESS).sendToTarget();
    }

    /**
     * 將URL轉化成bitmap形式
     *
     * @param url
     * @return bitmap type
     */
    public final static Bitmap returnBitMap(String url) {
        URL myFileUrl;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
            HttpURLConnection conn;
            conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 點選除了按鈕的任何一個地方,finish掉
     *
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                finish();
                break;
        }
        return super.onTouchEvent(event);
    }
}