android - GPS定位不起作用
问题描述
我使用此功能查找我的位置。
public static String getadrr() {
String adres = "";
String bestProvider = null;
Geocoder geocoder = null;
List<Address> user = null;
double lati, longi;
LocationManager lm = (LocationManager) cx.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
bestProvider = lm.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(cx, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(cx, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
Location location = lm.getLastKnownLocation(bestProvider);
if (location == null){
return "CustomLocation Not found";
}else{
geocoder = new Geocoder(cx);
try {
user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
lati=(double)user.get(0).getLatitude();
longi=(double)user.get(0).getLongitude();
adres =(String)user.get(0).getAddressLine(0);
Log.e("Data","lat : "+lati);
Log.e("Data","long : "+longi);
Log.e("Data","adres : "+adres);
}catch (Exception e) {
e.printStackTrace();
}
}
return adres;
}
设备 GPS 已启用,但此功能始终返回“未找到自定义位置”,但当我在手机中运行 Google 地图应用程序时,此功能正常工作。我不明白这个错误的原因。
如何解决?
解决方案
getLastKnownLocation 几乎不应该被调用。如果设备已经有一个位置,它只会返回一个结果,而且它通常没有。相反,requestLocationUpdates 或 requestSingleUpdate 并等待回调。
推荐阅读
- python - 如何将 np.linalg.solve 移植到 R?
- c++ - 忽略 sprintf* 函数中的空白字符
- r - 因子变量标签,但按比例
- python - 验证 SIM 卡上的 ADM 以更改 IMSI
- node.js - 如何在 VS-Code 中更改为较旧/稳定版本的节点?
- python-3.x - Python,从外部类更新 statusBar()
- flutter - Firebase 在颤振应用中不显示通知
- r - 使用 rvest 包在 R 中抓取博客文章
- android - fastlane:[!] Google Api 错误:无效请求 - 找不到包:com.example.todo
- wso2 - 我可以在同一个集群中部署两个 wso2 api 管理器吗