我正在开发一个 C# Xamarin 项目,我需要从我的 Android 手机获取已安装应用程序的列表。
为此,我尝试使用 PackageManager 类中的 GetInstalledApplications 方法。
由于该类是抽象的,因此我无法直接使用它。所以我创建了一个名为 PM2 的新类,它继承了它的所有方法,包括 GetInstalledApplications。
问题是当我尝试使用该方法获取List ApplicationInfo时,它总是触发NotImplementedException,而不是返回列表。
这是来自 MyApp.Android\Services\HelperService.cs 的代码
public IList<ApplicationInfo> PM()
{
IList<PackageInfo> lista = new List<PackageInfo>();
PackageManager pm2 = new PM2();
PackageInfoFlags flags = new PackageInfoFlags();
IList<ApplicationInfo> packages = (IList<ApplicationInfo>)pm2.GetInstalledApplications(flags);
return (IList<ApplicationInfo>)packages;
}
这是具有继承方法的继承类。还有更多方法,但我只是输入相关的方法:
[Obsolete]
public class PM2 : PackageManager
{
public override IList<ApplicationInfo> GetInstalledApplications([GeneratedEnum] PackageInfoFlags flags)
{
throw new NotImplementedException();
}
}
这是我在项目的专属 Android 部分之外调用方法的接口。它位于 MyApp\Services\IHelperService.cs 上:
public interface IHelperService {
IList<ApplicationInfo> PM();
}
这就是我调用接口的地方。它位于 MyApp\Extensions\PaymentMethods.xaml.cs 上:
IList<ApplicationInfo> packages = DependencyService.Get<Services.IHelperService>().PM();
这些是 MyApp.Android\Properties\AssemblyInfo 上使用的权限:
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
[assembly: UsesPermission(Android.Manifest.Permission.RequestInstallPackages)]
[assembly: UsesPermission(Android.Manifest.Permission.QueryAllPackages)]
我需要获取应用程序列表,因为我的应用程序(A)调用第三方应用程序(B),并且如果应用程序B未安装,我们不希望它只是抛出异常。我们想要设计一个自定义警报,告诉用户他需要做什么,即下载应用程序 B。
任何帮助将非常感激,因为我需要这个来工作,而且我已经被这个问题困扰一个多月了。
谢谢你。
首先,作为塞尔文 说如果你想使用
PackageManager
,你可以从上下文中获取它的实例。斯库赫:
var packagemanager = Android.App.Application.Context.PackageManage;
or
var packagemanager = Android.App.Application.Context.ApplicationContext.PackageManager;
然后你说:
我需要获取应用程序列表,因为我的应用程序(A)调用第三方应用程序(B),如果应用程序B未安装,我们不希望它只是抛出异常
您可以参考这个帖子:如何使用MAUI App检查应用程序是否安装。使用 PackageManager.GetPackageInfo() 方法也是一个不错的选择。