Android GPS 存取時需啟用相關權限如下,請於AndroidManifest.xml 內設定
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
Java Code
以下將會使用到的變數進行適當的宣告。
private double currentLatitude = 0;
private double currentLongitude = 0;
private LocationManager mLocationManager;
private static final int LOCATION_UPDATE_MIN_DISTANCE = 1000;
private static final int LOCATION_UPDATE_MIN_TIME = 50;
定義 getCurrentLocation 作為取得當前定位(GPS)的函數(方法)。
其中由於Android 6.0 以後之因使用者體驗上的考量,Android 權限需在程式中再三驗證,以避免使用者不允許該權限時程式崩潰。
其中 requestLocationUpdates 函數是設定 LOCATION_UPDATE_MIN_DISTANCE (ms) 的時間或移動 LOCATION_UPDATE_MIN_TIME 距離時觸發 mLocationListener 傾聽器。
private void getCurrentLocation() {
boolean isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location location = null;
if (!(isGPSEnabled || isNetworkEnabled)) {
// location_provider error
} else {
if (isNetworkEnabled) {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_UPDATE_MIN_TIME,
LOCATION_UPDATE_MIN_DISTANCE, mLocationListener);
location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} else if (isGPSEnabled) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_UPDATE_MIN_TIME,
LOCATION_UPDATE_MIN_DISTANCE, mLocationListener);
location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
if (location != null) {
Log.d("location",String.format("getCurrentLocation(%f, %f)", location.getLatitude(), location.getLongitude()));
}
}
設定 GPS 定位的傾聽器。LocationListener中 onLocationChanged 主要是當 GPS 位置改變時,會觸發該函數,因此此範例在此透過Toast顯示當下最新之GPS經緯度。
private LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
String msg = String.format("%f, %f", location.getLatitude(), location.getLongitude());
Toast.makeText(getApplicationContext(), msg, 100).show();
} else {
// Logger.d("Location is null");
Toast.makeText(getApplicationContext(), "Location is null", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
最後在 onCreate 函數中增加以下程式碼,取得手機的定位服務,並試圖提取當下的GPS位置。
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
getCurrentLocation();
文章標籤
全站熱搜
留言列表