public class LocationMianActivity extends AppCompatActivity { LocationManager locationManager; TextView textView; Location location; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.location_main_activity); textView = (TextView) findViewById(R.id.txt_content); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); // 获取location对象 location = getBestLocation(locationManager); updateView(location); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 8, new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { updateView(locationManager.getLastKnownLocation(provider)); } @Override public void onProviderDisabled(String provider) { updateView(null); } @Override public void onLocationChanged(Location location) { location = getBestLocation(locationManager);// 每次都去获取GPS_PROVIDER优先的location对象 updateView(location); } }); } private void updateView(Location location) { if (location != null) { StringBuffer sb = new StringBuffer(); sb.append("位置信息:\n"); sb.append("经度:" + location.getLongitude() + ", 纬度:" + location.getLatitude()); textView.setText(sb.toString()); } else { textView.setText(""); } } /** * 获取location对象,优先以GPS_PROVIDER获取location对象,当以GPS_PROVIDER获取到的locaiton为null时 * ,则以NETWORK_PROVIDER获取location对象,这样可保证在室内开启网络连接的状态下获取到的location对象不为空 * @param locationManager * @return */ private Location getBestLocation(LocationManager locationManager) { Location result = null; if (locationManager != null) { result = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (result != null) { return result; } else { result = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); return result; } } return result; } }
android GPS定位
最新推荐文章于 2024-04-21 13:16:51 发布