我一直在測試這個,發現以下工作。首先,你單獨下載該文件,並將其存儲在設備上,然後你去做到這一點:
File file = new File("/sdcard/download/somepdf.pdf");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
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");
startActivity(intent);
我已經測試這對各種仿真器和一個植根氰電話以及一個HTC Magic的。如果沒有pdf渲染器可用,則列表將返回零並且不會發生任何事情。
將數據類型設置爲pdf mime類型以獲得正確的行爲似乎很重要。
如果您安裝droidreader它會對意圖做出反應並顯示pdf。
當然,您也可以在下載pdf之前進行檢查,具體取決於您的使用情況,或者執行諸如彈出警報或重定向其他目的以下載或進行其他操作。
編輯:因爲我已經重構了這一點到一個單獨的方法..
public static final String MIME_TYPE_PDF = "application/pdf";
/**
* Check if the supplied context can render PDF files via some installed application that reacts to a intent
* with the pdf mime type and viewing action.
*
* @param context
* @return
*/
public static boolean canDisplayPdf(Context context) {
PackageManager packageManager = context.getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType(MIME_TYPE_PDF);
if (packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0) {
return true;
} else {
return false;
}
}
我的HTC Hero帶着觀衆的QuickOffice和HTC自家的PDF閱讀器預裝。 – adrianbanks 2010-05-06 22:10:38