반응형
Activity에서 위치 값 가져오기
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
멤버 변수로 설정
double mLatitude = 0;
double mLongitude = 0;
private FusedLocationProviderClient fusedLocationProviderClient;
onCreate에서 fusedLocationProviderClient 초기화
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
위치 값 가져오기
private void getCurrentLocation() {
try {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
fusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(this, location -> {
if (location != null) {
// 현재 위치 가져오기 성공
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
Log.e("Location", "Latitude: " + mLatitude + ", Longitude: " + mLongitude);
} else {
Log.e("Location", "Failed to get current location.");
}
});
} catch (Exception e) {
Log.e("Location", "Failed to get current location.");
}
}
Forground Service에서 위치 값 가져오기
Activity에서 사용한 위 방법으로는 위치 값을 가져올 수 없습니다. 서비스에서 getLastLocation으로 호출을 해도 위치 값을 항상 0 입니다.
그래서 LocationRequest를 이용해서 위치 값을 가져옵니다.
AndroidManifest.xml 내 권한은 위와 같습니다.
멤버 변수로 설정
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationCallback locationCallback;
onCreate에서 LocationCallback을 이용해서 위치 값 가져오기
@Override
public void onCreate() {
super.onCreate();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
// 위치 업데이트를 위한 LocationRequest 생성
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//locationRequest.setInterval(mnTimer);
locationRequest.setInterval(SJSingtonData.getInstance().nTime);
// 위치 업데이트를 처리하는 LocationCallback 생성
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
// 위치 값을 가져와서 원하는 작업을 수행합니다.
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
// 원하는 작업을 수행하세요.
Log.e("Location2", "Latitude: " + mLatitude + ", Longitude: " + mLongitude);
}
}
};
// 위치 업데이트 시작
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
} else {
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
미국식
[loʊ│keɪʃn]
영국식
[ləʊ│keɪʃn]
1. (…이 일어나는·존재하는) 장소[곳/위치]
2. (영화의) 야외 촬영지[로케이션]
3. …의 위치[소재] 찾기[추적]
반응형
'프로그램 개발해서 돈벌기 > Android' 카테고리의 다른 글
[Java] 안드로이드에서 크롬캐스트 연결 시 "전송 대상" 선택 후 앱 죽는 현상에 대한 해결 방법 (0) | 2023.06.27 |
---|---|
[Java] 안드로이드 서비스에서 Local Notification 보내기 (0) | 2023.06.26 |
[Java] 안드로이드에서 싱글톤(Singleton) 클래스와 사용법 예제 (0) | 2023.06.26 |
android studio refactor를 이용해서 패키지명을 바꾸었을 때 R 인식을 못하는 이유는? 해결 방법은? (0) | 2023.06.26 |
android에서 포그라운드 서비스(Forground Service) 동작 확인 방법 (0) | 2023.06.23 |
댓글