close

想要利用手機裡面的GPS或者網路取得使用者目前所在的位置

 

Step 1:

在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>

 

Step 2:

在onCreate裡面新增以下程式

LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    // 判斷目前裝置是否提供 GPS 服務
    if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        try{
            Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if(location == null)
            {
                location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            }
            //緯度
            Double latitude = location.getLatitude();
            //經度
            Double longitude = location.getLongitude();
            Log.d(TAG,"Latitude:"+latitude+"  Longitude:"+longitude);
        }catch (SecurityException e){
            e.printStackTrace();
        }
    }
    else
    {
        // 到設定請使用者開啟 GPS 服務
        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
    }
}

//當經緯度有改變時
@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        String msg = String.format("%f, %f", location.getLatitude(), location.getLongitude());
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    } else {
        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) {

}

 

Step 3:

若Android版本大於6.0則需要再另位血讓使用者開啟權限的通知喔

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 小小工程師 的頭像
    小小工程師

    理工女孩

    小小工程師 發表在 痞客邦 留言(0) 人氣()