打开另一个应用程序活动,如果未安装应用程序,请转到Play商店

时间:2017-03-25 18:20:53

标签: java android android-intent

我想从我的应用中打开另一个应用活动,如果未安装该应用,请转到Play商店安装应用。

我的代码工作正常,但它只打开应用程序的包名,它不是打开活动。

代码:

public void startApplication(String packageName)
{
    try
    {
        Intent intent = new Intent("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");

        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(intent, 0);

        for(ResolveInfo info : resolveInfoList)
            if(info.activityInfo.packageName.equalsIgnoreCase(packageName))
            {
                launchComponent(info.activityInfo.packageName, info.activityInfo.name);
                return;
            }

        // No match, so application is not installed
        showInMarket(packageName);
    }
    catch (Exception e)
    {
        showInMarket(packageName);
    }
}

private void launchComponent(String packageName, String name)
{
    Intent intent = new Intent("android.intent.action.MAIN");
    intent.addCategory("android.intent.category.LAUNCHER");
    intent.setComponent(new ComponentName(packageName, name));
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    startActivity(intent);
}

private void showInMarket(String packageName)
{
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName));
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

1 个答案:

答案 0 :(得分:0)

尝试

public void startApplication(String packageName) {
    Intent launchIntent = getPackageManager().getLaunchIntentForPackage(packageName);
    if (launchIntent != null) { 
        startActivity(launchIntent);
    } else {
        showInMarket(packageName);
    }
}