1、從GPS來
2、從WIFI資訊來
首先,先在 AndroidManifest加入下面兩個權限
//宣告Application會使用取得座標資料 FIN為gps,COARSE為wifi
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
在你想要取得的Activity 先 implements LocationListener 必且加入下面Function
private LocationManager lms; private String bestProvider = LocationManager.GPS_PROVIDER; private boolean getGPSService; /** * 啟用定位模組,使用後記得關閉 * @return Location */ public Location locationServiceInitial() { /* 取得系統定位服務 */ LocationManager status = (LocationManager) (this.getSystemService(Context.LOCATION_SERVICE)); /* 確認是否開啟GPS服務or網路定位服務 */ if (status.isProviderEnabled(LocationManager.GPS_PROVIDER) || status.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { getGPSService=true; lms = (LocationManager) getSystemService(LOCATION_SERVICE); // 取得系統定位服務 Criteria criteria = new Criteria(); // 資訊提供者選取標準 bestProvider = lms.getBestProvider(criteria, true); Location location = lms.getLastKnownLocation(bestProvider); // 使用GPS定位座標 if(location != null){ return location; }else{ Toast.makeText(this, "無法定位座標", Toast.LENGTH_LONG).show(); return null; } } else { Toast.makeText(this, "請開啟定位服務", Toast.LENGTH_LONG).show(); // 開啟設定畫面 startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); return null; } }
重新進入時更新、離開時要關閉
@Override @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); if (getGPSService) { // 服務提供者、更新頻率毫秒、最短距離、地點改變時呼叫物件 lms.requestLocationUpdates(bestProvider, 1000, 1, (LocationListener) this); } } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); if (getGPSService) { lms.removeUpdates((LocationListener) this); // 離開頁面時停止更新 getGPSService = false; } }