android 获取设备当前经纬度 GPS位置信息
通过GPS_PROVIDER或是NETWORK_PROVIDER获取设备当前经纬度定位,现将其整理至一个工具类中方便直接使用
import android.content.Context; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.provider.Settings; import android.util.Log; public class XXLocationManager { private static final String TAG = "XXLocationManager"; private boolean mRecordLocation; private Context mContext; private LocationManager mLocationManager; private static SOSLocationManager mSOSLMInstance; LocationListener [] mLocationListeners = new LocationListener[] { new LocationListener(android.location.LocationManager.GPS_PROVIDER), new LocationListener(android.location.LocationManager.NETWORK_PROVIDER) }; private SOSLocationManager(Context context) { mContext = context; init(); } public static SOSLocationManager getInstance(Context context ) { if(mSOSLMInstance == null) { synchronized(SOSLocationManager.class) { if(mSOSLMInstance == null) { mSOSLMInstance = new SOSLocationManager(context); } } } return mSOSLMInstance; } private void init() { recordLocation(true); } public Location getCurrentLocation() { if (!mRecordLocation) { return null; } // go in best to worst order for (int i = 0; i < mLocationListeners.length; i++) { Location l = mLocationListeners[i].current(); if (l != null) { return l; } } Log.d(TAG, "No location received yet."); return null; } /** * Start/stop location recording. */ public void recordLocation(boolean recordLocation) { if (mRecordLocation != recordLocation) { mRecordLocation = recordLocation; if (recordLocation) { startReceivingLocationUpdates(); } else { stopReceivingLocationUpdates(); } } } private void startReceivingLocationUpdates() { Log.v(TAG, "starting location updates"); if (mLocationManager == null) { mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); } if (mLocationManager != null) { boolean isEnableGPS = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);//这里强制开启GPS定位方式服务 if(!isEnableGPS){ Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(), LocationManager.GPS_PROVIDER, true); android.util.Log.i(TAG,"setLocationProviderEnabled = true"); } try { mLocationManager.requestLocationUpdates( android.location.LocationManager.NETWORK_PROVIDER, 1000, 0F, mLocationListeners[1]); } catch (SecurityException ex) { Log.i(TAG, "fail to request location update, ignore"+ex.getMessage()); } catch (IllegalArgumentException ex) { Log.d(TAG, "provider does not exist " + ex.getMessage()); } try { mLocationManager.requestLocationUpdates( android.location.LocationManager.GPS_PROVIDER, 1000, 0F, mLocationListeners[0]); } catch (SecurityException ex) { Log.i(TAG, "fail to request location update, ignore"+ex.getMessage()); } catch (IllegalArgumentException ex) { Log.d(TAG, "provider does not exist " + ex.getMessage()); } Log.d(TAG, "startReceivingLocationUpdates"); } } private void stopReceivingLocationUpdates() { Log.v(TAG, "stopping location updates"); if (mLocationManager != null) { for (int i = 0; i < mLocationListeners.length; i++) { try { mLocationManager.removeUpdates(mLocationListeners[i]); } catch (Exception ex) { Log.i(TAG, "fail to remove location listners, ignore", ex); } } Log.d(TAG, "stopReceivingLocationUpdates"); } } private class LocationListener implements android.location.LocationListener { Location mLastLocation; boolean mValid = false; String mProvider; public LocationListener(String provider) { mProvider = provider; mLastLocation = new Location(mProvider); } @Override public void onLocationChanged(Location newLocation) { if (newLocation.getLatitude() == 0.0 && newLocation.getLongitude() == 0.0) { // Hack to filter out 0.0,0.0 locations return; } if (!mValid) { Log.d(TAG, "Got last location."); } Log.d(TAG, "location. update"); mLastLocation.set(newLocation); mValid = true; } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { mValid = false; } @Override public void onStatusChanged( String provider, int status, Bundle extras) { switch(status) { case android.location.LocationProvider.OUT_OF_SERVICE: case android.location.LocationProvider.TEMPORARILY_UNAVAILABLE: { // we can't get the correct location but null. //mValid = false; break; } } } public Location current() { return mValid ? mLastLocation : null; } } }
在获取Location对象前记得在合适的位置开启获取位置功能,
Location location = SOSLocationManager.getInstance(context).getCurrentLocation();
if(location != null) {
boolean hasLatLon = false;
StringBuffer sb = new StringBuffer();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
hasLatLon = (latitude != 0.0d) || (longitude != 0.0d);
String locat = sb.append(latitude).append(",").append(longitude).toString();
android.util.Log.i(TAG,"location ="+locat);
return hasLatLon ? locat : "no signal";
}
return "no signal";
当前不需要位置服务功能时可在合适的位置关闭位置服务功能:
new XXLocationManager();
在开启位置服务功能后即可获取设备经纬度,调用代码:
Location location = new XXLocationManager().getCurrentLocation(); //这是最直接的调用方式,你也可以在此基础上封装一个new XXLocationManager()对象,如将其封装为单例模式等,
location.getLatitude();
location.getLongitude();
或是
private String getGPSLocation() {
Location loc = new XXLocationManager().getCurrentLocation();
if (loc != null) {
boolean hasLatLon = false;
android.util.Log.i(TAG,"gps location not null");
android.widget.Toast.makeText(context,"location not null", android.widget.Toast.LENGTH_SHORT).show();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
hasLatLon = (latitude != 0.0d) || (longitude != 0.0d);
String locat = sb.append(latitude).append(",").append(longitude).toString();
return hasLatLon ? locat : "no signal";
}
return "no signal";
}
方式二: 已封装成方法
public static String getGPSLocation(Context context){ LocationManager pLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); boolean isEnableGPS = pLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);//forced to be turned on this gps function if(!isEnableGPS){ Settings.Secure.setLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER, true); android.util.Log.i(TAG,"setLocationProviderEnabled = true"); } List<String> providers = pLocationManager.getProviders(true); Location location = null; for (String provider : providers) { Location l = pLocationManager.getLastKnownLocation(provider); if (l == null) { continue; } if (location == null || l.getAccuracy() < location.getAccuracy()) { location = l; } } if(location != null) { boolean hasLatLon = false; StringBuffer sb = new StringBuffer(); double latitude = location.getLatitude(); double longitude = location.getLongitude(); hasLatLon = (latitude != 0.0d) || (longitude != 0.0d); String locat = sb.append(latitude).append(",").append(longitude).toString(); android.util.Log.i(TAG,"location ="+locat); return hasLatLon ? locat : "no signal"; } android.util.Log.i(TAG,"Unable to get location"); return "no signal"; }
封装一个定位service
public class LocationService extends Service { private LocationManager lm; private MyLocationListener listener; @Override public IBinder onBind(Intent intent) { return null; } @SuppressLint("MissingPermission") @Override public void onCreate() { super.onCreate(); lm = (LocationManager) getSystemService(LOCATION_SERVICE); listener = new MyLocationListener(); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); criteria.setAltitudeRequired(false);//不要求海拔 criteria.setBearingRequired(false);//不要求方位 criteria.setCostAllowed(true);//允许有花费 criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗 String provider = lm.getBestProvider(criteria, true); log.w("定位的provider:" + provider); Location location = lm.getLastKnownLocation(provider); log.w("location-" + location); if (location != null) { //不为空,显示地理位置经纬度 String longitude = "Longitude:" + location.getLongitude(); String latitude = "Latitude:" + location.getLatitude(); log.w("getLastKnownLocation:" + longitude + "-" + latitude); stopSelf(); } //第二个参数是间隔时间 第三个参数是间隔多少距离,这里我试过了不同的各种组合,能获取到位置就是能,不能获取就是不能 lm.requestLocationUpdates(provider, 3000, 10, listener); } class MyLocationListener implements LocationListener { // 位置改变时获取经纬度 @Override public void onLocationChanged(Location location) { String longitude = "Longitude:" + location.getLongitude(); String latitude = "Latitude:" + location.getLatitude(); log.w("onLocationChanged:" + longitude + "-" + latitude); stopSelf(); // 获取到经纬度以后,停止该service } // 状态改变时 @Override public void onStatusChanged(String provider, int status, Bundle extras) { log.w("onStatusChanged - provider:"+provider +" status:"+status); } // 提供者可以使用时 @Override public void onProviderEnabled(String provider) { log.w("GPS开启了"); } // 提供者不可以使用时 @Override public void onProviderDisabled(String provider) { log.w("GPS关闭了"); } } @Override public void onDestroy() { super.onDestroy(); lm.removeUpdates(listener); // 停止所有的定位服务 } }
评论