@Android 定位不依赖三方sdk
申请定位权限
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<!-- 网络权限 -->
<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"/>
<!-- 模拟定位授权 -->
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"
tools:ignore="MockLocation,ProtectedPermissions" />
定义LocationManager对象实现监听接口
获取到维度 经度 使用GetAddressUtil工具类得到位置信息
根据经纬度获取当前位置地址信息工具类
package com.example.myapplication;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.util.Log;
import androidx.annotation.RequiresApi;
import java.util.List;
public class GetAddressUtil {
Context context;
public GetAddressUtil(Context context) {
this.context = context;
}
@RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
public String getAddress(double lnt, double lat) {
Geocoder geocoder = new Geocoder(context);
boolean falg = geocoder.isPresent();
StringBuilder stringBuilder = new StringBuilder();
try {
//根据经纬度获取地理位置信息—这里会获取最近的几组地址信息,具体几组由最后一个参数决定
List
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.getAdminArea());//省份
stringBuilder.append(address.getLocality());//市
stringBuilder.append(address.getFeatureName());//周边地址
Log.d(“wy”, “地址信息—>” + stringBuilder);
}
} catch (Exception e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
}
来源:oschina
链接:https://my.oschina.net/u/4284321/blog/4873645