【发布时间】:2017-05-28 22:48:36
【问题描述】:
我编写了一个应用程序,我可以在其中从服务器下载 pdf 文件。
当我点击下载按钮时,我可以在顶部看到正在下载的标志,但随后它停止并告诉我“下载完成”。
当我尝试打开文件或在文件夹中搜索它时,找不到它并告诉我“文件路径不存在”。
我在清单中添加了“WRITE_EXTERNAL_STORAGE”和“Internet”权限。
我必须在代码中添加权限检查/请求吗?
FragmentDownloads.java
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class FragmentDownloads extends Fragment implements View.OnClickListener {
Button buttonCV;
View view;
public FragmentDownloads() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_downloads, container, false);
buttonCV = (Button) view.findViewById(R.id.buttonCV);
buttonCV.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
DownloadManager downloadManager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("https://cvdatabase.000webhostapp.com/file.pdf");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
}
}
附加问题:最后的对象“引用”是灰色的。在 YouTube 视频中,不知何故。我是初学者,不知道为什么。
fragment_downloads.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="androfenix.mycvapp.FragmentDownloads">
<!-- TODO: Update blank fragment layout -->
<Button
android:id="@+id/buttonCV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</FrameLayout>
已解决: 我必须添加必须下载文件的目录路径。 .setDestinationInExternalFilesDir(getActivity().getApplicationContext(), Environment.DIRECTORY_DOWNLOADS, "filename.pdf");
【问题讨论】:
标签: android button fragment onclicklistener