原文地址:https://blog.xamarin.com/cross-platform-apis-xamarin-essentials-latest-preview/api
在 Microsoft Build 2018 咱們宣佈了 Xamarin.Essentials,一個幫助開發者構建原生應用的跨平臺 API 核心套件。Xamarin.Essentials 提供給開發者經過共享代碼訪問超過30個特定平臺的 API,包括地理位置、安全存儲、傳感器、設備信息和更多其餘的 API。最重要的是,Xamarin.Essentials 能夠用在任意的 iOS、Android、UWP 或者 Xamarin.Forms 應用,無論你如何建立用戶界面。來自開發者的第一個預覽版的反饋很是棒,訪問這些原生特性的直截了當的方式受到了一致的讚賞。安全
今天,咱們很高興發佈 Xamarin.Essentials(0.7.0-preview)的第二個預覽版,今天在 NuGet 上就能夠使用了。這個版本結合了開發者的反饋、bug 修復和幾個新 API,今天你就能夠試用了。優化
定位傳感器ui
Xamarin.Essentials 第一個預覽版提供給開發者訪問加速計、陀螺儀、磁力計和指南針。根據大家的反饋,咱們增長了一個定位傳感器 API。這個 API容許你訂閱讀讀取到報告回來的四元數變化,它描述了地球座標相對於設備座標的旋轉。這在建立須要訪問 3D 空間的應用時很是有用。this
public class OrientationSensorTest { // Set speed delay for monitoring changes. SensorSpeed speed = SensorSpeed.Ui; public OrientationSensorTest() { // Register for reading changes, be sure to unsubscribe when finished OrientationSensor.ReadingChanged += OrientationSensor_ReadingChanged; } void OrientationSensor_ReadingChanged(AccelerometerChangedEventArgs e) { var data = e.Reading; Console.WriteLine($"Reading: X: {data.Orientation.X}, Y: {data.Orientation.Y}, Z: {data.Orientation.Z}, W: {data.Orientation.W}"); // Process Orientation quaternion (X, Y, Z, and W) } public void ToggleOrientationSensor() { try { if (OrientationSensor.IsMonitoring) OrientationSensor.Stop(); else OrientationSensor.Start(speed); } catch (FeatureNotSupportedException fnsEx) { // Feature not supported on device } catch (Exception ex) { // Other error has occurred. } } }
主線程 APIspa
當開發在後臺處理信息的應用時,在主線程上更新用戶界面時很重要的。使用主線程 API,如今能夠訪問檢測當前線程是否在主線程上,並開始在主線程上進行更新。咱們在內部使用這個 API 來優化 Xamarin.Essentials 中的代碼。線程
using Xamarin.Essentials; public class MyViewModel { public bool UpdateUI() { MainThread.BeginInvokeOnMainThread(() => { // Ensure invoked on MainThread. Xamarin.Essentials will optimize this and check if you are already on the main thread }); } public bool ProcessInformation() { if(MainThread.IsMainThread) { // Start new thread to process on background } else { // Already on non-main thread. } } }
簡化的 Android 依賴code
基於大家的反饋,Xamarin.Essentials 如今是針對 Android 8.1(API27)構建的,附帶更新了2個 Android Support 庫的依賴,CustomTabs 和 Core.Utils。這意味着你須要確認你的 Xamarin.Android 項目針對 Android 8.1(API27)編譯,能夠在項目的屬性中設置。orm
請記住,在項目中擁有全部 Android Support 庫的版本很重要,如今是更新你的項目中依賴的好時機。視頻
Xamarin.Essentials 行動
準備好了解更多關於 Xamarin.Essentials 了嘛?沒有比觀看最新的 Xamarin Show 更進一步。Snack Pack 給出了 Xamarin.Essentials 的全面概述和如何開始集成到你的應用中。
視頻地址(若是你能夠看到): https://www.youtube.com/watch?v=uGby6JBG2pY
瞭解更多
在咱們的完整發行說明能夠閱讀更多關於這個版本的信息並瀏覽咱們完整的文檔來確認,有一個全面的概述和如何使用 Xamarin.Essentials 的每個特性。