1. 程式人生 > >c#開發移動APP-Xamarin入門

c#開發移動APP-Xamarin入門

tst log popu append 完成後 tool android request tar

原文:c#開發移動APP-Xamarin入門

  如果您在.net環境下做開發,並且對WPF技術有一定了解及應用,同時也想進入移動App開發領域,推薦使用Xamarin開發移動應用

  關於Xamarin不做介紹,網上很多,這裏主要涉及的是一些來自微軟官網文章的翻譯,希望能夠幫助有需要的小夥伴,有疑問或文章有錯誤處,還請及時聯系

最終效果

技術分享圖片

創建Phoneword 應用程序步驟如下:

技術分享圖片

技術分享圖片

  在新窗口中點擊 Cross-Platform,選中Mobile App (Xamarin.Forms) ,指定名稱及路徑

技術分享圖片

  在 New Cross Platform App對話框中點擊Blank App,在Code Sharing Strategy選中.NET Standard

技術分享圖片


打開MainPage.xaml可看到如下代碼

技術分享圖片


  用下述替換上述代碼

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                   x:Class="Phoneword.MainPage">
    <ContentPage.Padding>
<OnPlatform x:TypeArguments="Thickness"> <On Platform="iOS" Value="20, 40, 20, 20" /> <On Platform="Android, UWP" Value="20" /> </OnPlatform> </ContentPage.Padding> <StackLayout> <Label Text="Enter a Phoneword:"
/> <Entry x:Name="phoneNumberText" Text="1-855-XAMARIN" /> <Button x:Name="translateButon" Text="Translate" Clicked="OnTranslate" /> <Button x:Name="callButton" Text="Call" IsEnabled="false" Clicked="OnCall" /> </StackLayout> </ContentPage>

  保存並關閉文件

  在MainPage.xaml.cs文件中用如下代碼替換模板代碼

using System;
using Xamarin.Forms;
namespace Phoneword
{
    public partial class MainPage : ContentPage
    {
        string translatedNumber;

        public MainPage ()
        {
            InitializeComponent ();
        }

        void OnTranslate (object sender, EventArgs e)
        {
            translatedNumber = PhonewordTranslator.ToNumber (phoneNumberText.Text);
            if (!string.IsNullOrWhiteSpace (translatedNumber)) {
                callButton.IsEnabled = true;
                callButton.Text = "Call " + translatedNumber;
            } else {
                callButton.IsEnabled = false;
                callButton.Text = "Call";
            }
        }

        async void OnCall (object sender, EventArgs e)
        {
            if (await this.DisplayAlert (
                    "Dial a Number",
                    "Would you like to call " + translatedNumber + "?",
                    "Yes",
                    "No")) {
                var dialer = DependencyService.Get<IDialer> ();
                if (dialer != null)
                    dialer.Dial (translatedNumber);
            }
        }
    }
} 

  OnTranslate 和 OnCall方法會在對應按鈕點擊時執行
解決方案郵件添加-》新項
技術分享圖片

  選擇新建類PhoneTranslator
  PhoneTranslator.cs代碼如下

using System.Text;
namespace Phoneword
{
    public static class PhonewordTranslator
    {
        public static string ToNumber(string raw)
        {
            if (string.IsNullOrWhiteSpace(raw))
                return null;

            raw = raw.ToUpperInvariant();

            var newNumber = new StringBuilder();
            foreach (var c in raw)
            {
                if (" -0123456789".Contains(c))
                    newNumber.Append(c);
                else
                {
                    var result = TranslateToNumber(c);
                    if (result != null)
                        newNumber.Append(result);
                    // Bad character?
                    else
                        return null;
                }
            }
            return newNumber.ToString();
        }

        static bool Contains(this string keyString, char c)
        {
            return keyString.IndexOf(c) >= 0;
        }

        static readonly string[] digits = {
            "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
        };

        static int? TranslateToNumber(char c)
        {
            for (int i = 0; i < digits.Length; i++)
            {
                if (digits[i].Contains(c))
                    return 2 + i;
            }
            return null;
        }
    }
} 

  新建接口IDialer
  IDialer.cs中定義一個Dail方法,該方法必須在每一個平臺上實現

namespace Phoneword
{
    public interface IDialer
    {
        bool Dial(string number);
    }
}

  到這一步,常規代碼已經完成,下面會實現指定平臺撥號代碼作為 DependencyService.

  解決方案下右鍵Phoneword.iOS 項目選擇添加新類PhoneDialer.cs,

using Foundation;
using Phoneword.iOS;
using UIKit;
using Xamarin.Forms;

[assembly: Dependency(typeof(PhoneDialer))]
namespace Phoneword.iOS
{
    public class PhoneDialer : IDialer
    {
        public bool Dial(string number)
        {
            return UIApplication.SharedApplication.OpenUrl (
                new NSUrl ("tel:" + number));
        }
    }
}

  在Phoneword.Android項目右鍵添加PhoneDialer.cs

using Android.Content;
using Android.Telephony;
using Phoneword.Droid;
using System.Linq;
using Xamarin.Forms;
using Uri = Android.Net.Uri;

[assembly: Dependency(typeof(PhoneDialer))]
namespace Phoneword.Droid
{
    public class PhoneDialer : IDialer
    {
        public bool Dial(string number)
        {
            var context = MainActivity.Instance;
            if (context == null)
                return false;

            var intent = new Intent (Intent.ActionDial);
            intent.SetData (Uri.Parse ("tel:" + number));

            if (IsIntentAvailable (context, intent)) {
                context.StartActivity (intent);
                return true;
            }

            return false;
        }

        public static bool IsIntentAvailable(Context context, Intent intent)
        {
            var packageManager = context.PackageManager;

            var list = packageManager.QueryIntentServices (intent, 0)
                .Union (packageManager.QueryIntentActivities (intent, 0));

            if (list.Any ())
                return true;

            var manager = TelephonyManager.FromContext (context);
            return manager.PhoneType != PhoneType.None;
        }
    }
}

  在Phoneword.Android項目雙擊MainActivity.cs,並用一下代碼替換

using Android.App;
using Android.Content.PM;
using Android.OS;

namespace Phoneword.Droid
{
    [Activity(Label = "Phoneword", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        internal static MainActivity Instance { get; private set; }

        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(bundle);
            Instance = this;
            global::Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new App());
        }
    }
}

  右鍵Phoneword.Android雙擊Properties,選中Android Manifest選項卡

技術分享圖片

在Required permissions部分使能CALL_PHONE權限

技術分享圖片

在Phoneword.UWP右鍵新建類PhoneDialer.cs,

using Phoneword.UWP;
using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Calls;
using Windows.UI.Popups;
using Xamarin.Forms;

[assembly: Dependency(typeof(PhoneDialer))]
namespace Phoneword.UWP
{
    public class PhoneDialer : IDialer
    {
        bool dialled = false;

        public bool Dial(string number)
        {
            DialNumber(number);
            return dialled;
        }
        async Task DialNumber(string number)
        {
            var phoneLine = await GetDefaultPhoneLineAsync();
            if (phoneLine != null)
            {
                phoneLine.Dial(number, number);
                dialled = true;
            }
            else
            {
                var dialog = new MessageDialog("No line found to place the call");
                await dialog.ShowAsync();
                dialled = false;
            }
        }
        async Task<PhoneLine> GetDefaultPhoneLineAsync()
        {
            var phoneCallStore = await PhoneCallManager.RequestStoreAsync();
            var lineId = await phoneCallStore.GetDefaultLineAsync();
            return await PhoneLine.FromIdAsync(lineId);
        }
    }
}

  Phoneword.UWP項目右鍵References,添加References

技術分享圖片



  對話框中選中Universal Windows > Extensions > Windows Mobile Extensions for UWP
  在Phoneword.UWP下雙擊Package.appxmanifest

技術分享圖片

  在 Capabilities 頁下使能 Phone Call 能力

技術分享圖片

  以上完成後:Build > Build Solution
  右鍵 Phoneword.UWP選中Set as StartUp Project:作為啟動項目
  然後運行項目

  上面是對Xamarin開發應用程序的基本了解,下節深入剖析該程序

c#開發移動APP-Xamarin入門