我正在尝试使用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);
}
});
}
答案 0 :(得分:0)
在片段中我认为你应该在onCreateView方法中初始化并返回视图。阅读以下文章:
Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments When to use onCreateView for fragments?
你的错误日志是什么?
您确定已宣布以下两项权限吗?
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />