You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET MAUI应用中检测某款应用是否已安装?

.NET MAUI 检测应用是否已安装的替代方案

你原来的代码依赖Android原生PackageManager,但在.NET MAUI中因上下文获取方式错误、API过时,加上Android 11+的权限限制,导致检测失效。以下是跨平台的替代实现方案:

1. 定义共享接口

先在共享项目中创建统一的检测接口:

public interface IAppInstallationService
{
    bool IsAppInstalled(string identifier);
}

2. Android平台实现

在Android平台项目中实现接口,确保正确获取应用上下文并适配权限:

[assembly: Dependency(typeof(AppInstallationService_Android))]
namespace YourAppNamespace.Platforms.Android
{
    public class AppInstallationService_Android : IAppInstallationService
    {
        public bool IsAppInstalled(string packageName)
        {
            var packageManager = Android.App.Application.Context.PackageManager;
            try
            {
                // 使用非过时的PackageInfoFlags重载
                packageManager.GetPackageInfo(packageName, Android.Content.PM.PackageInfoFlags.MetaData);
                return true;
            }
            catch (PackageManager.NameNotFoundException)
            {
                return false;
            }
            catch
            {
                return false;
            }
        }
    }
}

Android权限配置

Android 11(API 30)及以上版本,需在AndroidManifest.xml中添加应用查询权限,指定要检测的包名:

<queries>
    <!-- 检测Google Pay的包名 -->
    <package android:name="com.google.android.apps.nbu.paisa.user" />
    <!-- 如需检测其他应用,添加更多package标签 -->
</queries>

若需检测任意应用,可添加QUERY_ALL_PACKAGES权限,但该权限需通过Google Play审核,不推荐随意使用。

3. iOS平台实现(可选)

iOS无法直接通过包名检测,需通过应用的URL Scheme判断:

[assembly: Dependency(typeof(AppInstallationService_iOS))]
namespace YourAppNamespace.Platforms.iOS
{
    public class AppInstallationService_iOS : IAppInstallationService
    {
        public bool IsAppInstalled(string urlScheme)
        {
            if (string.IsNullOrWhiteSpace(urlScheme))
                return false;
            
            var url = new NSUrl(urlScheme);
            return UIApplication.SharedApplication.CanOpenUrl(url);
        }
    }
}

iOS权限配置

在Info.plist中添加允许查询的URL Scheme:

<key>LSApplicationQueriesSchemes</key>
<array>
    <!-- Google Pay的URL Scheme,需确认实际值 -->
    <string>googlepay</string>
</array>

4. 共享代码中调用

在共享项目中通过依赖注入获取服务并调用:

var appInstallService = DependencyService.Get<IAppInstallationService>();
// Android传入包名,iOS传入URL Scheme
bool isGooglePayInstalled = appInstallService.IsAppInstalled("com.google.android.apps.nbu.paisa.user");

内容的提问来源于stack exchange,提问作者Abhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 05:58:33