1.以下代码为我提供网络位置但不提供GPS位置
2.当我禁用我的WIFI时,它会给出网络位置
3.当我禁用我的网络时,它仅显示上一个已知位置
4.首先,我需要检查网络是否可用
5.如果网络可用从网络获取位置
6.否则我需要获得GPS的位置
public class GetandGiveLocation extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
String bestProvider;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
private static final long MIN_TIME_BW_UPDATES = 0;
protected LocationManager locationManager;
public GetandGiveLocation(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
showSettingsAlert();
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
@Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
GoogleMapViewer gmv = new GoogleMapViewer();
SendToWebsite stw = new SendToWebsite();
stw.execute(latitude, longitude);
}
}
答案 0 :(得分:0)
我的猜测是你可能想要改变
if (isNetworkEnabled) {
...
}
if (isGPSEnabled) {
...
}
要
if (isNetworkEnabled) {
...
}
else if (isGPSEnabled) {
...
}
否则它(我假设)如果两者都可用,则在转向GPS之前不会尝试WiFi。
选择GPS时,预热可能需要一些时间。在此期间,getLastKnownLocation可能是陈旧的,甚至是null。
我已经使用GPS实现了一些代码,用于确定GPS是否以及何时准备好提供有效数据(已经获得第一次修复)。您可以在此处找到代码:Location servise GPS Force closed
代码只关心GPS,但也必须修改以处理网络定位。我记得,我在上面的链接中提到的原始代码也有网络定位,所以不应该再次添加。
希望这有帮助 - 快乐编码