http://cw1057.blogspot.tw/2011/11/android-locationmanager.html
我不太的寫範例,
只是會希望能夠快速開發,
所以這裡貼的程式碼,會是複製後馬上就能進行
是我改寫了文章內容後的結果
public class LocationActivity extends Activity {
private LocationManager locationMgr;
private double longitude = 0;
private double latitude = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.locationMgr = (LocationManager) this.getSystemService(LOCATION_SERVICE);
}
@Override
protected void onResume() {
super.onResume();
// 取得位置提供者,不下條件,讓系統決定最適用者,true 表示生效的 provider
String provider = this.locationMgr.getBestProvider(new Criteria(), true);
if (provider == null) {
debug_log("沒有 location provider 可以使用");
return;
}
debug_log("取得 provider - " + provider);
debug_log("requestLocationUpdates...");
// 註冊 listener,兩個 0 不適合在實際環境使用,太耗電
this.locationMgr.requestLocationUpdates(provider, 0, 0, mLocationListener);
debug_log("getLastKnownLocation...");
Location location = this.locationMgr.getLastKnownLocation(provider);
if (location == null) {
debug_log("未取過 location");
return;
}
debug_log("取得上次的 location");
mLocationListener.onLocationChanged(location);
}
public LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
debug_log("onLocationChanged...");
String msg = "經度: " + location.getLongitude() + ", 緯度: "
+ location.getLatitude();
debug_log(msg);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
debug_log("onStatusChanged...");
// 當 location provider 改變時
}
@Override
public void onProviderEnabled(String provider) {
debug_log("onProviderEnabled...");
// 當 location provider 有效時
}
@Override
public void onProviderDisabled(String provider) {
debug_log("onProviderDisabled...");
// 當 location provider 無效時
}
};
private void debug_log(String msg) {
Log.e("log",msg);
}
@Override
protected void onPause() {
super.onPause();
this.debug_log("removeUpdates...");
this.locationMgr.removeUpdates(mLocationListener);
}
}
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />