原地址:Android:原生的手机获取经纬度得到当前位置_谢桥的博客-CSDN博客_android 获取经纬度
这是一套完整的代码,模拟器与真机调试可用
1.首先得注册权限
- android:name="android.permission.ACCESS_COARSE_LOCATION"
- android:name="android.permission.ACCESS_FINE_LOCATION"
1.1其次最重要的是,申请权限,一直真机调试不成功,折磨死我啦,放在protected void onCreate方法就可以
- if(ContextCompat.checkSelfPermission(EventsReportedActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
- != PackageManager.PERMISSION_GRANTED){//未开启定位权限
- //开启定位权限,200是标识码
- ActivityCompat.requestPermissions(EventsReportedActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},200);
- }else{
- initLocation();//初始化定位信息
- Toast.makeText(EventsReportedActivity.this,"已开启定位权限", Toast.LENGTH_LONG).show();
- }
1.2这边再回调一下
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- super.onRequestPermissionsResult(requestCode, permissions, grantResults);
- switch (requestCode){
- case 200://刚才的识别码
- if(grantResults[0] == PackageManager.PERMISSION_GRANTED){//用户同意权限,执行我们的操作
- initLocation();//开始定位
- }else{//用户拒绝之后,当然我们也可以弹出一个窗口,直接跳转到系统设置页面
- Toast.makeText(EventsReportedActivity.this,"未开启定位权限,请手动到设置去开启权限",Toast.LENGTH_LONG).show();
- }
- break;
- default:break;
- }
- }
写到这里差不多就结束啦,
2.获取经纬度
2.1工具类
- package com.skyinfor.szls.Util;
- import android.Manifest;
- import android.content.Context;
- import android.content.pm.PackageManager;
- import android.location.Location;
- import android.location.LocationListener;
- import android.location.LocationManager;
- import android.os.Build;
- import android.os.Bundle;
- import android.util.Log;
- import androidx.core.app.ActivityCompat;
- import java.util.List;
- import static android.content.ContentValues.TAG;
- public class LocationUtils {
- private volatile static LocationUtils uniqueInstance;
- private LocationManager locationManager;
- private String locationProvider;
- private Location location;
- private Context mContext;
- private LocationUtils(Context context) {
- mContext = context;
- getLocation();
- }
- //采用Double CheckLock(DCL)实现单例
- public static LocationUtils getInstance(Context context) {
- if (uniqueInstance == null) {
- synchronized (LocationUtils.class) {
- if (uniqueInstance == null) {
- uniqueInstance = new LocationUtils(context);
- }
- }
- }
- return uniqueInstance;
- }
- private void getLocation() {
- //1.获取位置管理器
- locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
- //2.获取位置提供器,GPS或是NetWork
- List<String> providers = locationManager.getProviders(true);
- if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
- //如果是网络定位
- Log.d(TAG, "如果是网络定位");
- locationProvider = LocationManager.NETWORK_PROVIDER;
- } else if (providers.contains(LocationManager.GPS_PROVIDER)) {
- //如果是GPS定位
- Log.d(TAG, "如果是GPS定位");
- locationProvider = LocationManager.GPS_PROVIDER;
- } else {
- Log.d(TAG, "没有可用的位置提供器");
- return;
- }
- // 需要检查权限,否则编译报错,想抽取成方法都不行,还是会报错。只能这样重复 code 了。
- if (Build.VERSION.SDK_INT >= 23 &&
- ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
- ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- return;
- }
- if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- return;
- }
- //3.获取上次的位置,一般第一次运行,此值为null
- Location location = locationManager.getLastKnownLocation(locationProvider);
- if (location != null) {
- setLocation(location);
- }
- // 监视地理位置变化,第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
- locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
- }
- private void setLocation(Location location) {
- this.location = location;
- String address = "纬度:" + location.getLatitude() + "经度:" + location.getLongitude();
- Log.d(TAG, address);
- }
- //获取经纬度
- public Location showLocation() {
- return location;
- }
- // 移除定位监听
- public void removeLocationUpdatesListener() {
- // 需要检查权限,否则编译不过
- if (Build.VERSION.SDK_INT >= 23 &&
- ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
- ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- return;
- }
- if (locationManager != null) {
- uniqueInstance = null;
- locationManager.removeUpdates(locationListener);
- }
- }
- /**
- * LocationListern监听器
- * 参数:地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器
- */
- LocationListener locationListener = new LocationListener() {
- /**
- * 当某个位置提供者的状态发生改变时
- */
- @Override
- public void onStatusChanged(String provider, int status, Bundle arg2) {
- }
- /**
- * 某个设备打开时
- */
- @Override
- public void onProviderEnabled(String provider) {
- }
- /**
- * 某个设备关闭时
- */
- @Override
- public void onProviderDisabled(String provider) {
- }
- /**
- * 手机位置发生变动
- */
- @Override
- public void onLocationChanged(Location location) {
- location.getAccuracy();//精确度
- setLocation(location);
- }
- };
- }
2.2调用
- private void initLocation(){
- Location location = LocationUtils.getInstance( EventsReportedActivity.this ).showLocation();
- if (location != null) {
- String address = "纬度:" + location.getLatitude() + "经度:" + location.getLongitude();
- Log.d( "FLY.LocationUtils", address );
- //text_location.setText( address );
- text_location.setText( getAddress(location.getLongitude(),location.getLatitude()));
- }
- }
3.转为具体地址
3.1方法
- public String getAddress(double lnt, double lat) {
- Geocoder geocoder = new Geocoder(EventsReportedActivity.this);
- boolean falg = geocoder.isPresent();
- Log.e("the falg is " + falg,"the falg is ");
- StringBuilder stringBuilder = new StringBuilder();
- try {
- //根据经纬度获取地理位置信息---这里会获取最近的几组地址信息,具体几组由最后一个参数决定
- List<Address> addresses = geocoder.getFromLocation(lat, lnt, 1);
- if (addresses.size() > 0) {
- Address address = addresses.get(0);
- for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
- //每一组地址里面还会有许多地址。这里我取的前2个地址。xxx街道-xxx位置
- if (i == 0) {
- stringBuilder.append(address.getAddressLine(i)).append("-");
- }
- if (i == 1) {
- stringBuilder.append(address.getAddressLine(i));
- break;
- }
- }
- //stringBuilder.append(address.getCountryName()).append("");//国家
- stringBuilder.append(address.getAdminArea()).append("");//省份
- stringBuilder.append(address.getLocality()).append("");//市
- stringBuilder.append(address.getFeatureName()).append("");//周边地址
- // stringBuilder.append(address.getCountryCode()).append("_");//国家编码
- // stringBuilder.append(address.getThoroughfare()).append("_");//道路
- Log.d("thistt", "地址信息--->" + stringBuilder);
- }
- } catch (Exception e) {
- Log.d("获取经纬度地址异常","");
- e.printStackTrace();
- }
- return stringBuilder.toString();
- }
3.2调用
String Address = getAddress(location.getLongitude(),location.getLatitude());