DependencyService 使用
共享项目中创建接口
using System.Collections.Generic; using System.Text; namespace OutAppDemo { public interface IAppManager { void CloseApp(); } }
在各个平台上分别实现此接口
安卓平台using Android.OS; namespace OutAppDemo.Droid { public class AppManager : IAppManager { void IAppManager.CloseApp() { Process.KillProcess(Android.OS.Process.MyPid()); } } }
iOS
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; namespace OutAppDemo.iOS { public class AppManager : IAppManager { void IAppManager.CloseApp() { System.Threading.Thread.CurrentThread.Abort(); } } }
UWP
省略
注册各平台实现
各平台接口实现类中,添加如下代码using Android.OS; using Xamarin.Forms; <--此处添加 [assembly: Dependency(typeof(OutAppDemo.Droid.AppManager))] <--此处添加 namespace OutAppDemo.Droid { public class AppManager : IAppManager { void IAppManager.CloseApp() { ...... } } }
安卓最终现实
using System; using Android.OS; using Xamarin.Forms; [assembly: Dependency(typeof(OutAppDemo.Droid.AppManager))] namespace OutAppDemo.Droid { public class AppManager : IAppManager { void IAppManager.CloseApp() { Process.KillProcess(Android.OS.Process.MyPid()); } } }
使用
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace OutAppDemo { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } private void Button_Clicked(object sender, EventArgs e) <--此处使用 { //此处使用 var manager = DependencyService.Get<IAppManager>(); manager.CloseApp(); } } }