사용자 위치 정보 읽기
문제
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="kr.ac.skuniv.a1211practice_5">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.1211practice_5">
<activity android:name=".MainActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView status;
int MY_PERMISSIONS_REQUEST_LOCATION = 10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (TextView) findViewById(R.id.status);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
// 시스템의 위치 서비스에 접근하는 개체 생성
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// 위치가 변할때 LocationManager로부터 공지를 받고, 각 메소드를 실행하는 LocationListener 객체를 생성
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) { // 위치가 변할때 자동으로 호출
status.setText("위도; " + location.getLatitude() + "\n경도:" + location.getLongitude() + "\n고도:" + location.getAltitude());
}
// provider의 상태가 변할때 자동으로 호출
public void onStatusChanged(String provider, int status, Bundle extras) {}
// 사용자에 의해 provider가 사용 가능하게 될때 자동으로 호출
public void onProviderEnabled(String provider) {}
// 사용자에 의해 provider가 사용 불가능하게 될 때 자동으로 호출
public void onProviderDisabled(String provider) {}
};
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) {
Toast.makeText(MainActivity.this, "First enable LOCATION ACCESS in settings.", Toast.LENGTH_LONG).show();
return;
}
// requestLocationUpdates(위치 획득할 프로바이더, 갱신시간, 갱신이동거리, 리스너)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,1,locationListener);
}
}