要求:确保在用户离开PDF查看屏幕后从设备中删除PDF文档
代码:请注意首先调用createFile()
,然后调用startActivityForIntentResult()
private File file;
private ArrayList<Uri> uriList = new ArrayList<Uri>();
private void createFile() {
int fileNameLength = pdfFileName[0].length();
String fileName = pdfFileName[0].substring(0, fileNameLength - 4) + DateTime.now();
String fileExtension = pdfFileName[0].substring(fileNameLength - 4, fileNameLength);
byte[] content = Base64.decodeBase64(pdfData[0].getBytes());
BufferedOutputStream outputStream = null;
try {
File path = new File(getExternalFilesDir(null).getAbsolutePath(), "temp");
if (!path.exists()) {
path.mkdirs();
}
file = new File(path, fileName + fileExtension);
outputStream = new BufferedOutputStream(new FileOutputStream(file));
outputStream.write(content);
file.deleteOnExit();
uriList.add(Uri.fromFile(file));
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static int REQUEST_CODE = 1;
private Intent intent;
private void startActivityForIntentResult() {
if (file.exists()) {
Uri targetUri = uriList.get(0);
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
startActivityForResult(intent, REQUEST_CODE);
}
catch (ActivityNotFoundException e) {
toastTitle = "Error Displaying PDF";
toastMessage = "Please make sure you have an application for viewing PDFs installed on your device and try again.";
toast = new GenericCustomToast();
toast.show(toastTitle, toastMessage, QueryForPDF.this);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_CANCELED && requestCode == REQUEST_CODE) {
if(!file.delete()) {
file.delete();
}
}
searchAgain();
}
@Override
public void onBackPressed() {
super.onBackPressed();
if(!file.delete()) {
file.delete();
}
searchAgain();
}
@Override
public void onStop() {
super.onStop();
if(!file.delete()) {
file.delete();
}
}
@Override
public void onDestroy() {
super.onDestroy();
if(!file.delete()) {
file.delete();
}
}
编辑:我也尝试过实施回调,绝对确定createFile()
已经完成了它的工作。我甚至尝试添加延迟(不同时间增量)以及为Intent.FLAG_GRANT_READ_URI_PERMISSION
,Intent.FLAG_GRANT_WRITE_URI_PERMISSION
和Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
添加(完全不必要的)标记。
答案 0 :(得分:0)
我仍然不知道为什么这是有效的,但这是解决方案以防其他人遇到此问题:
它是创建文件的目录。出于某种原因,在两台三星设备上,与华硕设备相比,访问或创建文件的方式有所不同。因此File path = new File(getExternalFilesDir(null).getAbsolutePath(), "temp");
变为File path = new File(getExternalCacheDir().getAbsolutePath());
,问题就会消失。