如何在Android上下載文件

一、使用系統下載管理器下載文件

Android系統提供了一個簡單易用的下載管理器,可以方便地下載文件。使用系統下載管理器下載文件的步驟如下:

1、在AndroidManifest.xml文件中加入以下下載權限。

<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" />

2、創建一個DownloadManager.Request對象,並設置下載文件的相關參數,如下載地址、標題、描述、存儲路徑等。

DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://example.com/file.mp3"));
request.setTitle("文件名");
request.setDescription("下載中...");
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "file.mp3");

3、獲取系統下載管理器,並調用enqueue方法添加下載任務。

DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
long downloadId = downloadManager.enqueue(request);

4、接收下載完成的廣播。

class DownloadReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
        DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadId);
        Cursor cursor = downloadManager.query(query);
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            if (status == DownloadManager.STATUS_SUCCESSFUL) {
                String fileName = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE));
                String filePath = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                Toast.makeText(context, fileName + "下載成功,保存路徑為:" + filePath, Toast.LENGTH_SHORT).show();
            } else {
                String reason = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
                Toast.makeText(context, "下載失敗,原因:" + reason, Toast.LENGTH_SHORT).show();
            }
        }
        cursor.close();
    }
}

二、使用OkHttp下載文件

在Android中,通常使用第三方庫OkHttp來實現HTTP請求,包括文件下載。使用OkHttp下載文件的步驟如下:

1、添加OkHttp庫的依賴。

dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.9.0'
}

2、創建OkHttpClient對象,並使用它來創建一個Request對象。

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("http://example.com/file.mp3")
        .build();

3、使用OkHttpClient對象執行Request請求,獲取Response對象。

Response response = client.newCall(request).execute();

4、通過Response對象獲取ResponseBody,將文件內容寫入本地文件中。

String fileName = "file.mp3";
File outFile = new File(getExternalFilesDir(null), fileName);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
    if (response.isSuccessful()) {
        inputStream = response.body().byteStream();
        outputStream = new FileOutputStream(outFile);
        byte[] buffer = new byte[4096];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.flush();
        Toast.makeText(this, fileName + "下載成功,保存路徑為:" + outFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "下載失敗,錯誤碼:" + response.code(), Toast.LENGTH_SHORT).show();
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (inputStream != null) {
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (outputStream != null) {
        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

三、使用DownloadTask下載文件

如果你不想使用系統下載管理器或者OkHttp庫,也可以通過自定義DownloadTask類來完成文件下載。DownloadTask通過HttpURLConnection發送請求,獲取文件內容後保存到本地文件中。DownloadTask實現文件下載的步驟如下:

1、創建一個DownloadTask類,繼承AsyncTask。

public class DownloadTask extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... params) {
        String url = params[0];
        String fileName = params[1];
        InputStream inputStream = null;
        OutputStream outputStream = null;
        HttpURLConnection connection = null;
        try {
            URL downloadUrl = new URL(url);
            connection = (HttpURLConnection) downloadUrl.openConnection();
            connection.connect();
            inputStream = connection.getInputStream();
            outputStream = new FileOutputStream(new File(getExternalFilesDir(null), fileName));
            byte[] buffer = new byte[4096];
            int len = 0;
            int totalLength = connection.getContentLength();
            int downloadedLength = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
                downloadedLength += len;
                if (totalLength > 0) {
                    publishProgress((int) (downloadedLength * 100 / totalLength));
                }
            }
            outputStream.flush();
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        int progress = values[0];
        Log.d("DownloadTask", "下載進度:" + progress);
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (result == null) {
            Toast.makeText(MainActivity.this, "下載失敗", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, result + "下載成功,保存路徑為:" + getExternalFilesDir(null) + "/" + result, Toast.LENGTH_SHORT).show();
        }
    }
}

2、通過DownloadTask的execute方法調用。

new DownloadTask().execute("http://example.com/file.mp3", "file.mp3");

3、在onProgressUpdate方法中更新下載進度。

以上就是三種不同的下載文件的方式,可以根據不同的場景選擇不同的方法。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/230575.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-10 18:18
下一篇 2024-12-10 18:18

相關推薦

發表回復

登錄後才能評論