[英]XAMARIN Android App, how do I get a list of installed apps as a service in MVVM?
我一直在寻找有关Android.App.Application.Context.PackageManager.GetInstalledApplications
的文章,但是我无法弄清楚如何获得对它的引用。
您可以使用依赖服务来实现这一点。 我将详细介绍,以便其他不熟悉 Xamarin 的人也可以理解。
首先,我们将创建 model。 您可以在 Shared 目录中将其命名为InApp.cs
。
public class InApp
{
public string AppName { get; set; }
public string PackageName { get; set; }
public InApp(string appName, string packageName)
{
AppName = appName;
PackageName = packageName;
}
}
现在我们可以在Android
文件夹中创建我们的依赖服务。 将此命名为AndroidService.cs
。
public class AndroidService : IAndroidService
{
public List<InApp> GetIntalledApps()
{
List<InApp> inApps = new List<InApp>();
IList<ApplicationInfo> apps = Android.App.Application.Context.PackageManager.GetInstalledApplications(PackageInfoFlags.MatchAll);
for (int i = 0; i < apps.Count; i++)
{
inApps.Add(new InApp(apps[i].LoadLabel(Android.App.Application.Context.PackageManager), apps[i].PackageName));
}
return inApps;
}
}
上面的代码将获取已安装的应用程序,然后创建我们在上面创建的 model 的List
并返回它。
在运行时,Xamarin 应该知道在哪里寻找依赖服务,因此我们应该将其添加到我们上面创建的AndroidService
class 的名称空间之上。
[assembly: Xamarin.Forms.Dependency(typeof(AndroidService))]
IAndroidService
是在运行时访问Android
文件夹AndroidService
class 的接口。 我们将在 Shared 目录中创建这个 class。 我们可以将其命名为IAndroidService.cs
。
public interface IAndroidService
{
List<InApp> GetIntalledApps();
}
现在我们已经完成了依赖服务的实现。 下一部分是创建一个ListView
并添加从我们的 Android 服务返回的已安装应用程序列表。
由于我们在MVVM
中执行此操作,我们现在将创建一个视图 model。
在 Shared 目录中创建InstalledAppViewModel.cs
。
public class InstalledAppViewModel: INotifyPropertyChanged
{
private ObservableCollection<InApp> installedApps;
public ObservableCollection<InApp> InstalledApps
{
get { return installedApps; }
set
{
installedApps = value;
}
}
public InstalledAppViewModel()
{
List<InApp> listOfInstalledApps = DependencyService.Get<IAndroidService>().GetIntalledApps();
InstalledApps = new ObservableCollection<InApp>(listOfInstalledApps);
}
public event PropertyChangedEventHandler PropertyChanged;
}
上面,我们已经完成了依赖注入并将GetInstalledApps
方法的返回值添加到我们的Observable
列表中。
现在在您的MainPage.Xaml.Cs
绑定视图 model。
BindingContext = new InstalledAppViewModel();
在MainPage.Xaml
中添加列表视图。
<ListView ItemsSource="{Binding InstalledApps}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Vertical">
<StackLayout Orientation="Horizontal" VerticalOptions="CenterAndExpand">
<Label Text="{Binding AppName}" FontSize="Medium" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
在列表视图属性的ItemSource
中,您正在绑定我们在视图 Model class 中创建的Observable
列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.