Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 從網絡下載圖片並保存到 SD 卡

編輯:關於 Android 程式設計

做分享功能時遇到一個需求:分享出去的圖片不能直接引用網絡 URL,必須先落地到本地存儲。這裡把實現過程記錄下來。

第一步:申請權限

需要三項權限:訪問網絡、讀寫外部存儲,以及掛載/卸載文件系統。

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

需要提醒的是,從 Android 6.0(API 23)開始,WRITE_EXTERNAL_STORAGE 屬於危險權限,僅在清單中聲明是不夠的,必須在運行時通過 requestPermissions 動態申請,否則創建文件時會拋出 SecurityException。

第二步:異步下載並寫入文件

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

    @Override
    protected String doInBackground(String... params) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(params[0]);
        InputStream is = null;
        FileOutputStream fos = null;

        try {
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

                File f = new File(myJpgPath);
                f.createNewFile();

                fos = new FileOutputStream(f);
                byte[] buf = new byte[1024];
                int length;
                while ((length = is.read(buf)) != -1) {
                    fos.write(buf, 0, length);
                }
                fos.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { if (is != null) is.close(); } catch (IOException e) { }
            try { if (fos != null) fos.close(); } catch (IOException e) { }
        }
        return null;
    }
}

第三步:調用

public class MainActivity extends Activity {

    private static final String url =
        "https://ww3.sinaimg.cn/bmiddle/6e91531djw1e8l3c7wo7xj20f00qo755.jpg";

    private static final String myJpgPath =
        Environment.getExternalStorageDirectory() + "/pepper/test.png";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 確保目標目錄存在
        new File(myJpgPath).getParentFile().mkdirs();

        new MyImageAsync().execute(url);
    }
}

執行完成後,文件會出現在 /sdcard/pepper/test.png。

更值得推薦的現代寫法

示例中的 DefaultHttpClient 與 AndroidHttpClient 已在 Android 6.0 中被移除,AsyncTask 也早已不再推薦。今天更合適的組合是 HttpURLConnection 或 OkHttp 加上線程池 / Kotlin 協程,並配合 MediaScannerConnection 通知系統掃描新文件。下面是一個用 HttpURLConnection 的版本:

private void downloadWithHttpURLConnection(String urlStr, File target)
        throws IOException {
    HttpURLConnection conn = null;
    InputStream is = null;
    FileOutputStream fos = null;
    try {
        URL url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("GET");

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException("服務器返回異常狀態碼");
        }

        is = conn.getInputStream();
        fos = new FileOutputStream(target);
        byte[] buffer = new byte[8 * 1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.flush();
    } finally {
        if (is != null) try { is.close(); } catch (IOException ignored) { }
        if (fos != null) try { fos.close(); } catch (IOException ignored) { }
        if (conn != null) conn.disconnect();
    }
}

另外,從 Android 10(API 29)開始,直接使用 Environment.getExternalStorageDirectory() 隨意寫入共享存儲的方式受到分區存儲限制。若目標是讓其他應用也能訪問的媒體文件,應改用 MediaStore API;若只是本應用私有文件,則應寫入 getExternalFilesDir() 返回的目錄。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved