Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Location returns 0.0 with WIFI/3G/4G in Lollipop 5.0.2

I am trying to fetch location based on WiFi/3G/4G connection but it always returns 0.0 as latitude and longitude. If same code is used with GPS ON then it works so something is changed from 4.4 onwards.

Also tried following link but its not working too.

http://www.androidhive.info/2015/02/android-location-api-using-google-play-services/

public class GPSTracker extends Service implements LocationListener {

private static final String TAG = "GPSTracker";

private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude
double speed;
double altitude;
double bearings;

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 5000; // 10 seconds

protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {

    try {

        if (mContext == null)
            Log.d("GPS Tracker", "Context is null");

        locationManager = (LocationManager) mContext
                .getSystemService(Context.LOCATION_SERVICE);

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

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

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled

            Log.d("GPSTracker", "No Provider is Enabled");

        } else {
            this.canGetLocation = true;
            // First get location from Network Provider

            if (isNetworkEnabled) {

                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                Log.d("GPSTracker", "Network Enabled");

                if (locationManager != null) {

                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                    if (location != null) {

                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        altitude = location.getAltitude();
                        speed = location.getSpeed();
                        bearings = location.getBearing();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {

                if (location == null) {

                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    Log.d("GPSTracker", "GPS Enabled");

                    if (locationManager != null) {

                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);

                        if (location != null) {

                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            altitude = location.getAltitude();
                            speed = location.getSpeed();
                            bearings = location.getBearing();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener Calling this function will stop using GPS in your
 * app
 * */
public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * 
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}

Is there any solution to get location based on WiFi/Dataconnection from 4.4 kitkat onwards??

Any help/suggestion would be appreciated.

like image 650
moDev Avatar asked Jan 09 '23 18:01

moDev


2 Answers

The steps to be followed :

Step 1 : check the following permission in Manifest File

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Step 2 : check the service class

import android.annotation.SuppressLint;


public class  GPSTracker extends Service implements LocationListener {

public static boolean isGPSEnabled = false;
public static boolean isNetworkEnabled = false;
static boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 2; // 2 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;

@Override
public IBinder onBind(Intent arg0) {
    return null;
}
@SuppressWarnings("static-access")
@Override
public void onCreate() {
    super.onCreate();
    Log.d("onCreate", "Success !");
        latitudeAndLongtitude();
}

public void latitudeAndLongtitude()
{
    locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
    isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (!isGPSEnabled && !isNetworkEnabled) {
        Toast.makeText(getApplicationContext(), "No provider found!", Toast.LENGTH_SHORT).show();
    }else{
        GPSTracker.canGetLocation = true;
        if(isGPSEnabled)
        {
            if (location == null) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            Log.d("Network", "GPS");
            if (locationManager != null) {
                Log.d("locationManager", "is not null ");
                location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location != null) {
                    Log.d("Network", "GPS lat and long gets ");
                    Toast.makeText(getApplicationContext(), "isNetworkEnabled!", Toast.LENGTH_SHORT).show();
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                    Helper.savePreferences(getApplicationContext(), NameConversion.LATITUDE,String.valueOf(latitude));
                    Helper.savePreferences(getApplicationContext(), NameConversion.LONGITUDE,String.valueOf(longitude));
                }else{
                    Log.d("location", "is getting null ");
                }
            }
        }
    }
        else if(isNetworkEnabled)
        {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            Log.d("Network", "Network");
            if (locationManager != null) {
                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (location != null) {
                    //Toast.makeText(getApplicationContext(), "isGPSEnabled!", Toast.LENGTH_SHORT).show();
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                    Helper.savePreferences(getApplicationContext(), NameConversion.LATITUDE,String.valueOf(latitude));
                    Helper.savePreferences(getApplicationContext(), NameConversion.LONGITUDE,String.valueOf(longitude));
                }
            }
        }
    }
}
public Location getLocation() {
    return location;
}
/**
 * Stop using GPS listener Calling this function will stop using GPS in your
 * app
 * */
public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}
/**
 * Function to get latitude
 * */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }
    // return latitude
    return latitude;
}
/**
 * Function to get longitude
 * */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }
    // return longitude
    return longitude;
}

public void sendLocationToServer() {
    Log.i("sendLocationToServer", "Called!");

}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.i("onDestroy", "Called!");
    stopSelf();

}

/**
 * Function to check GPS/wifi enabled
 * 
 * @return boolean
 * */
@SuppressWarnings("static-access")
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog On pressing Settings button will
 * lauch Settings Options
 * */
@SuppressLint("NewApi")

@Override
public void onLocationChanged(Location location) {

    latitudeAndLongtitude();
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}}

step 3 : Enable the service in Manifest file

inside application tag

  <service
        android:name=“.your package name.GPSTracker"
        android:enabled="true" >
    </service>

setp 4 : start the service in where you want

Hope this will work if you face stil problem may be your mobile will not get the GPS and Network Locaiton .

like image 95
John Avatar answered Jan 13 '23 12:01

John


When you call locationManager.requestLocationUpdates() this tells Android that you would like to be called back when the user's location changes. If you don't have GPS enabled and you want to use NETWORK_PROVIDER, you need to have Internet access. This all happens asynchronously. You call requestLocationUpdates() and then some time later, Android will call you back by calling onLocationChanged() with the new location.

What you are doing after calling requestLocationUpdates() is immediately calling getLastKnownLocation() which may or may not return something useful. In your implementation of onLocationChanged() you are doing nothing. You will need to wait until Android calls onLocationChanged() at which point you should store the passed Location parameter in your member variable.

like image 35
David Wasser Avatar answered Jan 13 '23 10:01

David Wasser