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?
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.