Как проверить активность, если файл не был загружен полностью, повторно загрузить его - PullRequest
0 голосов
/ 09 июля 2019

У меня такой вопрос: когда начинается загрузка, файл "music.mp3" попадает в каталог, но он не завершен. Я хочу проверить, не завершен ли файл, повторно загрузить его вот мой код:

Строка root = android.os.Environment.getExternalStorageDirectory () + "/folderName/music.mp3"; Файл wav = новый файл (корневой); длинная длина = длина волны ();

        if (!wav.isFile()) {

            // instantiate it within the onCreate method
            mProgressDialog = new ProgressDialog(TV_LG.this); // Downloading = activity name
            mProgressDialog.setMessage("downloading... . .");
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(true);

            // execute this when the downloader must be fired
            final DownloadTask downloadTask = new DownloadTask(TV_LG.this); // Downloading = activity name

downloadTask.execute ("http://dl.music.ml/1398/03/16/music.mp3"); // URL-адрес файла, который вы хотите загрузить

            mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    downloadTask.cancel(true);
                }
            });
            return;

        }
    }

закрытый класс DownloadTask расширяет AsyncTask {

    private Context context;

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

    @Override
    protected String doInBackground(String... sUrl) {
        // take CPU lock to prevent CPU from going off if the user
        // presses the power button during download
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                getClass().getName());
        wl.acquire();

        try {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                // expect HTTP 200 OK, so we don't mistakenly save error report
                // instead of the file
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();

                // this will be useful to display download percentage
                // might be -1: server did not report the length
                int fileLength = connection.getContentLength();

                // download the file
                input = connection.getInputStream();

                File root = android.os.Environment.getExternalStorageDirectory();
                File dir = new File(root.getAbsolutePath() + "/folderName");
                if (!dir.exists()) {
                    dir.mkdirs(); // build directory
                }
                output = new FileOutputStream(root.getAbsolutePath() + "/folderName/music.mp3");

                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    // allow canceling with back button
                    if (isCancelled())
                        return null;
                    total += count;
                    // publishing the progress....
                    if (fileLength > 0) // only if total length is known
                        publishProgress((int) (total * 100 / fileLength)); 

                    output.write(data, 0, count);
                }
            } catch (Exception e) {
                return e.toString();
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }

                if (connection != null)
                    connection.disconnect();
            }
        } finally {
            wl.release();
        }
        return null;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...