当前位置: 移动技术网 > IT编程>移动开发>Android > Android中实现GPS定位的简单例子

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

2019年07月24日  | 移动技术网IT编程  | 我要评论

混凝土破碎机械,12月份有什么节日,具俊表的妈妈

今天弄了一个多小时,写了一个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("无法获取地理信息");
    }

  }

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网