如何在.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
相关产品推荐
相关产品推荐

