Xamarin.Forms中DependencyService的使用
在Xamarin.Forms中,我们经常会根据各个平台的特性特殊处理一些需求,比如:读取应用的版本号。
在此也以读取应用版本号为例,练习DependencyService用法:
创建IPlatformInfoService接口:
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 5 namespace XFPractice.Service 6 { 7 public interface IPlatformInfoService 8 { 9 10 /// <summary> 11 /// 获取应用版本 12 /// </summary> 13 /// <returns></returns> 14 string GetAppVersion(); 15 16 } 17 }
在Android创建ImpDroidService实现IPlatformInfoService接口:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 using Android.App; 7 using Android.Content; 8 using Android.Content.PM; 9 using Android.OS; 10 using Android.Runtime; 11 using Android.Views; 12 using Android.Widget; 13 using Xamarin.Forms; 14 using XFPractice.Service; 15 16 17 [assembly: Dependency(typeof(XFPractice.Droid.ImpService.ImpDroidService))] 18 namespace XFPractice.Droid.ImpService 19 { 20 public class ImpDroidService: IPlatformInfoService 21 { 22 public string GetAppVersion() 23 { 24 var context = Android.App.Application.Context; 25 var packageInfo = context.PackageManager.GetPackageInfo( 26 context.PackageName, PackageInfoFlags.Configurations); 27 return packageInfo.VersionName; 28 } 29 } 30 }
在iOS创建ImpiOSService实现IPlatformInfoService接口:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 using Foundation; 7 using UIKit; 8 using Xamarin.Forms; 9 using XFPractice.Service; 10 11 12 [assembly: Dependency(typeof(XFPractice.iOS.ImpService.ImpiOSService))] 13 namespace XFPractice.iOS.ImpService 14 { 15 public class ImpiOSService : IPlatformInfoService 16 { 17 public string GetAppVersion() 18 { 19 var version = NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleVersion"); 20 return version.ToString(); 21 } 22 } 23 }
使用:
1 private readonly IPlatformInfoService _platformService; 2 3 _platformService = DependencyService.Get<IPlatformInfoService>(); 4 5 var AppVersion = _platformService.GetAppVersion();
这样我们就能读取到App的版本了。
原文地址:https://www.cnblogs.com/devin_zhou/p/8313352.html
时间: 2024-10-25 14:14:50