如何在Android中在线或离线获取当前的gps位置?

时间:2014-08-29 18:25:54

标签: android gps location

我想让当前位置同时使用在线或离线GPS,以及GPS的预期行为是: 1.如果有wifi或3g网络可用,它将使用它们来获取GPS位置。 2.如果没有wifi或3g网络可用,它将使用平板电脑的OFFLINE GPS(如果有的话) 3.如果不存在任何内容,则会显示错误消息。

我正在尝试很多但尚未成功。我的网络启用始终是真的。

public boolean isGPSEnabled() {
        Location location = null;
        try {
            mLocationManager = (LocationManager) getApplicationContext()
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
                return false;
            }
        } catch (Exception e) {
            toast("Exception " + e.toString());
        }
        return true;
    }

如果有人有想法。请帮忙。提前致谢

1 个答案:

答案 0 :(得分:0)

而不是单个函数将其拆分为两个函数来检查哪个函数已启用

检查是否已启用GPS

public boolean isGPSEnabled() {
    Location location = null;
    try {
        mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
        // getting GPS status
        isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception e) {
        toast("Exception " + e.toString());
    }
    return true;
}

检查是否启用了WIFI

public boolean isWIFIEnabled() {
    Location location = null;
    try {
        mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
        // getting network status
        isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception e) {
        toast("Exception " + e.toString());
    }
    return true;
}

然后,只要你想检查它,试试这个

if(isWIFIEnabled())
{
    //request location updates from network provider
}
else if(isGPSEnabled())
{
    //request location updates from gps provider    
}
else
{
    //display error
}