Как проверить, завершена ли загрузка в библиотеке извлечения onCreate android? - PullRequest
0 голосов
/ 16 марта 2020

Как проверить, завершена ли загрузка в библиотеке извлечения onCreate? Следующий код работает без проблем, но, возможно, пользователь отменит операцию загрузки до завершения, и в пути будет найден неполный файл.

public class MainActivity extends AppCompatActivity implements FetchObserver<Download> {

    private Button Edame, tavaghof, DownloadImage, online;
    public static TextView etaTextView;
    public static TextView downloadSpeedTextView;
    public static Request request;
    public static Fetch fetch;
    public static ProgressBar progressBar;
    public static TextView progressTextView;
    private LinearLayout dllaye;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            File root = android.os.Environment.getExternalStorageDirectory();
            File path = new File(root.getAbsolutePath() + "/telavat/" + "naba.mp3");
            if (path.exists()) {
                dllaye.setVisibility(View.GONE);
            }
        } catch (Exception e) {

        }

        FetchConfiguration fetchConfiguration = new FetchConfiguration.Builder(this)
                .setDownloadConcurrentLimit(3)
                .build();

        fetch = Fetch.Impl.getInstance(fetchConfiguration);

        DownloadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    enqueueDownload();
            }
        });

        Edame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                fetch.resume(request.getId());
            }
        });
        tavaghof.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                fetch.pause(request.getId());
            }
        });

//EndOnceate
    }


    private void enqueueDownload() {
        File root = android.os.Environment.getExternalStorageDirectory();
        final String url = "https://amoozesh3.ir/play/naba.mp3";
        final String filePath = root.getAbsolutePath() + "/telavatquran/" + Uri.parse(url).getLastPathSegment();
        request = new Request(url, filePath);
        request.setExtras(getExtrasForRequest(request));

        fetch.attachFetchObserversForDownload(request.getId(), this)
                .enqueue(request, new Func<Request>() {
                    @Override
                    public void call(@NotNull Request result) {
                        request = result;
                    }
                }, new Func<Error>() {
                    @Override
                    public void call(@NotNull Error result) {
                    }
                });

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (request != null) {
            fetch.attachFetchObserversForDownload(request.getId(), this);
        }
    }

   @Override
    protected void onPause() {
        super.onPause();
        if (request != null) {
            fetch.removeFetchObserversForDownload(request.getId(), this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
       fetch.close();
    }

    @Override
    public void onChanged(Download data, @NotNull Reason reason) {
        updateViews(data, reason);
    }

    private Extras getExtrasForRequest(Request request) {
        final MutableExtras extras = new MutableExtras();
        extras.putBoolean("testBoolean", true);
        extras.putString("testString", "test");
        extras.putFloat("testFloat", Float.MIN_VALUE);
        extras.putDouble("testDouble", Double.MIN_VALUE);
        extras.putInt("testInt", Integer.MAX_VALUE);
        extras.putLong("testLong", Long.MAX_VALUE);
        return extras;
    }

    private void updateViews(@NotNull Download download, Reason reason) {
        if (request.getId() == download.getId()) {
            if (reason == Reason.DOWNLOAD_COMPLETED) {
                dllaye.setVisibility(View.GONE);
                Toast.makeText(getApplicationContext(), "File download successful",
                        Toast.LENGTH_LONG).show();

            }
            setProgressView(download.getStatus(), download.getProgress());

            etaTextView.setText(Utils.getETAString(this, download.getEtaInMilliSeconds()));
            downloadSpeedTextView.setText(Utils.getDownloadSpeedString(this, download.getDownloadedBytesPerSecond()));

        }
    }


    private void setProgressView(@NonNull final Status status, final int progress) {

        switch (status) {
            case QUEUED: {
                progressTextView.setText(R.string.queued);
                progressBar.setProgress(progress);

                break;
            }
            case ADDED: {
                progressTextView.setText(R.string.added);
                progressBar.setProgress(progress);

                break;
            }
            case DOWNLOADING: {
                if (progress == -1) {
                    progressTextView.setText(R.string.downloading);
                    progressBar.setProgress(progress);

                } else {
                    final String progressString = getResources().getString(R.string.percent_progress, progress);
                    progressTextView.setText(progressString);
                    progressBar.setProgress(progress);
                }
                break;
            }

            case COMPLETED: {

                break;
            }
            default: {
                progressTextView.setText(R.string.status_unknown);
                progressBar.setProgress(progress);

                break;
            }
        }
    }

}

Я хочу освободить больше места на экране после загрузки

Как я могу понять, что загрузка завершена?

Буду признателен за сотрудничество.

...