크로스플랫폼 개발을 위한 자마린(Xamarin)을 이용하여 C#코드로 작성된 예제입니다. xamarin.com의 phoneworld Hello 안드로이드 프로젝트를 따라해 본 예문으로 처음 시작하시는 분들에게 도움이 될것 입니다. (문자로 입력된 전화번호를 숫자로 변환하고 실제 전화를 거는 응용 앱) https://developer.xamarin.com/guides/android/getting_started/hello,android/hello,android_quickstart/
설치환경 : 윈도우 10 64Bit 8G RAM, 비주얼 스튜디오 커뮤니티 2015, 실습코드는 http://ojc.asia에서 다운로드 가능 합니다.
2. Hello Android
(Xamarin.Android Application)
xamarin.com의 phoneworld Hello 안드로이드 프로젝트를 따라해 보자.
(문자로 입력된 전화번호를 숫자로 변환하고 실제 전화를 거는 응용 앱)
https://developer.xamarin.com/guides/android/getting_started/hello,android/hello,android_q
uickstart/
설치환경
윈도우 10 64Bit 8G RAM, 비주얼 스튜디오 커뮤니티 2015
실습코드는 http://ojc.asia에서 다운로드 가능 합니다.
3. 1. 비주얼 스튜디오를 실행 후 File -> New Project 후 좌측 Template에서 Android 클
릭 후 오른쪽의 Blank App를 선택하고, 프로젝트 이름은 “phoneword”, “확인” 버튼
을 클릭.
4. 2. 프로젝트가 생성되면 우측 솔루션 탐색기의 Resources -> Layout 아래의
Main.axml을 더블 클릭하면 폰화면이 나타난다, 이 파일이 스크린의 Layout 파일인
데 만약 아래처럼 안드로이드 SDK 버전이 낮다고 하면 “Open Android SDK”를 클릭
하여 Android SDK Manager에서 업데이트를 해야 한다. 업데이트할 때 비주얼 스튜
디오는 Close하는 것이 좋다. (시간이 좀 걸림)
6. 3. 좌측에 도구상자(ToolBox)가 보이지 않으면 보기메뉴 -> 도구상자를 클릭해서 보
이도록 한후 Text(Large)를 드래그 해서 폰화면의 상단 가운데 위치 시키자.
4. Text(Large)를 선택 후 우측하단 속성창애서 Text 속성을 " Enter a Phoneword : ”
로 설정하자.
7. 5. 툴박스(ToolBox)에서 Plain Text 위젯을 선택 후 Text(Large) 박스 아래에 위치 시키
고 id속성을 “@+id/PhoneNumberText”, Text 속성을 “010-0xamarin”으로 설정하자.
8. 6. 툴박스(ToolBox)에서 Button을 선택 Plain Text 아래에 위치 시키고 id 속성은
“@+id/TranslateButton”, Text 속성은 “변환하기”로 설정하자.
9. 7. Button을 하나 더 선택해서 “변환하기” 버튼 아래에 위치시키고 id 속성은
“@+id/CallButton”, Text 속성은 “전화걸기”로 입력하자.
10. 8. 알파벳 입력을 숫자로 변환하는 C#코드를 작성하는데 오른쪽 솔루션 탐색기에서
프로젝트 -> 마우스 우측버튼 -> 추가(Add) -> 새항목(New Item) -> Visual C# ->
Code를 선택하자. 파일명은 “PhoneTranslator.cs”로 입력.
[PhoneTranslator.cs]
using System.Text;
using System;
namespace Core
{
public static class PhonewordTranslator
{
public static string ToNumber(string raw)
{
if (string.IsNullOrWhiteSpace(raw))
return "";
else
raw = raw.ToUpperInvariant();
11. 8. “PhoneTranslator.cs” 작성중
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);
}
}
return newNumber.ToString();
}
static bool Contains(this string keyString, char c)
{ return keyString.IndexOf(c) >= 0; }
static int? TranslateToNumber(char c)
{
if ("ABC".Contains(c)) return 2;
else if ("DEF".Contains(c)) return 3;
else if ("GHI".Contains(c)) return 4;
else if ("JKL".Contains(c)) return 5;
else if ("MNO".Contains(c)) return 6;
else if ("PQRS".Contains(c)) return 7;
else if ("TUV".Contains(c)) return 8;
else if ("WXYZ".Contains(c)) return 9;
return null;
}
}
12. 9. 솔루션 탐색기에서 MainActivity.cs 파일을 오픈하자. “변환하기“ 버튼 기능을 구현
하는데 MainActivity의 OnCreate() 메소드안에 변환버튼, 전화걸기 버튼 기능을 구현
한다.
[MainActivity.cs]
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace phoneword
{
[Activity(Label = "phoneword", MainLauncher = true,
Icon = "@drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{ base.OnCreate(bundle);
// Set our view from the "main" layout
resource
SetContentView (Resource.Layout.Main);
//---------------------------------------------
--
// 로드된 UI로 부터 컨트롤참조를 얻음
//---------------------------------------------
--
//전화번호 입력창
EditText phoneNumberText =
FindViewById<EditText>(Resource.Id.PhoneNumberT
ext);
//변환버튼
Button translateButton =
FindViewById<Button>(Resource.Id.TranslateButton);
14. 9. MainActivity.cs 작성중
//-----------------------------------------------------
//전화걸기 버튼 코드
//---------------------------------------------------
--
callButton.Click += (object sender, EventArgs e)
=> {
var callDialog = new AlertDialog.Builder(this);
callDialog.SetMessage("Call " +
translatedNumber + "?");
//Call 클릭
callDialog.SetNeutralButton("Call", delegate {
// Create intent to dial phone
var callIntent = new Intent(Intent.ActionCall);
callIntent.SetData(Android.Net.Uri.Parse("tel:" +
translatedNumber));
StartActivity(callIntent);
});
//Cancel 클릭
callDialog.SetNegativeButton("Cancel",
delegate { });
// Show the alert dialog to the user and
wait for response.
callDialog.Show();
};
}
}
}
15. 10. 우리가 만든 Application에 전화거는 기능을 활성화 시키자. Android Manifest안
에 권한과 관련된 부분을 정의해야 하는데 솔루션 탐색기에서 Properties를 더블클
릭하고 좌측 Android Manifest를 선택 후 하단의 Permission중 CALL_PHONE
permission을 활성화 하자.
16. 11. 모든 변경사항을 저장(Ctrl+Shift+S)하고 빌드하자.(Build > Rebuild Solution)
12. MainActivity.cs의 Label은 응용프로그램의 스크린 최상단에 디스플레이되는 텍스
트이니 필요하다면 수정을 하면 된다.
[Activity(Label = "phone word", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity {
13. 응용프로그램의 아이콘을 설정할 수 있는데
https://developer.xamarin.com/guides/android/getting_started/hello,android/Res
ources/XamarinAppIconsAndLaunchImages.zip 에서 아이콘 ZIP 파일을 다운받아
적당히 압축을 풀자. 프로젝트의 Resources -> drawable에 존재하는 Icon.png
파일을 먼저 삭제후 압축푼 경로 아래 Androiddrawable 폴더의 Icon.png를 다시
선택해 주면 되는데 솔루션 탐색기 -> Ressources -> drawable 에서 마우스
우측버튼 -> 추가 -> 기존항목 선택 후 압축 푼 경로의 Androiddrawable 아래의
Icon.png 파일을 선택하면 아이콘이 등록된다.
17. 14. 앞에서 다운 받은 파일의 Androiddrawable* 폴더들을 프로젝트로 복사하면 되
는데 drawable 폴더를 제외한 모든 폴더를 복사 후 프로젝트의 Resources 아래에
붙여넣자.
18. 15. 다음은 Android Manifest안에 아이콘을 등록하면 되는데 솔루션 탐색기의
Properties 더블클릭 -> 왼쪽에서 Android Manifest를 선택 후 나타나는 화면의
Application Icon 메뉴에서 @drawble/Icon을 선택하자.
19. 16. 이제 이뮬레이터로 테스트를 해보도록 하자.
Properties를 더블클릭 후 좌측 Application 에서 API LEVEL 23(mashimallow)로 설정
하고 이뮬레이터를 실행했다. 상단의 실행단추를 눌러 실행하자.
20. 17. 이제는 실제 휴대폰에서 실행해 보자. 안드로이드 휴대폰을 USB로 연결 후 폰에
서 USB 디버깅을 활성화 해야 되는데 휴대폰 상단 설정을 클릭하고 더보기 -> 개발
자옵션 ->USB 디버깅을 체크하자.
솔루션 탐색기의
Properties를 더블클릭 후
좌측 Application을 선택
후 가운데 Minimum
Android to target에서
“Use Compile using SDK
Version”으로 바꾼 후
비주얼 스튜디오의 상단
의 우측 화살표 클릭하여
USB 로 연결한 휴대폰을
선택 후 실행하면 된다.
(실제 전화도 잘 간다. )
21. This Practice makes the Expert!
C#,ADO.NET,Network
프로그래밍 기초과정
C#기초, Xamarin 앱 개발과정 Xamarin 앱개발 과정