android - 成功将文件写入磁盘存储后如何打开文件
问题描述
所以我有这种方法可以从我的服务器写入写入存储的响应结果。
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
File filesDir = getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
assert filesDir != null;
downloadedFile = new File(filesDir,
"file_name" + ".pdf");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(downloadedFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
}
outputStream.flush();
// This is how i call openPDF() method
openPDF(Uri.fromFile(downloadedFile));
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
但是如何在成功写入磁盘存储后立即打开这个文件呢?我已尝试阅读标题为“访问共享存储中的文档和其他文件”和“访问特定于应用程序的文件”的文档,但解释并没有导致我需要的信息。
根据我的阅读,我认为从不同的 android 版本访问存储需要一个差异化因素,比如
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
// only for gingerbread and newer versions
}
我试过这个方法,但它不起作用..
private void openPDF(Uri uri) {
try {
Intent testIntent = new Intent("com.adobe.reader");
testIntent.setType("application/pdf");
testIntent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(uri);
testIntent.setDataAndType(uri, "application/pdf");
startActivity(testIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
解决方案
推荐阅读
- c# - 如何使用 lambda 表达式在子集合中使用 where 条件?
- c# - C#如何订阅使用委托的事件?
- c++ - 处理OKCallback崩溃
- javascript - 如何使用 javascript 使用多个组合框设置多个事件(更改时)
- python - Python Sockets 通过 HTTP 下载 jpg
- ubuntu - 安装tomcat后无法启动Ubuntu 16.04
- sql - 具有同一列的多个 INSERT (MS ACCESS)
- mongodb - MongoDB通过正则表达式条件添加字段
- azureservicebus - 在 Azure 上实现域事件 (DDD-CQRS)
- ruby-on-rails - 如何为属于同一模型的两个不同实例并在Factory Bot中需要其ID的方法编写工厂?