将带有 url 的文件下载到内部存储 Android Studio 时出错

Error when downloading a file with url into internal storage Android Studio

我正在尝试将 mp3 音乐下载到内部存储中,但 conexion.connect(); 似乎出现错误并最终进入异常。

这是我的代码:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        String filePath = getExternalCacheDir().getAbsolutePath();
        filePath += "/audiotest.mp3";

        int count;
        try {
            URL url = new URL("my_url_to_download");
            URLConnection  conexion = url.openConnection();
            conexion.connect(); //here is the error

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

            byte data[] = new byte[1024];

            while ((count = input.read(data)) != -1) {
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
            Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
        }
    }
}

首先需要在manifest文件中添加用户权限:

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

接下来,要求用户授予权限(您可以将此代码放在您的 onCreate 中):

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_DENIED) {
            Log.d("permission", "permission denied to WRITE_EXTERNAL_STORAGE - requesting it");
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            requestPermissions(permissions, 1);
        }
    }

使用以下代码:

try {
                                    ProgressDialog progress;
                                    Update downloadAndInstall = new Update();
                                    progress = new ProgressDialog(YourActivity.this);
                                    progress.setCancelable(false);
                                    progress.setMessage("Downloading...");
                                    downloadAndInstall.setContext(getApplicationContext(), progress);
                                    downloadAndInstall.execute("http://yourURL.com/music.mp3");
                                } catch (Exception e) {

                                }

现在是异步任务方法:

public class Update extends AsyncTask<String, Void, Void> {

    private ProgressDialog progressDialog;
    private int status = 0;

    private Context context;

    public void setContext(Context context, ProgressDialog progress) {
        this.context = context;
        this.progressDialog = progress;
    }

    public void onPreExecute() {
        progressDialog.setTitle("Downloading New Updates");
        progressDialog.setMessage("This might take a while...");
        progressDialog.setIndeterminate(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.show();
    }

    @Override
    protected Void doInBackground(String... arg0) {
        try {
            URL url = new URL(arg0[0]);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            int fileLength = c.getContentLength();

            ContextWrapper cw = new ContextWrapper(context);

            String PATH = Environment.getExternalStorageDirectory() + "/download/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, "music.mp3");
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is ;
            int status = c.getResponseCode();
            if (status != HttpURLConnection.HTTP_OK)
                is = c.getErrorStream();
            else
                is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            long total = 0;
            while ((len1 = is.read(buffer)) != -1) {
                total += len1;
                publishProgress((int) (total * 100 / fileLength));
                fos.write(buffer, 0, len1);
            }
            fos.flush();
            fos.close();
            is.close();

        } catch (FileNotFoundException fnfe) {
            status = 1;
            Log.e("File", "FileNotFoundException! " + fnfe);
        } catch (Exception e) {
            Log.e("UpdateAPP", "Exception " + e);
        }
        return null;
    }

    private void publishProgress(int i) {
        progressDialog.setProgress(i);
    }

    public void onPostExecute(Void unused) {
        progressDialog.dismiss();
    }
}

此方法会将文件下载到内部存储的下载目录中。而且我还添加了进度对话框来显示下载进度。