android 下载网络文件

工具类

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

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

public class FileDownloader extends AsyncTask<String, Integer, String> {
    private Context context;
    private ProgressDialog progressDialog;

    public FileDownloader(Context context) {
        this.context = context;
    }

    // 执行下载前的准备工作
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Downloading file...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    // 后台下载文件
    @Override
    protected String doInBackground(String... params) {
        String fileUrl = params[0];
        String fileName = params[1];
        String filePath = Environment.getExternalStorageDirectory().getPath() + "/" + fileName;

        try {
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            int fileLength = connection.getContentLength();

            InputStream input = new BufferedInputStream(url.openStream());
            FileOutputStream output = new FileOutputStream(filePath);

            byte[] data = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
        } catch (IOException e) {
            Log.e("FileDownloader", "Error: " + e.getMessage());
        }

        return filePath;
    }

    // 更新下载进度
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressDialog.setProgress(values[0]);
    }

    // 下载完成后执行的操作
    @Override
    protected void onPostExecute(String filePath) {
        super.onPostExecute(filePath);
        progressDialog.dismiss();
        // 在这里可以处理文件下载完成后的逻辑,比如打开文件等操作
    }
}

调用示例

String fileUrl = "http://www.example.com/file.pdf";
String fileName = "file.pdf";

FileDownloader downloader = new FileDownloader(this);
downloader.execute(fileUrl, fileName);

注意事项

添加相应权限

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

你可能感兴趣的:(android,android)