我正在启动设备上安装的默认 Youtube 应用程序来播放视频。首先,我想使用 PackageManager 检查设备上是否存在该应用。
如果该应用不存在,我想将用户重定向到 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 兼容的任何想法?