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

戏子无情 提交于 2021-01-29 18:23:06

问题


I'm trying to download a mp3 music into internal storage, but conexion.connect(); seems like it have a error and end up going to the Exception.

Here is my code:

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();
        }
    }
}

回答1:


First of all, you need to add user permission in the manifest file :

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

Next, ask the user to grant permission (you can put this code inside your 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);
        }
    }

Use the following code :

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) {

                                }

Now for the asynctask method :

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();
    }
}

This method will download the file to your Download directory in internal storage. And also I added progress dialog to show the download progress.



来源:https://stackoverflow.com/questions/64000457/error-when-downloading-a-file-with-url-into-internal-storage-android-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!