嘗試以 ACTION_VIEW 開啟 PDF,若擲出 ActivityNotFoundException 則彈出對話框引導用戶前往 Play 商店下載 Adobe Reader。
File file = new File(Environment.getExternalStorageDirectory(), "sample.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
new AlertDialog.Builder(this)
.setTitle("未找到 PDF 閱讀器")
.setMessage("是否前往 Google Play 下載 Adobe Acrobat Reader?")
.setPositiveButton("前往下載", (dialog, which) -> {
Intent market = new Intent(Intent.ACTION_VIEW);
market.setData(Uri.parse("market://details?id=com.adobe.reader"));
startActivity(market);
})
.setNegativeButton("取消", null)
.show();
}
使用 FileProvider 產生 content:// Uri:
Uri uri = FileProvider.getUriForFile(this, "com.example.fileprovider", file);
intent.setDataAndType(uri, "application/pdf");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
market:// 協定直接開啟 Play 商店頁面。ActivityNotFoundException 是判斷是否安裝對應應用的標準方式。