DownloadManager 在 Android 中无法在 Fragment 中工作

DownloadManager not working inside Fragment in Android

我正在尝试使用 DownloadManager 下载文件

相同的代码在 Activity 中有效,但在 Fragment 中无效。有什么问题?下面的文字可能是问题所在,但请查看整个代码

在Activity我用了DownloadManager manager = (DownloadManager) getBaseContext().getSystemService(Context.DOWNLOAD_SERVICE);

在片段中我使用了DownloadManager manager = (DownloadManager) getActivity().getBaseContext().getSystemService(Context.DOWNLOAD_SERVICE); 里面 download.setOnClickListener()

 String myHTTPurl = "http://status9.in/ankushfiles/it2.html";
  File file;
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    String title = getTitle();
    webView = (WebView) getActivity().findViewById(R.id.webView);
    download = (Button) getActivity().findViewById(R.id.bDownloadTT);


    file = new File(Environment.getExternalStoragePublicDirectory("/sdcard/KiiTTimeTableData"), "it2.html");
    if(file.exists())
    {
        Toast.makeText(getActivity(), "File Exists", Toast.LENGTH_SHORT).show();
        webView.loadUrl("file://"+Environment.getExternalStorageDirectory()+"/sdcard/KiiTTimeTableData/it2.html");
    }
    else
    {
        Toast.makeText(getActivity(), "File Does Not Exist", Toast.LENGTH_SHORT).show();
        webView.setVisibility(View.INVISIBLE);
    }

    download.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            file.delete();
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myHTTPurl));
            request.setTitle("File Download");
            request.setDescription("Downloading....");

            //request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            String nameOfFile = URLUtil.guessFileName(myHTTPurl, null, MimeTypeMap.getFileExtensionFromUrl(myHTTPurl));

            request.setDestinationInExternalPublicDir("sdcard/KiiTTimeTableData", nameOfFile);
            DownloadManager manager = (DownloadManager) getActivity().getBaseContext().getSystemService(Context.DOWNLOAD_SERVICE);
            manager.enqueue(request);
        }
    });

}

在片段中,我认为您应该在 onCreateView 方法中初始化和 return 视图。阅读以下文章:

When to use onCreateView for fragments?

你的错误日志是什么?

您确定已声明以下两个权限吗?

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