Get Current Location in background

2.4k views Asked by At

I am currently working on a project which is include in get current location every 5 second. I create a service for that. But current location not getting. I try this link. But I am not getting current Location.

public class Locfetching extends Service{

LocationManager locationManager;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e("2", "2");
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    MyLocationListener myLocationListener = new MyLocationListener();
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1, myLocationListener);

    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location != null) {
        Log.e("SERVICE123", "LATITUDE:- "+ location.getLatitude() + " Longitude:- " + location.getLongitude());
    }

    return START_STICKY;
}

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

@Override
public void onCreate() {
    super.onCreate();
    Log.e("1", "1");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.e("3", "3");
    if (locationManager != null) {
        locationManager = null;
    }
}

public class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        Log.e("SERVICE", "LATITUDE:- "+ location.getLatitude() + " Longitude:- " + location.getLongitude());
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

}   }

How can I getting current location in background?

3

There are 3 answers

0
praveen On

You haven't made enough research What is the simplest and most robust way to get the user's current location on Android? is the best ans i can provide you

0
Guy S On

try checking if the location provider is enabled.

also, check if you're getting a location with the network provider

if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1, myLocationListener);

} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 1, myLocationListener);

}
1
Eldhose M Babu On

Have you checked Location services for that phone? Is it enabled? If it seems enabled, please turn it off and on and click on agree (in the case of Android 4+ devices). Then check, it should work. Also check, whether you have added permissions for the same in the manifest.