【发布时间】:2023-01-30 17:06:39
【问题描述】:
所以我有一个片段,我在其中向用户显示某些内容的条款和条件,这些条款和条件采用从服务器检索的 pdf 文件的形式。
这是检索 pdf 并为 pdfView 提供输入流以显示数据的代码。
class RetrievePDFFromUrl extends AsyncTask<String, Void, InputStream> {
@Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
if (urlConnection.getResponseCode() == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return inputStream;
}
@Override
protected void onPostExecute(InputStream inputStream) {
pdfView.fromStream(inputStream).load();
}
}
到目前为止,一切都很好。 但现在我必须添加共享和保存文档的功能。 问题是我必须使用其他代码来完成任务。 而且由于我无法在不下载的情况下共享该文档,所以它有点乱。 这是我下载文档的方式。
private void downloadPDFContent(){
String fileName = getCurrentDocumentName();;
String urlToDownload = !secondDocument ? documentUrl1 : documentUrl2;
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
if (outputFile.exists()) {
return;
}
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(urlToDownload));
request.setTitle(fileName);
request.setMimeType("application/pdf");
request.allowScanningByMediaScanner();
request.setAllowedOverMetered(true);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager downloadManager = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
downloadManager.enqueue(request);
}
尝试共享文档时出现问题,在尝试共享文档之前延迟 200 毫秒是错误的,因为没有人知道有时连接有多慢并且无法正常工作。
private void shareDocument() {
downloadPDFContent();
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getCurrentDocumentName());
Uri uri = FileProvider.getUriForFile(getContext(),
getContext().getPackageName() + ".provider", outputFile);
Intent share = new Intent();
share.setAction(Intent.ACTION_SEND);
share.setType("application/pdf");
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share document"));
}
}, 200);
}
有没有人有更好的想法我怎样才能完成这 3 个任务 - 使用输入流加载文档供用户查看和共享/保存它,同时重用代码而不是以不同和不稳定的方式进行?
【问题讨论】: