软件编程
位置:首页>> 软件编程>> Android编程>> Android中实现GPS定位的简单例子

Android中实现GPS定位的简单例子

作者:junjie  发布时间:2021-11-24 21:01:25 

标签:Android,GPS

今天弄了一个多小时,写了一个GPS获取地理位置代码的小例子,包括参考了网上的一些代码,并且对代码进行了一些修改,希望对大家的帮助。具体代码如下:  要实用Adnroid平台的GPS设备,首先需要添加上权限,所以需要添加如下权限: 


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

具体实现代码如下:

首先判断GPS模块是否存在或者是开启:


private void openGPSSettings() {
   LocationManager alm = (LocationManager) this
       .getSystemService(Context.LOCATION_SERVICE);
   if (alm
       .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
     Toast.makeText(this, "GPS模块正常", Toast.LENGTH_SHORT)
         .show();
     return;
   }

Toast.makeText(this, "请开启GPS!", Toast.LENGTH_SHORT).show();
   Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
   startActivityForResult(intent,0); //此为设置完成后返回到获取界面

}

如果开启正常,则会直接进入到显示页面,如果开启不正常,则会进行到GPS设置页面:

获取代码如下:


private void getLocation()
 {
   // 获取位置管理服务
   LocationManager locationManager;
   String serviceName = Context.LOCATION_SERVICE;
   locationManager = (LocationManager) this.getSystemService(serviceName);
   // 查找到服务信息
   Criteria criteria = new Criteria();
   criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
   criteria.setAltitudeRequired(false);
   criteria.setBearingRequired(false);
   criteria.setCostAllowed(true);
   criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗

String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息
   Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
   updateToNewLocation(location);
   // 设置 * ,自动更新的最小时间为间隔N秒(1秒为1*1000,这样写主要为了方便)或最小位移变化超过N米
   locationManager.requestLocationUpdates(provider, 100 * 1000, 500,
       locationListener);  }

到这里就可以获取到地理位置信息了,但是还是要显示出来,那么就用下面的方法进行显示:


private void updateToNewLocation(Location location) {

TextView tv1;
   tv1 = (TextView) this.findViewById(R.id.tv1);
   if (location != null) {
     double latitude = location.getLatitude();
     double longitude= location.getLongitude();
     tv1.setText("纬度:" + latitude+ "\n经度" + longitude);
   } else {
     tv1.setText("无法获取地理信息");
   }

}

这样子就能获取到当前使用者所在的地理位置了,至少如何下地图上实现,在下面将进行获取,并显示出来!对参考代码的人表示感谢!

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com