当GPS提供商没有正确的位置更新时,在android中更改我的位置提供程序

时间:2013-03-25 12:54:06

标签: android location

我需要定期跟踪用户位置。

为此,我在我的服务的onCreate方法中调用requestLocationUpdates()。

@Override
public void onCreate()
{
LocationManager aLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

aLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, new LocationListener(LocationManager.GPS_PROVIDER));
}

通常,我会通过此GPS_PROVIDER以固定时间间隔获取位置更新。但是,在某些地区,我无法正确获取位置更新。在这些方面,我喜欢切换requestLocationUpdates调用以使用NETWORK_PROVIDER。

因此,当我无法从GPS_PROVIDER获得正确的位置更新时,我可以切换requestLocationUpdates以使用NETWORK_PROVIDER。

我该怎么做?检查某种条件并更改onStatusChanged()中的requestLocationUpdates()是否正确。

建议请。

谢谢。

2 个答案:

答案 0 :(得分:2)

是的,有办法做到这一点。如果错误,您可以使用locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)检查GPS提供商是否可用,然后使用网络提供商

您还可以覆盖onProviderEnabled()和onProviderDisabled()以从GPS切换到网络 如果您想使用库,则可以使用此位置跟踪库 https://github.com/nagendraksrivastava/Android-Location-Tracking-Library 它漂亮的图书馆和完美的工作

这里是获取所有提供者列表的代码,并在此基础上获取数据,所以在这种情况下你应该担心提供者

LocationManager mLocationManager = new LocationManager()
List<String> matchingProviders = mLocationManager.getProviders(true);
for(String provider : matchingProviders ){
Location location = mLocationManager.getLastKnownLocation(provider);
if(location != null){
double lat = location.getLatitude();
}

答案 1 :(得分:1)

试试这个代码对我有用......

void currentlocation(){
    LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Called when a new location is found by the network location provider.
            MyContants.lat = location.getLatitude();
            MyContants.lon = location.getLongitude();
            //  Log.w(MyContants.ScanResult_TAG, "Currnet Location==="+String.valueOf(lat)+"-----"+String.valueOf(lon));
        }
        public void onStatusChanged(String provider, int status, Bundle extras) {}
        public void onProviderEnabled(String provider) {}
        public void onProviderDisabled(String provider) {}

    };


    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    //GPS location updates.
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}

USE Permission

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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" />