I tried many code snippets but all the example takes too much time to provide latitude and longitude .
I want to get current latitude in every 5 seconds .
You can create service that broadcasts your latitude and longitude in every 5 seconds using LocationManager.
public class MyLocationService extends Service {
private LocationManager locationManager;
private LocationListener locationListener;
public final String APP_BROADCAST_RECEIVER = "LatLonReciever"; // You should define it somewhere else as a static. e.g within Const class
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (locationListener == null ) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
locationIsChanged(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 5000, locationListener); // here 5000 is 5 seconds
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void locationIsChanged(Location location){
Intent intent = new Intent(APP_BROADCAST_RECEIVER);
intent.putExtra("lat", location.getLatitude());
intent.putExtra("lon", location.getLongitude());
sendBroadcast(intent);
}
}
Also, don't foret to register the reciever where you want to recieve the results:
public final String APP_BROADCAST_RECEIVER = "LatLonReciever";
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Here you do what you want with recieved intent that contains lat and lon
}
};
IntentFilter intentFilter = new IntentFilter(APP_BROADCAST_RECEIVER);
registerReceiver(broadcastReceiver, intentFilter);