Xamarin.Forms中DependencyService的使用

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 }
View Code

在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 }
View Code

在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 }
View Code

使用:

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值