我需要从我的 Android 应用程序打开一个 pdf 文件。我将 pdf 保存在应用程序包文件夹(/data/data/com.app.example/files)中。我已经在 android 模拟器中安装了 adobe reader 应用程序。问题是,当我尝试使用 adobe reader 打开 pdf 文件时,模拟器会显示下一条消息:文件路径无效。
我不知道为什么会发生这种情况,但我坚持这一点。该文件已正确保存,因为我可以在我的计算机中打开它。
这是代码:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
request(response, file_name);
File file = new File("data/data/com.app.example/files/"+file_name);
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
if(file.exists())
{
if (list.size() > 0 && file.isFile()) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}else
{
System.out.println("NO APPs TO OPEN PDFs.");
}
}
else
{
System.out.println("FILE DOES NOT EXIST.");
}
}catch(Exception ex){
System.out.println("Failed!");
ex.printStackTrace();
}
public String request(HttpResponse response, String file){
String result = "";
try{
InputStream in = response.getEntity().getContent();
FileOutputStream f = openFileOutput(file, MODE_WORLD_WRITEABLE);
byte[] buffer = new byte[in.toString().length()];
int len1 = 0;
int counter = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
counter++;
}
f.close();
}
catch(Exception ex){
result = "Error";
}
return result;
}
提前致谢。
问候,哈维。
这是因为 PDF 文件驻留在您自己的包中,并且 Adobe reader 试图从您的包中访问 PDF 文件,这对于 Android 应用程序开发是不允许的。
您可以尝试将文件保存到SDCARD上然后打开它
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)