Getting Location frequently from the Android Device

  • Replies:0
Chetan Talwar
  • Forum posts: 1

Nov 14, 2015, 7:12:08 AM via Website

I wish to get the location of the user after some specific (but variable) point of time, even if he is at the same position. I have tried services, alarm manager in service, broadcast receiver, etc.. for the purpose, but still i am not getting that what i need. In a single activity, i am getting the location but when i implement in service it just says 0.00,0.00. This is GPS tracker class which is fetching the location

public Location getLocation() {
try {
    locationManager = (LocationManager) mContext
            .getSystemService(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
    } else {
        this.canGetLocation = true;
        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) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }
            }
        }
        // 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("GPS Enabled", "GPS Enabled");
                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;

}

I have created this function in a class and further using this in service using thread and then using a receiver i initiating it in main activity but it is returning 0.00,0.00. Don't know whether its the right way to do so.

— modified on Nov 14, 2015, 7:24:11 AM

Reply