Android之获取当前位置的经纬度

上一篇说了一下获取网络位置的经纬度

直接获取的是聚合数据上面的数据~

这一篇和上一篇差不多~

直接贴代码:

public class MainActivity extends Activity {

	private TextView tv;
	
	private LocationManager mLocationManager;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv=(TextView) findViewById(R.id.tv);
		//求俩个经纬度的距离
		/*float[] results=new float[3];
		Location.distanceBetween(100, 200, 200, 400, results);
		tv.setText(results[0]+"米");*/
		mLocationManager=(LocationManager) getSystemService(LOCATION_SERVICE);
		Location mlocation=mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		updateLocation(mlocation);
		
		//每隔5秒  2000米的距离
		mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 2000, new LocationListener() {
			
			//在用户禁用具有定位功能的硬件时被调用
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
				// TODO Auto-generated method stub
				
			}
			//位置服务可用
			//在用户启动具有定位功能的硬件是被调用
			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				updateLocation(mLocationManager.getLastKnownLocation(provider));
			}
			//在提供定位功能的硬件状态改变是被调用
			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
				
			}
			//位置改变
			//在设备的位置改变时被调用
			@Override
			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				updateLocation(location);
			}
		});
	}
	private void updateLocation(Location mlocation) {
		// TODO Auto-generated method stub
		if(mlocation!=null){
		StringBuffer stringBuffer=new StringBuffer();
		stringBuffer.append("经度:"+mlocation.getLongitude());
		stringBuffer.append("纬度:"+mlocation.getLatitude());
		stringBuffer.append("海拔:"+mlocation.getAltitude());
		stringBuffer.append("速度:"+mlocation.getSpeed());
		stringBuffer.append("方向:"+mlocation.getBearing());
		tv.setText(stringBuffer.toString());
		}else{
			tv.setText("正在获取位置信息");
		}
	}

	
}

记得加权限:

    
    
效果图就不贴了,这个要真机测试的~

你可能感兴趣的:(安卓)