gpt4 book ai didi

android - 试图通过手机信号塔获取位置但仍返回 null

转载 作者:行者123 更新时间:2023-11-29 19:09:01 26 4
gpt4 key购买 nike

我想做的是从用户那里获取位置信息。首先它尝试通过 GPS 获取位置并检查位置是否可用。如果不是,则它会尝试通过网络塔。当 GPS 打开时,它工作正常。但是当我关闭 GPS 时,它无法使用网络提供商获取位置

 manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = manager.getBestProvider(new Criteria(), false);

Log.i("ITEMSET best", provider);


manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}

Log.i("ITEMSET provider", provider);

location = manager.getLastKnownLocation(provider);
Log.i("ITEMSET netLoc", location + "");
if(location==null) {
provider = LocationManager.NETWORK_PROVIDER;
location = manager.getLastKnownLocation(provider);
Log.i("ITEMSET netLoc", location + "qqq");
}



Log.i("ITEMSET current", provider);
Log.i("ITEMSET location", location + "");

Logcat

Location 最初为空,因为 GPS 未打开。但随后将提供商更改为网络提供商。但位置仍然为空

最佳答案

检查网络是否开启

 isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

然后:

     if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000,10, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {

latitude = location.getLatitude();
longitude = location.getLongitude();


}
}

关于android - 试图通过手机信号塔获取位置但仍返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46069293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com