今天弄了一个多小时,写了一个GPS获取地理位置代码的小例子,包括参考了网上的一些代码,并且对代码进行了一些修改,希望对大家的帮助。具体代码如下: 要实用Adnroid平台的GPS设备,首先需要添加上权限,所以需要添加如下权限:
<
uses
-
permission android:name
=
"
android.permission.ACCESS_FINE_LOCATION
"
></
uses
-
permission
>
具体实现代码如下:
首先判断GPS模块是否存在或者是开启:
01 |
private void openGPSSettings() { |
02 |
LocationManager alm = (LocationManager) this |
03 |
.getSystemService(Context.LOCATION_SERVICE); |
05 |
.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) { |
06 |
Toast.makeText( this , "GPS模块正常" , Toast.LENGTH_SHORT) |
11 |
Toast.makeText( this , "请开启GPS!" , Toast.LENGTH_SHORT).show(); |
12 |
Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS); |
13 |
startActivityForResult(intent, 0 ); |
如果开启正常,则会直接进入到显示页面,如果开启不正常,则会进行到GPS设置页面:
获取代码如下:
01 |
private void getLocation() |
04 |
LocationManager locationManager; |
05 |
String serviceName = Context.LOCATION_SERVICE; |
06 |
locationManager = (LocationManager) this .getSystemService(serviceName); |
08 |
Criteria criteria = new Criteria(); |
09 |
criteria.setAccuracy(Criteria.ACCURACY_FINE); |
10 |
criteria.setAltitudeRequired( false ); |
11 |
criteria.setBearingRequired( false ); |
12 |
criteria.setCostAllowed( true ); |
13 |
criteria.setPowerRequirement(Criteria.POWER_LOW); |
15 |
String provider = locationManager.getBestProvider(criteria, true ); |
16 |
Location location = locationManager.getLastKnownLocation(provider); |
17 |
updateToNewLocation(location); |
19 |
locationManager.requestLocationUpdates(provider, 100 * 1000 , 500 , |
到这里就可以获取到地理位置信息了,但是还是要显示出来,那么就用下面的方法进行显示:
01 |
private void updateToNewLocation(Location location) { |
04 |
tv1 = (TextView) this .findViewById(R.id.tv1); |
05 |
if (location != null ) { |
06 |
double latitude = location.getLatitude(); |
07 |
double longitude= location.getLongitude(); |
08 |
tv1.setText( "维度:" + latitude+ "\n经度" + longitude); |
10 |
tv1.setText( "无法获取地理信息" ); |
这样子就能获取到当前使用者所在的地理位置了,至少如何下地图上实现,在下面将进行获取,并显示出来!对参考代码的人表示感谢!