我需要從我的Android應用程序打開PDF文件。我將pdf保存在應用程序包文件夾(/data/data/com.app.example/files)中。我已經在Android模擬器中安裝了Adobe Reader應用程序。問題是,當我嘗試用Adobe Reader打開PDF文件時,模擬器向我顯示下一條消息:無效的文件路徑。在Android中打開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;
}
在此先感謝。
問候,Javi。
Thanks Drax。這讓我繼續開發xD。 – sharnak82