Менеджер загрузок, загрузка файлов в пакете приложения

Я создал веб-просмотр и добавил к нему прослушиватель загрузки. Когда я загружаю файл в приложение, он сохраняет файл в пакете приложения, а не в общедоступной папке загрузок.

Сомневаюсь, что это связано с использованным мной фрагментом или строкой (request.setDestinationInExternalFilesDir (getActivity (). GetApplicationContext (), Environment.DIRECTORY_DOWNLOADS, "test.jpg");). Пожалуйста помоги.

Заранее спасибо.

Скачал в папку: /storage/emulated/0/Android/data/packagename/files/Download/test.jpg

import android.app.DownloadManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import static android.content.Context.DOWNLOAD_SERVICE;

public class home extends Fragment {
    private WebView webView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.home, container, false);

        webView = (WebView) view.findViewById(R.id.testview);
        webView.getSettings().setJavaScriptEnabled(true);

        webView.getSettings().setDisplayZoomControls(false);

        webView.clearCache(true);

        // Change to your own forum url
        webView.loadUrl("https://example.com");

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                view.loadUrl("about:blank");
                Toast.makeText(getActivity(), "Error occurred, please check network connectivity", Toast.LENGTH_SHORT).show();
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // Loads only your forum domain and no others!
                if (url.contains("example") == true) {
                    view.loadUrl(url);
                    // If they are not your domain, use browser instead
                } else {
                    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(i);
                }
                return true;
            }
        });

        webView.setDownloadListener(new DownloadListener() {

            @Override
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimeType,
                                        long contentLength) {
                DownloadManager.Request request = new DownloadManager.Request(
                        Uri.parse(url));
                request.setMimeType("image/jpeg");
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription("Downloading file...");
                request.setTitle("test.jpg");
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalFilesDir(getActivity().getApplicationContext(),
                        Environment.DIRECTORY_DOWNLOADS,"test.jpg");
                DownloadManager dm = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
                dm.enqueue(request);
                Toast.makeText(getActivity().getApplicationContext(), "Downloading File. Usually takes 5 seconds.",
                        Toast.LENGTH_LONG).show();
            }
        });
        //returning our layout file
        //change R.layout.yourlayoutfilename for each of your fragments
        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //you can set the title for your toolbar here for different fragments different titles
        getActivity().setTitle("Home");
    }
}

это помогает?

David Medenjak 22.07.2018 10:56
0
1
510
1

Ответы 1

Попробуйте код ниже:

request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);

Здесь request.setDestinationInExternalPublicDir загрузит ваш файл в общий каталог, а Environment.DIRECTORY_DOWNLOADS - это имя каталога. Ваш файл будет помещен в папку "Загрузки". Если вы хотите загрузить свой файл в определенную папку, вы можете указать путь к каталогу вместо Environment.DIRECTORY_DOWNLOADS.

Другие вопросы по теме