1
我正在啓動安裝在設備上的默認Youtube應用以播放視頻。首先,我想使用PackageManager檢查設備上是否存在應用程序。PackageManager無法在Android 2.3.4上運行
如果該應用不存在,我想將用戶重定向到Google Play以下載該應用。
下面的代碼片段:
String appName = "com.google.android.youtube";
Boolean existFlg = false;
Context context = getApplicationContext();
PackageManager packageManager = context.getPackageManager();
// get all installed app's info
List<PackageInfo> pinfo = packageManager.getInstalledPackages(PackageManager.GET_ACTIVITIES);
for (int i = 0; i < pinfo.size(); i++) {
String name = pinfo.get(i).packageName;
if (name.equalsIgnoreCase(appName)) {
existFlg = true;
break;
}
}
if (existFlg) {
// start Youtube Native App
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"+video_id));
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
// not installed
else {
// goto the market to download Youtube App
Uri uri = Uri.parse("market://details?id=com.google.android.youtube");
Intent market = new Intent(Intent.ACTION_VIEW, uri);
market.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(market);
} catch (android.content.ActivityNotFoundException ex) {
// if market app not exist, goto the web of Google Play to download the Facebook App
String googleURL = "https://play.google.com/store/apps/details?id=com.google.android.youtube";
Uri googleplay_webpage = Uri.parse(googleURL);
Intent marketIntent = new Intent(Intent.ACTION_VIEW, googleplay_webpage);
marketIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(marketIntent);
}
}
此代碼的工作地很好的Android 4.0.4及以上。但是,當我試圖在Android 2.3.4上運行它時,它總是將用戶重定向到Google Play,而不管該應用是否已安裝。
有關如何使這與Android 2.3.4兼容的任何想法?
非常感謝!它的工作原理:) – Sourav
此外,我同意強迫用戶使用Youtube應用程序不是一個好主意......但在這種情況下,這是因爲一個特定的要求 – Sourav