Ошибка при загрузке файла с URL-адресом во внутреннее хранилище Android Studio

#android-studio #url #mp3 #internal-storage

#android-studio #url #mp3 #внутреннее хранилище

Вопрос:

Я пытаюсь загрузить музыку в формате 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();
        }
    }
}
  

Ответ №1:

Прежде всего, вам нужно добавить разрешение пользователя в файл манифеста :

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

                                }
  

Теперь для метода asynctask :

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

Этот метод загрузит файл в ваш каталог загрузки во внутреннем хранилище. А также я добавил диалоговое окно прогресса, чтобы показать ход загрузки.

введите описание изображения здесь