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 use this post to achieve what you are looking for. Look at the setInterval(5000) will do that
You can use FusedLocationProviderAPI to make your application location aware. Using the Google Play services location APIs, your app can request the last known location of the user's device. In most cases, you are interested in the user's current location, which is usually equivalent to the last known location of the device.
For receiving most accurate location updates you can use this solution. https://developer.android.com/training/location/index.html
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);
you can check and integrate this library which is a wrapper for google play services location which also handles permissions.
google location
In this lib you can find various methods to set param