参考博客:
https://blog.csdn.net/mingjiezuo/article/details/79755357
https://blog.csdn.net/qq_26420489/article/details/52120471
最后生成的工具类
package com.welldones.door.utils;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
public class LocationUtils {
public static String judgeProvider(LocationManager locationManager, Context context) {
List<String> prodiverlist = locationManager.getProviders(true);
if (prodiverlist.contains(LocationManager.NETWORK_PROVIDER)) {
return LocationManager.NETWORK_PROVIDER;//网络定位
} else if (prodiverlist.contains(LocationManager.GPS_PROVIDER)) {
return LocationManager.GPS_PROVIDER;//GPS定位
} else {
Toast.makeText(context, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
}
return null;
}
/**
* 获取定位的经纬度信息
*
* @param locationManager
* @param context
* @return
*/
public static Location beginLocatioon(LocationManager locationManager, Context context) {
//获得位置服务
String provider = judgeProvider(locationManager, context);
//有位置提供器的情况
if (provider != null) {
//为了压制getLastKnownLocation方法的警告
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return null;
}
return locationManager.getLastKnownLocation(provider);
} else {
//不存在位置提供器的情况
Toast.makeText(context, "不存在位置提供器的情况", Toast.LENGTH_SHORT).show();
}
return null;
}
/**
* 将经纬度转换为城市
*
* @return
*/
public static String getCityName(LocationManager locationManager, Context context) {
Location location = beginLocatioon(locationManager, context);
String mCityName = null;
Geocoder geocoder = new Geocoder(context);
if (null != location) {
try {
List<Address> fromLocation = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (fromLocation != null && fromLocation.size() > 0) {
for (int i = 0; i < fromLocation.size(); i++) {
Address address = fromLocation.get(i);
mCityName = address.getLocality();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
return mCityName;
}
}
使用:
LocationManager locationManager;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(null != LocationUtils.getCityName(locationManager,this)) {
tv_address.setText(LocationUtils.getCityName(locationManager,this));
}else {
tv_address.setText("null");
}
权限添加:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
遇到的问题:
不存在位置提供器:手动打开应用的 读取位置权限。暂时没有发现怎么通过代码解决