首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 判斷並引導安裝 Adobe Reader:捕獲 ActivityNotFoundException 開啟 Play 商店

     編輯:程式設計綜合問答

嘗試以 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();
}

Android 7.0+ 適配

使用 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 商店頁面。
  • 若裝置無 Play 商店(如中國大陸 ROM),可改用瀏覽器開啟下載頁面。
  • 捕獲 ActivityNotFoundException 是判斷是否安裝對應應用的標準方式。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved