1. 程式人生 > >用URL 下載圖片(程式碼) (6.0許可權)

用URL 下載圖片(程式碼) (6.0許可權)

首先我們知道要用到安卓讀寫許可權
只需要在AndroidManifest檔案中宣告即可,就像下面這樣:

 <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

在build.gradle 裡 導一個包:

compile 'com.master.android:permissionhelper:1.4'

在java程式碼裡,用到了6.0以上版本的許可權 :

package com.example.lenovo.myapplication.download;

import android.Manifest;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import
android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import com.example.lenovo.myapplication.R; import com.master.permissionhelper.PermissionHelper; public class Download extends AppCompatActivity { private ProgressBar progressBar; private
Button download_btn; private ImageView imageView; private String TAG = "HelloActivity"; private PermissionHelper permissionHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_download); permissionHelper = new PermissionHelper(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100); permissionHelper.request(new PermissionHelper.PermissionCallback() { @Override public void onPermissionGranted() { Log.d(TAG, "onPermissionGranted() called"); } @Override public void onIndividualPermissionGranted(String[] grantedPermission) { Log.d(TAG, "onIndividualPermissionGranted() called with: grantedPermission = [" + TextUtils.join(",",grantedPermission) + "]"); } @Override public void onPermissionDenied() { Log.d(TAG, "onPermissionDenied() called"); } @Override public void onPermissionDeniedBySystem() { Log.d(TAG, "onPermissionDeniedBySystem() called"); } }); progressBar=findViewById(R.id.main_progressbar); download_btn=findViewById(R.id.download_btn); imageView=findViewById(R.id.main_ImageView); download_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { download_btn.setEnabled(false); //構造方法初始化 DownloadTask dTask = new DownloadTask(Download.this,download_btn,progressBar,imageView); //執行任務 dTask.execute("http://img31.mtime.cn/mg/2012/10/30/201631.37192876.jpg","fra.jpg"); } }); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (permissionHelper != null) { permissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults); } } }

對xml的佈局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.lenovo.myapplication.download.Download">


    <ProgressBar
        android:layout_marginTop="45dp"
        android:id="@+id/main_progressbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        />
    <Button
        android:layout_marginTop="45dp"
        android:id="@+id/download_btn"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:text="下載"
        />
    <ImageView
        android:id="@+id/main_ImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

在內部類裡面 :

package com.example.lenovo.myapplication.download;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
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.MalformedURLException;
import java.net.URL;


public class DownloadTask extends AsyncTask<String, Integer, Integer> {

    private Context context;
    private Button btn;
    private ProgressBar pBar;
    private String SDPATH = "";
    private String PATH="";
    private ImageView img;
    private String fileName;
    /**
     * 構造方法
     * @param context Activity上下文環境
     * @param btn   下載按鈕
     * @param pBar  進度條
     */
    public DownloadTask(Context context, Button btn, ProgressBar pBar, ImageView imageView) {
        this.context = context;
        this.btn = btn;
        this.pBar = pBar;
        this.SDPATH = Environment.getExternalStorageDirectory() + "/";
        this.PATH = this.SDPATH+"downod_pica/";
        this.img=imageView;

    }

    @Override
    protected Integer doInBackground(String... params) {
        //定義輸入流和輸出流物件
        InputStream inputStream = null;
        OutputStream outputStream = null;
        //定義檔案物件
        File file = null;
        //判斷檔案是否存在
        if (isFileExists(PATH+params[1])) {
            //如果存在,直接返回,執行onPostExecute方法
            return -1;
        }
        try {
            //建立URL物件
            URL url = new URL(params[0]);
            //通過URL物件建立HTTP連線
            HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
            //判斷返回碼
            if (httpUrlConnection.getResponseCode() == 200) {
                inputStream = httpUrlConnection.getInputStream();
                // 更新進度條(設定進度條總長度)
                publishProgress(-2, httpUrlConnection.getContentLength());
            } else {
                // 下載有誤,網路連線錯誤
                publishProgress(-1);
            }
            //建立目錄
            createDir(PATH);
            //建立檔案
            file = createFile(PATH+params[1]);
            fileName = PATH+params[1];
            //建立輸出流
            outputStream = new FileOutputStream(file);
            //建立緩衝區
            byte buffer[] = new byte[4*1024];
            int length = 0;
            int sum = 0;
            while((length = inputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,length);
                //已經下載的長度
                sum+=length;
                //更新進度條
                publishProgress(0,sum);
            }
            outputStream.flush();//強制把緩衝區的資料寫入到檔案並清空緩衝區

        } catch (IOException e) {
            e.printStackTrace();
        }

        return 0;
    }

    /**
     * 下載過程中執行此方法
     * @param
     */
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

        switch (values[0]) {
            case 0:
                pBar.setProgress(values[1]);
                break;
            case -1:
                Toast.makeText(context, "網路連線錯誤,請檢查下載連結是否正確", Toast.LENGTH_LONG).show();
                break;
            case -2:
                pBar.setMax(values[1]);
                break;
            default:
                break;
        }
    }

    /**
     * 下載完成後執行此方法
     * @param result
     */
    @Override
    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
        btn.setEnabled(true);
        switch (result) {
            case -1:
                Bitmap bm2= BitmapFactory.decodeFile(fileName);
                img.setImageBitmap(bm2);
                Toast.makeText(context, "檔案已存在", Toast.LENGTH_LONG).show();
                break;
            case 0:
                Bitmap bm= BitmapFactory.decodeFile(fileName);
                img.setImageBitmap(bm);
                Log.e("TASK","下載完成");

                break;
        }
    }

    /**
     * 工具方法——判斷檔案已存在
     *
     * @return
     */
    private boolean isFileExists(String fileName) {
        File file = new File(fileName);
        if (file.exists()) {
            // 檔案已存在
            return true;
        }
        return false;
    }
    /**
     * 工具方法——建立目錄
     */
    private boolean createDir(String dirName) {
        File file = new File(dirName);
        boolean isCreateDir = file.mkdir();
        return isCreateDir;
    }
    /**
     * 工具方法——建立檔案
     * @param fileName
     */
    private File createFile(String fileName) {
        File file = new File(fileName);
        boolean isCreateFile  = false;
        try {
            isCreateFile = file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

}

效果圖:

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述