Android 개발자가 이용할 수있는 130 가지 이상의 고유 권한을 사용하여 응용프로그램에서 사용할 권한을 정확히 알기 어렵다. Android Marshmallow는 사용 권한을 단순화 할뿐만 아니라 필요한 사용 권한의 수를 줄이기 위해 응용 프로그램 사용 권한에 대해 완전히 새로운 방향을 제시하는 데 예제를 통해 알아보자.
폰접근 권한을 받아오고 GPS를 통해 위치 정보를 받아, 지도를 로딩하는 방법에 대한 실습
(자마린안드로이드예제실습)현재 위치를 얻은 후 지도에 표시하기, GPS다루기, 마시멜로이후 권한 획득방법 구현_추천자마린학원/자마린교육
1. 크로스플랫폼 앱개발을 위한
자마린 기초강좌
Xamarin.Android 심플예제
현재 위치를 얻은 후 지도에 표시하기, 마시멜로
이후 권한 획득방법 구현
탑크리에듀(http://topcredu.co.kr), 이종철
2. 예제 개요 – 프로젝트 생성
Android 개발자가 이용할 수있는 130 가지 이상의 고유 권한을 사용하여 응용프로그램에
서 사용할 권한을 정확히 알기 어렵다. Android Marshmallow는 사용 권한을 단순화 할뿐
만 아니라 필요한 사용 권한의 수를 줄이기 위해 응용 프로그램 사용 권한에 대해 완전히
새로운 방향을 제시하는 데 예제를 통해 알아보자.
폰접근 권한을 받아오고 GPS를 통해 위치 정보를 받아, 지도를 로딩하는 방법에 대한 실
습
“GetLocation“ 라는 이름의 Xamarin.Android 프로젝트 생성
AssemblyInfo.cs에 위치정보 서비스를 위한 두개의 권한을 허용
사용자 위치를 얻기 위해 GPS를 사용해야하는 경우 ACCESS_FINE_LOCATION 및
ACCESS_COARSE_LOCATION 권한을 지정하고 API 레벨 23(마시멜로) 이상에서 런타임시
사용자에게 요청하게 된다.
탑크리에듀(http://topcredu.co.kr), 이종철
3. 예제 개요 - 권한
Android 애플리케이션에서 특정 API를 호출 할 때 필요한 모든 권한을 지정해야 한다. 즉,
사용자 위치를 얻기 위해 GPS를 사용해야하는 경우 ACCESS_FINE_LOCATION 및
ACCESS_COARSE_LOCATION 권한을 지정해야 했다. 사용 권한 그룹은 위치, 연락처, 전화,
센서, SMS 및 저장소와 같은 유사한 작업을 수행하는 사용 권한을 단순화하려고 시도하는
데 앱 그룹은 현재 1 ~ 7 개의 권한을 단일 권한 그룹으로 묶는데 한 번에 그룹의 모든 권
한을 요청할 수 있다.
이러한 권한 그룹 중 하나에서 찾은 권한 또는 일반으로 지정되지 않은 권한을 사용하는
경우 사용자에게 권한을 요청해야 한다.
Geolocator Plugin은 AccessFineLocation and AccessCoarseLocation 위치 권한을 모두
필요로하며, android.permission-group.LOCATION에 그룹화되어 있다.
AndroidManifest.xml에 이 두 가지 권한을 추가해야 하며 런타임에 요청해야 한다.
[assembly: UsesPermission(Manifest.Permission.AccessFineLocation)]
[assembly: UsesPermission(Manifest.Permission.AccessCoarseLocation)]
탑크리에듀(http://topcredu.co.kr), 이종철
4. 예제 개요 - 권한
AssemblyInfo.cs에 Geocoder 클래스를 사용하는 데 필요한 권한을 선언, 기기의 GPS 좌
표를 얻기 위해 꼭 필요한 것은 아니지만 본 예제에서는 현재 위치의 번지를 얻기 위해 사
용.[assembly: UsesPermission(Manifest.Permission.Internet)]
위3가지 권한을 Properties 더블클릭 후 Android 매니페스트에서 필수권한을 체크하자.
탑크리에듀(http://topcredu.co.kr), 이종철
11. MainActivity.cs 파일에
Button의 클릭 이벤트 코드 작성
// 권한을 가져온다.
void PermissionButton_OnClick(object
sender, EventArgs e)
{
if ((int)Build.VERSION.SdkInt < 23)
{
return;
}
탑크리에듀(http://topcredu.co.kr), 이종철
//Check to see if any permission in our group is
available, if one, then all are
const string permission =
Manifest.Permission.AccessFineLocation;
if (CheckSelfPermission(permission) ==
(int)Permission.Granted)
{
return;
}
//Finally request permissions with the list of
permissions and Id
RequestPermissions(PermissionsLocation,
RequestLocationId);
}
12. MainActivity.cs 파일에
Button의 클릭 이벤트 코드 작성
// 사용자가 권한 요청을 승인하거나 거부
한 후에는 응답을 처리하고 기능을 켜거나
끔
// 권한이 요청 된 활동의
OnRequestPermissionsResult를 재정 의하여
수행
// 이 메소드는 결과 코드 (권한을
요청할 때 지정된 코드)와 부여 또는 거부 된
결과를 리턴
public override async void
OnRequestPermissionsResult(int
requestCode, string[] permissions,
Permission[] grantResults)
{ 탑크리에듀(http://topcredu.co.kr), 이종철
switch (requestCode)
{
case RequestLocationId:
{
if (grantResults[0] == Permission.Granted)
{
var callDialog = new AlertDialog.Builder(this);
callDialog.SetMessage("Permission Confirmed!
");
callDialog.SetNeutralButton("OK",
delegate
{
// Create intent to dial phone
});
14. MainActivity.cs 파일에
Button의 클릭 이벤트 코드 작성
// 지도를 표시한다.
async void MapButton_OnClick(object
sender, EventArgs e)
{
if (currentLocation == null)
{
addressText.Text = "Can't determine
the current address. Try again in a few
minutes.";
return;
}
탑크리에듀(http://topcredu.co.kr), 이종철
Address address = await
ReverseGeocodeCurrentLocation();
var geoUri =
Android.Net.Uri.Parse("geo:" +
address.Latitude.ToString()+",
"+address.Longitude.ToString());
var mapIntent = new
Intent(Intent.ActionView, geoUri);
StartActivity(mapIntent);
}
15. MainActivity.cs 파일에
Button의 클릭 이벤트 코드 작성
// 위도와 경도를 읽고 에서 주소를 가져옴.
async void
AddressButton_OnClick(object sender,
EventArgs e)
{
InitializeLocationManager();
currentLocation =
locationManager.GetLastKnownLocation(loc
ationProvider);
탑크리에듀(http://topcredu.co.kr), 이종철
if (currentLocation == null) {
addressText.Text = "Can't determine the
current address. Try again in a few minutes.";
return;
}
locationText.Text = string.Format("{0:f6},{1:f6}",
currentLocation.Latitude, currentLocation.Longitude);
Address address = await
ReverseGeocodeCurrentLocation();
DisplayAddress(address);
}
16. MainActivity.cs 파일에
Button의 클릭 이벤트 코드 작성
// LocationManager 클래스는 장치에서 GPS 업데이트를
수신하고
// 이벤트를 통해 응용 프로그램에 알린다.
// 주어진 기준 세트와 일치하는 최고의 GPS 위치
제공자를 Android에 요청하고
// 그 제공자를 LocationManager에 제공한다.
void InitializeLocationManager()
{
locationManager =
(LocationManager)GetSystemService(LocationService);
Criteria criteriaForLocationService = new Criteria
{
Accuracy = Accuracy.Fine
};
탑크리에듀(http://topcredu.co.kr), 이종철
IList<string> acceptableLocationProviders =
locationManager.GetProviders(criteriaForLoc
ationService, true);
if (acceptableLocationProviders.Any())
{
locationProvider =
acceptableLocationProviders.First();
}
17. MainActivity.cs 파일에
Button의 클릭 이벤트 코드 작성
else
{
locationProvider = string.Empty;
}
Log.Debug(TAG, "Using " +
locationProvider + ".");
}
탑크리에듀(http://topcredu.co.kr), 이종철
// 현재 위치의 Address 개체 컬렉션을 비동기 적으로
조회한다.
// 위치 및 네트워크 가용성과 같은 요소에 따라
하나 또는 여러 개의 주소가 리턴되는데
// 첫 번째 주소 (가능한 경우)는 Activity에
주소를 표시하는 DisplayAddress 메소드로 전달된다.
async Task<Address>
ReverseGeocodeCurrentLocation()
{
Geocoder geocoder = new Geocoder(this);
IList<Address> addressList =
await
geocoder.GetFromLocationAsync(currentLocation.Lat
itude, currentLocation.Longitude, 10);
18. MainActivity.cs 파일에
Button의 클릭 이벤트 코드 작성
Address address =
addressList.FirstOrDefault();
return address;
}
탑크리에듀(http://topcredu.co.kr), 이종철
void DisplayAddress(Address address) {
if (address != null) {
StringBuilder deviceAddress = new
StringBuilder();
deviceAddress.AppendLine(address.GetAddressLine(0));
// Remove the last comma from the end of the address.
addressText.Text = deviceAddress.ToString();
} else {
addressText.Text = "Unable to determine the
address. Try again in a few minutes.";
} } }}