相信大家在项目中应该会经常用到这类功能,需要在请求api的时候获取当前定位信息,以便获取周边信息,以下是我常用的工具类,大家应该用得上
import android.annotation.suppresslint;
import android.content.context;
import android.location.location;
import android.location.locationmanager;
import android.os.handler;
import android.os.looper;
import androidx.annotation.nonnull;
/**
* 描述: 获取定位信息
* 创建者: it乐手
* 日期: 2025/5/21
*/
public class locationutils {
private final static string tag = "locationutils";
private static double latitude = 22.665424;
private static double longitude = 114.075724;
private static locationmanager locationmanager = null;
private static final handler mainhandler = new handler(looper.getmainlooper());
/**
* 获取经纬度
* @return 经纬度字符串
*/
public static string getlocationstring() {
double[] locations = getlocation();
string locationstr = locations[0]+","+locations[1];
atotologger.d(tag, locationstr);
return locationstr;
}
@suppresslint("missingpermission")
public static double[] getlocation() {
if (locationmanager == null) {
locationmanager = (locationmanager) appglobalutils.getapplication().getsystemservice(context.location_service);
}
// 检查gps/网络是否可用
boolean hasgps = locationmanager.isproviderenabled(locationmanager.gps_provider);
boolean hasnetwork = locationmanager.isproviderenabled(locationmanager.network_provider);
boolean haspassive = locationmanager.isproviderenabled(locationmanager.passive_provider);
atotologger.d(tag, "hasgps = " + hasgps + ", hasnetwork = " + hasnetwork + ", haspassive = " + haspassive);
if (!hasgps && !hasnetwork) {
atotologger.e(tag, "gps and network are not available");
return new double[]{0,0};
}
location location = locationmanager.getlastknownlocation(locationmanager.gps_provider);
if (location == null) {
atotologger.d(tag, "gps location is null, trying network location");
location = locationmanager.getlastknownlocation(locationmanager.network_provider);
}
if (location == null) {
atotologger.e(tag, "location is null");
// 在主线程中请求位置更新
if (looper.mylooper() == looper.getmainlooper()) {
requestlocationupdatesoncurrentthread();
} else {
mainhandler.post(locationutils::requestlocationupdatesoncurrentthread);
}
return new double[]{latitude,longitude};
}
latitude = location.getlatitude();
longitude = location.getlongitude();
atotologger.d(tag, "latitude: " + latitude + ", longitude: " + longitude);
// 处理经纬度信息
return new double[]{latitude, longitude};
}
@suppresslint("missingpermission")
private static void requestlocationupdatesoncurrentthread() {
try {
locationmanager.requestlocationupdates(
locationmanager.passive_provider,
0, // mintime (milliseconds)
0, // mindistance (meters)
locationlistener
);
} catch (exception e) {
atotologger.e(tag, "request location updates failed: " + e.getmessage());
}
}
private static final android.location.locationlistener locationlistener = new android.location.locationlistener() {
@override
public void onlocationchanged(location location) {
latitude = location.getlatitude();
longitude = location.getlongitude();
atotologger.d(tag, "location updated: latitude: " + latitude + ", longitude: " + longitude);
// 获取到位置后移除监听,避免持续更新
removelocationupdates();
}
@override
public void onstatuschanged(string provider, int status, android.os.bundle extras) {
}
@override
public void onproviderenabled(@nonnull string provider) {
}
@override
public void onproviderdisabled(@nonnull string provider) {
}
};
/**
* 移除位置更新监听
*/
public static void removelocationupdates() {
if (locationmanager != null) {
try {
locationmanager.removeupdates(locationlistener);
} catch (exception e) {
atotologger.e(tag, "remove location updates failed: " + e.getmessage());
}
}
}
@suppresslint("missingpermission")
private static location getlastknownlocation() {
if (locationmanager == null) return null;
location location = locationmanager.getlastknownlocation(locationmanager.gps_provider);
if (location == null) {
location = locationmanager.getlastknownlocation(locationmanager.network_provider);
}
return location;
}
}
方法补充
android 获取位置信息
android 提供 locationmanager 等相关api用于获取位置信息。
1.权限申请
app申请定位权限
manifest 文件中添加以下权限:
<uses-permission android:name="android.permission.access_coarse_location"/>
<uses-permission android:name="android.permission.access_fine_location"/>
- access_coarse_location: 允许一个程序访问cellid或wifi热点来获取粗略的位置
- access_fine_location: 允许一个程序访问精良位置(如gps)
开启手机定位服务
只有位置权限是不够的,还需要开启手机定位服务才能获取到位置信息。
/**
* 判断是否开启了gps或网络定位开关
*/
public boolean islocationproviderenabled() {
boolean result = false;
locationmanager locationmanager = (locationmanager) sdwanvpnapplication.getappcontext()
.getsystemservice(location_service);
if (locationmanager == null) {
return false;
}
if (locationmanager.isproviderenabled(locationmanager.gps_provider) || locationmanager
.isproviderenabled(locationmanager.network_provider)) {
result = true;
}
return result;
}
/**
* 跳转到设置界面,引导用户开启定位服务
*/
private void openlocationserver() {
intent i = new intent();
i.setaction(settings.action_location_source_settings);
startactivityforresult(i, request_code_location_server);
}
2.监听位置信息
android 可以通过网络或者gps,获取位置信息。gps获取比较准确,但是在室内有时候比较难获取到。
private final locationlistener mlocationlistener = new locationlistener() {
// provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
@override
public void onstatuschanged(string provider, int status, bundle extras) {
log.d(tag, "onstatuschanged");
}
// provider被enable时触发此函数,比如gps被打开
@override
public void onproviderenabled(string provider) {
log.d(tag, "onproviderenabled");
}
// provider被disable时触发此函数,比如gps被关闭
@override
public void onproviderdisabled(string provider) {
log.d(tag, "onproviderdisabled");
}
//当坐标改变时触发此函数,如果provider传进相同的坐标,它就不会被触发
@override
public void onlocationchanged(location location) {
log.d(tag, string.format("location: longitude: %f, latitude: %f", location.getlongitude(),
location.getlatitude()));
//更新位置信息
}
};
/**
* 监听位置变化
*/
private void initlocationlistener() {
locationmanager locationmanager = (locationmanager) myapplication.getappcontext()
.getsystemservice(location_service);
if (locationmanager == null) {
return;
}
locationmanager
.requestlocationupdates(locationmanager.network_provider, 1000, 10, mlocationlistener);
locationmanager
.requestlocationupdates(locationmanager.gps_provider, 1000, 10, mlocationlistener);
}
其中最重要的就是 requestlocationupdates 方法,使用指定的提供程序注册位置信息:
requestlocationupdates(string provider, long mintime, float mindistance, locationlistener listener) provider:注册的位置提供者名称 mintime:位置更新之间的最小时间间隔,以毫秒为单位 mindistance:位置更新之间的最小距离,以米为单位 listener:位置更新回调方法
该方法内部是通过handler进行通知回调,如果在非主线程调用该方法,需要多传入一个looper参数:
looper.prepare();
locationmanager
.requestlocationupdates(locationmanager.network_provider, 1000, 10, mlocationlistener, looper
.mylooper());
locationmanager
.requestlocationupdates(locationmanager.gps_provider, 1000, 10, mlocationlistener, looper
.mylooper());
如果只需要获取一次位置信息,获取后可以取消位置监听。
locationmanager.removeupdates(mlocationlistener);
3.获取最近一次位置信息
有时候由于各种原因例如在室内、网络问题等,导致注册的位置监听无法及时返回位置信息,这个时候可以使用 getlastknownlocation 方法返回一个从给定提供程序获得的最后一个已知位置数据。
private location getlastlocation() {
location location = null;
locationmanager locationmanager = (locationmanager) sdwanvpnapplication.getappcontext()
.getsystemservice(location_service);
if (locationmanager == null) {
return null;
}
list<string> providers = locationmanager.getproviders(true);
for (string provider : providers) {
location l = locationmanager.getlastknownlocation(provider);
if (l == null) {
continue;
}
if (location == null || l.getaccuracy() < location.getaccuracy()) {
// found best last known location: %s", l);
location = l;
}
}
return location;
}
4.通过经纬度获取详细地址
geocoder 相关api,支持通过经纬度获取详细位置信息
public static void getaddress(double latitude, double longitude) {
list<address> addresslist = null;
geocoder geocoder = new geocoder(myapplication.getappcontext());
try {
addresslist = geocoder.getfromlocation(latitude, longitude, 1);
} catch (ioexception e) {
e.printstacktrace();
}
if (addresslist != null) {
for (address address : addresslist) {
log.d(tag, string.format("address: %s", address.tostring()));
}
}
}
打印结果如下:
address: address[addresslines=[0:"福建省厦门市集美区诚毅北大街"],feature=null,admin=福建省,sub-admin=后溪镇,locality=厦门市,thoroughfare=诚毅北大街,postalcode=null,countrycode=cn,countryname=中国,haslatitude=true,latitude=24.622825253598176,haslongitude=true,longitude=118.05078728444207,phone=null,url=null,extras=null]
5.坐标系介绍
获取经纬度后在地图上查询发现,位置存在一定偏移,这个是因为使用的坐标系不一致引起的。
我国出于安全的考虑,会将所有的电子地图经行加偏处理,由真实的地理坐标系又称地球坐标系(wgs84)转换为火星坐标系(gcj02),但是使用 location 获取的经纬度又是wgs84坐标系的,所以再其他地图上显示会出现位置偏移现象。
目前坐标系主要有以下几种:
- wgs84坐标系:地球坐标系,国际通用坐标系
- gcj02坐标系:火星坐标系,wgs84坐标系加密后的坐标系,google国内地图、高德、qq地图使用
- bd09坐标系:百度坐标系,gcj02坐标系加密后的坐标系
可以调用你所使用的地图的服务商提供的坐标系转换接口进行坐标转换。
到此这篇关于android实现获取定位信息的工具类的文章就介绍到这了,更多相关android获取定位信息内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论