GPS获取地理位置

首先将通过GPS获取地理位置的权限添加到manifest中:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

支持GPS的核心API:locationmanager,locationprovider,location。

核心代码:

LocationManager lManager;
…..
lManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		//***************条件筛选,criteria类似一个筛选器
		Criteria criteria = new Criteria();
		criteria.setCostAllowed(false);//功能必须免费
		criteria.setAltitudeRequired(true);//可以获取高度信息
		criteria.setBearingRequired(true);//可以获取方向信息
		//获取所有可用(或者满足条件筛选的)locationprovider
		List<String> strings = lManager.getAllProviders();
		tView.setText(strings.toString());
		//********************************
		//获取指定的locationprovider
		LocationProvider locationProvider = lManager.getProvider(LocationManager.GPS_PROVIDER);
		//*******************************
		Location location = lManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		updaetView(location);
		lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 8, new LocationListener() {
			
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
			}
			
			@Override
			public void onProviderEnabled(String provider) {
				updaetView(null);
			}
			
			@Override
			public void onProviderDisabled(String provider) {
				updaetView(lManager.getLastKnownLocation(provider));
			}
			
			@Override
			public void onLocationChanged(Location location) {
				updaetView(location);
			}
		});
		
	}

	public void updaetView(Location newlocation){
		if(newlocation != null){
			tView1.setText("经度:"+newlocation.getLongitude());
			tView2.setText("纬度:"+newlocation.getLatitude());
			tView3.setText("高度:"+newlocation.getAltitude());
			tView4.setText("速度:"+newlocation.getSpeed());
			tView5.setText("方向:"+newlocation.getBearing());
		}else {
			tView1.setText("经度:");
			tView2.setText("纬度:");
			tView3.setText("高度:");
			tView4.setText("速度:");
			tView5.setText("方向:");
		}
	}
当然,上述代码在手机上偶尔并没有获取到自己的地理位置,可能是手机GPS的问题,具体情况不详
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值