android原生获取经纬度

定位所需权限AndroidManifest.XML配置

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

申请位置权限这里我使用xxpermissions依赖进行申请

implementation 'com.hjq:xxpermissions:5.2'

定位代码

   XXPermissions.with(getActivity())//getActivity() 我是用的是fragment所以使用getActivity
                .permission(Permission.ACCESS_FINE_LOCATION,ACCESS_COARSE_LOCATION)
                .request(new OnPermission() {
            @Override
            public void hasPermission(List<String> granted, boolean isAll) {
                initLoad();// 有定位权限
            }

            @Override
            public void noPermission(List<String> denied, boolean quick) {
				// 没有定位权限逻辑处理
            }
        });
   private void initLoad() {
        Location getlocation = getlocation(MyApplication.getContext());
        // 获取经纬度
        double latitude = getlocation.getLatitude();
        double longitude = getlocation.getLongitude();
        // 地理编辑器  如果想获取地理位置 使用地理编辑器将经纬度转换为省市区
        Geocoder geocoder = new Geocoder(MyApplication.getContext(), Locale.getDefault());
        try {
            List<Address> fromLocation = geocoder.getFromLocation(latitude, longitude, 1);
            Address address = fromLocation.get(0);
            String mAddressLine = address.getAddressLine(0);
            Log.i("xxx",mAddressLine.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 private Location getlocation(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        // gps
        @SuppressLint("MissingPermission") Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        // 网络定位
        @SuppressLint("MissingPermission") Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        return lastKnownLocation;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值