我在data/data/package/files/myfolder/.
中保存了文件,我尝试使用以下方法打开它们:
public static void openFile(Context context, File url) throws IOException {
// Create URI
File file = url;
Uri uri = Uri.fromFile(file);
Log.d("pathAttach", uri.toString());
Intent intent = new Intent(Intent.ACTION_VIEW);
if (url.toString().contains(".doc") || url.toString().contains(".docx")) {
// Word document
intent.setDataAndType(uri, "application/msword");
} else if(url.toString().contains(".pdf")) {
// PDF file
intent.setDataAndType(uri, "application/pdf");
} else if(url.toString().contains(".ppt") || url.toString().contains(".pptx")) {
// Powerpoint file
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
} else if(url.toString().contains(".xls") || url.toString().contains(".xlsx")) {
// Excel file
intent.setDataAndType(uri, "application/vnd.ms-excel");
} else if(url.toString().contains(".zip") || url.toString().contains(".rar")) {
// WAV audio file
intent.setDataAndType(uri, "application/x-wav");
} else if(url.toString().contains(".rtf")) {
// RTF file
intent.setDataAndType(uri, "application/rtf");
} else if(url.toString().contains(".wav") || url.toString().contains(".mp3")) {
// WAV audio file
intent.setDataAndType(uri, "audio/x-wav");
} else if(url.toString().contains(".gif")) {
// GIF file
intent.setDataAndType(uri, "image/gif");
} else if(url.toString().contains(".jpg") || url.toString().contains(".jpeg") || url.toString().contains(".png")) {
// JPG file
intent.setDataAndType(uri, "image/jpeg");
} else if(url.toString().contains(".txt")) {
// Text file
intent.setDataAndType(uri, "text/plain");
} else if(url.toString().contains(".3gp") || url.toString().contains(".mpg") || url.toString().contains(".mpeg") || url.toString().contains(".mpe") || url.toString().contains(".mp4") || url.toString().contains(".avi")) {
// Video files
intent.setDataAndType(uri, "video/*");
} else {
intent.setDataAndType(uri, "*/*");
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
该方法确实为每种类型的文件打开了正确的应用程序,但是该应用程序没有显示文件,说明其为何不存在。
该方法将其调用如下:
String pathAttach = context.getFilesDir().getAbsolutePath() +
File.separator + "myfolder/" +
messagesList.get(pos).getContent();
FileOpenUitl.openFile(context, new File(pathAttach));
通过控制台,我已打印pathAttach的值,并且uri.toString ()
为图像获得的值是:
pathAttach:/data/data/io.github.myuser.myapp/files/myfolder/6010141d505105c092eaf6d002a868a18b48544592cb304a3f173c30b4ee9892.jpeg
uri.toString():file: ///data/data/io.github.myuser.myapp/files/myfolder/6010141d505105c092eaf6d002a868a18b48544592cb304a3f173c30b4ee9892.jpeg
我认为一切都很好,但是我不明白为什么应用程序无法加载文件。
答案 0 :(得分:1)
/data/data/package/
是应用程序的私有空间,其他应用程序无法读取。
解决方案是:
Environment::getExternalStorage()
中其他应用可以读取的位置FileProvider
授予对文件的临时读取权限。答案 1 :(得分:0)
使用此
File file = new File("this is the file path");
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "this is the mime type of file");
startActivityForResult(intent, 100);