【发布时间】:2019-10-18 10:42:17
【问题描述】:
我有这个 AsyncTask 类的问题:
public class DownloadPDFTask extends AsyncTask<String, Void, File> {
private Context mContext;
private String mDownloadDIR = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
public DownloadPDFTask(Context mContext) {
this.mContext = mContext;
}
@Override
protected synchronized void onPreExecute() {
super.onPreExecute();
removeOldFiles();
}
@Override
protected synchronized File doInBackground(String... args) {
File retFile = null;
downloadFilePDF(args[0]);
File directory = new File(mDownloadDIR);
File[] files = directory.listFiles();
for (File file : files) {
if (file.getName().contains(".pdf")) {
retFile = file;
break;
}
}
return retFile;
}
@Override
protected synchronized void onPostExecute(File file) {
super.onPostExecute(file);
NotificationManager mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancelAll();
Intent mGoToPDFView = new Intent(mContext, PDFViewerActivity.class);
mGoToPDFView.putExtra("FILE", file);
mGoToPDFView.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(mGoToPDFView);
}
private void downloadFilePDF(String url) {
DownloadManager mDownloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
Uri mUri = Uri.parse(url);
DownloadManager.Request mReq = new DownloadManager.Request(mUri);
mReq.setTitle("Develop Test");
mReq.setDescription("PDF downloading....");
mReq.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
mReq.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "temp.pdf");
mReq.setMimeType("application/pdf");
mDownloadManager.enqueue(mReq);
}
private void removeOldFiles() {
File mDirectory = new File(mDownloadDIR);
if (mDirectory.isDirectory()) {
String[] children = mDirectory.list();
for (String child : children) {
if (child.contains(".pdf")) {
new File(mDirectory, child).delete();
}
}
}
}
}
如果我使用调试,我想清除下载文件夹,下载 PDF 和打开其他通过意图传递的文件创建的活动,然后慢慢进行过程工作,但在运行时,onPostExecute 方法在 doInBackground 方法之前调用。
你能帮帮我吗?
【问题讨论】:
-
"在 doInBackground 方法之前调用的 onPostExecute 方法" - 你有什么证据?
enqueue()onDownloadManager不会立即下载任何内容,因此运行速度非常快。这里唯一需要在后台线程上的代码是删除文件,这是您专门不在后台线程上拥有的代码。
标签: java android pdf android-asynctask