How to get current gps location both online or offline in android?

限于喜欢 提交于 2019-12-11 18:41:54

问题


I want to get the current location working with both online or offline GPS as well the expected behavior of the GPS is: 1. If wifi or 3g networks are available, it will use those to fetch the GPS position. 2. If NO wifi or 3g networks are avaiable it will use the OFFLINE GPS of the tablet (if present) 3. If nothing is present, it will display the Error message.

I am trying a lot but not succeeded yet. I am getting network enabled always true.

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;
    }

If any one have idea. Please help. Thanks in advance


回答1:


Instead of a single function split it into two functions to check which one is enabled

ie

To check if GPS enabled

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;
}

To check if WIFI enabled

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;
}

Then whenever you want to check it,try this

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


来源:https://stackoverflow.com/questions/25574128/how-to-get-current-gps-location-both-online-or-offline-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!