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


147

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

  1. 如果应用程序已安装在设备中,则该应用程序将自动打开。
  2. 否则,请安装特定的应用程序。

引导我。我不知道。谢谢。


Answers:


317

试试这个:

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
@Sathish:希望对您有所帮助
Aerrow

1
毫无疑问,您的帖子真的很有帮助,但是我遇到了一个异常“ java.lang.RuntimeException:添加窗口失败”和“ E / AndroidRuntime(7554):由以下原因引起:android.os.TransactionTooLargeException 05-14 11:37:25.305 :E / AndroidRuntime(7554):在android.os.BinderProxy.transact(本机方法)05-14 11:37:25.305:E / AndroidRuntime(7554):在android.view.IWindowSession $ Stub $ Proxy.add(IWindowSession .java:516)05-14 11:37:25.305:E / AndroidRuntime(7554):位于android.view.ViewRootImpl.setView(ViewRootImpl.java:494)“
DJhon 2014年

2
@BlueGreen:嗨,希望这个链接对您有帮助,stackoverflow.com/ questions/11451393/… ,否则,如果您使用的是Dialog Class,请检查一下。:)
Aerrow

1
@Aerrow ..假设我正在检查我的.apk是否已安装?在安装时...我在检查我的包com.test.installedornot..apk的大小超过9MB时遇到了相同的异常,那么在这种情况下,我将如何处理此异常?
DJhon 2014年

@BlueGreen:上面的代码将仅检查已安装的应用程序,在安装时这将不起作用。对于您的情况,请在安装该apk之后使用广播接收器获取通知。
2014年

65

比接受的答案(基于此问题)更干净的解决方案:

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

此答案显示了丢失应用程序后,如何从Play商店中获取该应用程序的信息,尽管需要在没有Play商店的设备上进行操作。


这需要任何特定的Android权限才能工作吗?
Bootstrapper

@Bootstrapper:不,不需要任何特殊权限。
Jonik

谢谢(有效的解决方案)
Naveed Ahmad

26

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

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

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

5
这样比较好,因为它不需要使用异常进行流控制!
QED

2
@QED令人震惊的是使用Exception作为if语句的人数!这绝对是正确的答案
ILikeTacos

1
目的的内容是什么?带有packageName的字符串不起作用
Henrique de Sousa

3
@HenriquedeSousaIntent intent = getPackageManager().getLaunchIntentForPackage("org.package.name");
Dominic K

如果应用程序被禁用,那应该是错误的。
雨果

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

1
return !list.isEmpty();会更适合Java风格
-headsvk

7

此代码检查以确保已安装该应用程序,还检查以确保已启用该应用程序。

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

这是应用程序的软件包名称。例如,“ com.example.apps.myapp”。我已经编辑了答案,以显示packageName而不是uri。
youravgjoe's

3

我认为使用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;
}

上面的代码在kotlin```private fun isAppInstalled(context:Context,uri:String):Boolean {val packageInfoList = context.packageManager.getInstalledPackages(PackageManager.GET_ACTIVITIES)return packageInfoList.asSequence()。filter {it?.packageName = = uri} .any()}`
Kishan B

3

比接受的答案(基于AndroidRate Library)更干净的解决方案(无try-catch ):

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

2

使用kotlin在Android中检查是否安装了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
}

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

1

使用Kotlin的更简单的实现

fun PackageManager.isAppInstalled(packageName: String): Boolean =
        getInstalledApplications(PackageManager.GET_META_DATA)
                .firstOrNull { it.packageName == packageName } != null

并这样称呼它(寻求Spotify应用):

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

0

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

    private fun isAppInstalled(context: Context, uri: String): Boolean {
        val packageInfoList = context.packageManager.getInstalledPackages(PackageManager.GET_ACTIVITIES)
        return packageInfoList.asSequence().filter { it?.packageName == uri }.any()
    }

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

现在,使用boolean变量isAppInstalled并执行您想要的任何操作。

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

0

解决其他问题的好方法。例如,如果您不想区分“ com.myapp.debug”和“ com.myapp.release”!

public static boolean isAppInstalled(final Context context, final String packageName) {
    final List<ApplicationInfo> appsInfo = context.getPackageManager().getInstalledApplications(0);
    for (final ApplicationInfo appInfo : appsInfo) {
        if (appInfo.packageName.contains(packageName)) return true;
    }
    return false;
}

0

与Kotlin suger比较好:

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

    val packageManager = context.packageManager

    return runCatching { packageManager.getPackageInfo(packageName, 0) }.isSuccess
  }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.