如果您收到「ActivityNotFoundException」,這意味着您的設備沒有安裝PDF查看器。
因此,在這種情況下,您可以重定向用戶下載prf查看器。
下面是一個示例代碼:
/**
* Show pdf.
*
* @param context the context
* @param fileName the file name
*/
public static void showPDF(Context context, String fileName) {
try {
Intent intentUrl = new Intent(Intent.ACTION_VIEW);
intentUrl.setDataAndType(getFileUri(context, fileName), "application/pdf");
intentUrl.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intentUrl);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No PDF Viewer Installed", Toast.LENGTH_LONG).show();
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.adobe.reader")));
}
}
而且,在我的情況,我無法直接從資產文件夾中打開PDF文件。因此,我在查看之前將pdf文件從資產文件夾複製到手機SD卡。
下面是將資產文件夾中的文件複製到SDCard並返回新文件URL的代碼段。
/**
* Gets the file uri.
*
* @param context the context
* @param fileName the file name
* @return the file uri
*/
private static Uri getFileUri(Context context, String fileName) {
String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "myAppFolder" + File.separator;
File file = new File(path, fileName);
if (!file.exists() || file.length() == 0) {
OutputStream outputStream = null;
InputStream inputStream = null;
try {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdir();
}
new File(path, ".nomedia").createNewFile();
outputStream = new FileOutputStream(file);
inputStream = context.getAssets().open("docs/" + fileName);
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
inputStream = null;
outputStream.flush();
outputStream.close();
outputStream = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
return Uri.fromFile(file);
}
這意味着沒有活動可以處理這個動作。安裝「pdf查看器」應用程序。 –