문제

I am launching the default Youtube App installed on device to play a video. First, I want to check if the app exists on the device using PackageManager.

If the app does not exists, I want to redirect the user to the Google Play to download the app.

Below is the code snippet:

    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);
        }
    }

This code works perfectly well on Android 4.0.4 and above. But when I am trying to run it on Android 2.3.4 it ALWAYS redirects the user to the Google Play irrespective of whether the App is installed or not.

Any idea as to how to make this compatible with Android 2.3.4 too ?

도움이 되었습니까?

해결책

It is probably because PackageManager.GET_ACTIVITIES doesn't really make much sense here? You probably want something like:

try {
  PackageInfo pi = pm.getPackageInfo("com.google.android.youtube", 0);
  // start Youtube
} catch (NameNotFoundException e) {
  // go to Play Store
}

Also a better approach would be not to force the Youtube app on the user, but simply use the VIEW action and let them choose the app they want to use.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top