如何以编程方式检查Android中是否安装了应用程序?

时间:2012-07-09 09:19:06

标签: android apk

我们已经以编程方式安装了应用程序。

  1. 如果应用程序已安装在设备中,则应用程序将自动打开。
  2. 否则请安装特定的应用程序。
  3. 指导我。我不知道。 感谢。

15 个答案:

答案 0 :(得分:301)

试试这个:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Add respective layout
        setContentView(R.layout.main_activity);

        // Use package name which we want to check
        boolean isAppInstalled = appInstalledOrNot("com.check.application");  

        if(isAppInstalled) {
            //This intent will help you to launch if the package is already installed
            Intent LaunchIntent = getPackageManager()
                .getLaunchIntentForPackage("com.check.application");
            startActivity(LaunchIntent);

            Log.i("Application is already installed.");       
        } else {
            // Do whatever we want to do if application not installed
            // For example, Redirect to play store

            Log.i("Application is not currently installed.");
        }
    }

    private boolean appInstalledOrNot(String uri) {
        PackageManager pm = getPackageManager();
        try {
            pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
        }

        return false;
    }

}

答案 1 :(得分:59)

比接受的答案(基于this question)更清晰的解决方案:

public static boolean isAppInstalled(Context context, String packageName) {
    try {
        context.getPackageManager().getApplicationInfo(packageName, 0);
        return true;
    }
    catch (PackageManager.NameNotFoundException e) {
        return false;
    }
}

我选择将它作为静态实用程序放在辅助类中。用法示例:

boolean whatsappFound = AndroidUtils.isAppInstalled(context, "com.whatsapp");

This answer展示了如果应用程序缺失,如何从Play商店获取应用程序,但需要注意不要使用Play商店的设备。

答案 2 :(得分:25)

以上代码对我不起作用。以下方法有效。

使用适当的信息创建一个Intent对象,然后使用以下函数检查Intent是否可调用:

private boolean isCallable(Intent intent) {  
        List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent,   
        PackageManager.MATCH_DEFAULT_ONLY);  
        return list.size() > 0;  
}

答案 3 :(得分:15)

如果你知道包名,那么这可以不使用try-catch块或迭代一堆包:

public static boolean isPackageInstalled(Context context, String packageName) {
    final PackageManager packageManager = context.getPackageManager();
    Intent intent = packageManager.getLaunchIntentForPackage(packageName);
    if (intent == null) {
        return false;
    }
    List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    return !list.isEmpty();
}

答案 4 :(得分:6)

此代码检查以确保安装了应用程序,但也检查以确保它已启用。

private boolean isAppInstalled(String packageName) {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
        return pm.getApplicationInfo(packageName, 0).enabled;
    }
    catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return false;
    }
}

答案 5 :(得分:3)

清洁解决方案(没有try-catch)而不是接受的答案(基于AndroidRate Library):

public static boolean isPackageExists(@NonNull final Context context, @NonNull final String targetPackage) {
    List<ApplicationInfo> packages = context.getPackageManager().getInstalledApplications(0);
    for (ApplicationInfo packageInfo : packages) {
        if (targetPackage.equals(packageInfo.packageName)) {
            return true;
        }
    }
    return false;
}

答案 6 :(得分:3)

使用kotlin在Android中安装或未安装Check App。

创建kotlin扩展名。

fun PackageManager.isAppInstalled(packageName: String): Boolean = try {
        getApplicationInfo(packageName, PackageManager.GET_META_DATA)
        true
    } catch (e: Exception) {
        false
    }

现在,可以检查应用程序是否已安装

if (packageManager.isAppInstalled("AppPackageName")) {
    // App is installed
}else{
    // App is not installed
}

答案 7 :(得分:2)

我认为使用try / catch模式对性能不是很好。我建议用这个:

public static boolean appInstalledOrNot(Context context, String uri) {
    PackageManager pm = context.getPackageManager();
    List<PackageInfo> packageInfoList = pm.getInstalledPackages(PackageManager.GET_ACTIVITIES);
    if (packageInfoList != null) {
        for (PackageInfo packageInfo : packageInfoList) {
            String packageName = packageInfo.packageName;
            if (packageName != null && packageName.equals(uri)) {
                return true;
            }
        }
    }
    return false;
}

答案 8 :(得分:1)

试试这个

  

此代码用于检查安装了包名称的应用程序的天气或   如果不是,那么它将打开你的应用程序的playstore链接,否则你的   已安装的应用

String your_apppackagename="com.app.testing";
    PackageManager packageManager = getPackageManager();
    ApplicationInfo applicationInfo = null;
    try {
        applicationInfo = packageManager.getApplicationInfo(your_apppackagename, 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    if (applicationInfo == null) {
        // not installed it will open your app directly on playstore
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + your_apppackagename)));
    } else {
        // Installed
        Intent LaunchIntent = packageManager.getLaunchIntentForPackage(your_apppackagename);
        startActivity( LaunchIntent );
    }

答案 9 :(得分:0)

@EgemenHamutçu在kotlin B中的答案 - )

CLLocationManager

答案 10 :(得分:0)

使用 Kotlin

进行更简单的实施
fun PackageManager.isAppInstalled(packageName: String): Boolean =
        getInstalledApplications(PackageManager.GET_META_DATA)
                .firstOrNull { it.packageName == packageName } != null

并像这样称呼(寻找Spotify应用程序):

packageManager.isAppInstalled("com.spotify.music")

答案 11 :(得分:0)

所有答案仅检查是否已安装某些应用程序。但是,众所周知,一个应用程序可以安装但被用户禁用,无法使用。

因此,此解决方案会同时检查两者。即已安装并启用的应用程序

public static boolean isPackageInstalled(String packageName, PackageManager packageManager) {
     try {
          return packageManager.getApplicationInfo(packageName, 0).enabled;
     }
     catch (PackageManager.NameNotFoundException e) {
          return false;
     }
}

调用方法isPackageInstalled()

boolean isAppInstalled = isPackageInstalled("com.android.app" , this.getPackageManager());

现在,使用布尔变量isAppInstalled并做任何您想做的事情。

if(isAppInstalled ) {
    /* do whatever you want */
}

答案 12 :(得分:0)

其他问题的不错答案。 例如,如果您不想区分“ com.myapp.debug”和“ com.myapp.release”!

class TripReportViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    serializer_class = TripReportSerializer
    pagination_class = TripReportSetPagination
    # To order by favorite count or 'top':
    queryset = TripReport.objects.all().annotate(count=Count('favoriters')).order_by('-count')
    #queryset = TripReport.objects.all().order_by('-pk')
    filter_backends = (filters.SearchFilter, filters.OrderingFilter)
    search_fields = ('=author__username', '=slug', 'countries__name', )
    ordering_fields = ('pk', )

class TripReportSerializer(serializers.ModelSerializer):
    author = AuthorField(queryset=User.objects.all())
    countries = CountryField(queryset=Country.objects.all(), many=True)
    favoriters = serializers.PrimaryKeyRelatedField(required=False, queryset=User.objects.all(), many=True)
    image = serializers.ImageField(max_length=None, use_url=True, required=False)

    class Meta:
        model = TripReport
        fields = ('__all__')

答案 13 :(得分:0)

与Kotlin suger比较好:

  private fun isSomePackageInstalled(context: Context, packageName: String): Boolean {

    val packageManager = context.packageManager

    return runCatching { packageManager.getPackageInfo(packageName, 0) }.isSuccess
  }

答案 14 :(得分:0)

您可以使用Kotlin扩展程序来实现:

fun Context.getInstalledPackages(): List<String> {
    val packagesList = mutableListOf<String>()
    packageManager.getInstalledPackages(0).forEach {
        if ( it.applicationInfo.sourceDir.startsWith("/data/app/") && it.versionName != null)
            packagesList.add(it.packageName)
    }
    return packagesList
}

fun Context.isInDevice(packageName: String): Boolean {
    return getInstalledPackages().contains(packageName)
}