Getting Latitude and Longitude in 30 Seconds

Getting Latitude and longitude in 30 seconds

Please check how i'm using in my app and its working perfect.I'm using fused api for update location please follow few steps.Currently you using very old approach.So, there is no need now
and pass here your time in milliseconds what you want
UPDATE_INTERVAL_IN_MILLISECONDS

Step 1. Make this class
GoogleLocationService.java

public class GoogleLocationService {
private GoogleServicesCallbacks callbacks = new GoogleServicesCallbacks();
LocationUpdateListener locationUpdateListener;
Context activity;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;

public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 30000;

public GoogleLocationService(Context activity, LocationUpdateListener locationUpdateListener) {
this.locationUpdateListener = locationUpdateListener;
this.activity = activity;
buildGoogleApiClient();
}

protected synchronized void buildGoogleApiClient() {
//Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(activity)
.addConnectionCallbacks(callbacks)
.addOnConnectionFailedListener(callbacks)
.addApi(LocationServices.API)
.build();
createLocationRequest();
mGoogleApiClient.connect();
}

protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

}

private class GoogleServicesCallbacks implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

@Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}

@Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) {
Toast.makeText(activity, "Google play service not updated", Toast.LENGTH_LONG).show();

}
locationUpdateListener.cannotReceiveLocationUpdates();
}

@Override
public void onLocationChanged(Location location) {
if (location.hasAccuracy()) {
if (location.getAccuracy() < 30) {
locationUpdateListener.updateLocation(location);
}
}
}
}

private static boolean locationEnabled(Context context) {
boolean gps_enabled = false;
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
return gps_enabled;
}

private boolean servicesConnected(Context context) {
return isPackageInstalled(GooglePlayServicesUtil.GOOGLE_PLAY_STORE_PACKAGE, context);
}

private boolean isPackageInstalled(String packagename, Context context) {
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}

public void startUpdates() {
/*
* Connect the client. Don't re-start any requests here; instead, wait
* for onResume()
*/
if (servicesConnected(activity)) {
if (locationEnabled(activity)) {
locationUpdateListener.canReceiveLocationUpdates();
startLocationUpdates();
} else {
locationUpdateListener.cannotReceiveLocationUpdates();
Toast.makeText(activity, "Unable to get your location.Please turn on your device Gps", Toast.LENGTH_LONG).show();
}
} else {
locationUpdateListener.cannotReceiveLocationUpdates();
Toast.makeText(activity, "Google play service not available", Toast.LENGTH_LONG).show();
}
}

//stop location updates
public void stopUpdates() {
stopLocationUpdates();
}

//start location updates
private void startLocationUpdates() {

if (checkSelfPermission(activity, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(activity, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, callbacks);
}
}

public void stopLocationUpdates() {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, callbacks);
}
}

public void startGoogleApi() {
mGoogleApiClient.connect();
}

public void closeGoogleApi() {
mGoogleApiClient.disconnect();
}

}

Step2. Make this interface
LocationUpdateListener.java

 public interface LocationUpdateListener {

/**
* Called immediately the service starts if the service can obtain location
*/
void canReceiveLocationUpdates();

/**
* Called immediately the service tries to start if it cannot obtain location - eg the user has disabled wireless and
*/
void cannotReceiveLocationUpdates();

/**
* Called whenever the location has changed (at least non-trivially)
* @param location
*/
void updateLocation(Location location);

/**
* Called when GoogleLocationServices detects that the device has moved to a new location.
* @param localityName The name of the locality (somewhere below street but above area).
*/
void updateLocationName(String localityName, Location location);
}

Step 3. Make this Location service class
LocationService.java

public class LocationService extends Service {

private GoogleLocationService googleLocationService;

@Override
public void onCreate() {
super.onCreate();
//start the handler for getting locations
//create component

updateLocation(getApplicationContext());
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}

//get current location os user
private void updateLocation(Context context) {
googleLocationService = new GoogleLocationService(context, new LocationUpdateListener() {
@Override
public void canReceiveLocationUpdates() {
}

@Override
public void cannotReceiveLocationUpdates() {
}

//update location to our servers for tracking purpose
@Override
public void updateLocation(Location location) {
if (location != null ) {
Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude());

}
}

@Override
public void updateLocationName(String localityName, Location location) {

googleLocationService.stopLocationUpdates();
}
});
googleLocationService.startUpdates();
}

IBinder mBinder = new LocalBinder();

public class LocalBinder extends Binder {
public LocationService getServerInstance() {
return LocationService.this;
}
}

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

//stop location updates on stopping the service
@Override
public void onDestroy() {
super.onDestroy();
if (googleLocationService != null) {
googleLocationService.stopLocationUpdates();
}
}
}

Edited Answer:

How to use service,

Start service in your main activity,like this

startService(new Intent(context, LocationService.class));

for stop,

stopService(new Intent(context, LocationService.class));

and declare in manifest like this,

<service
android:name=".service.location.LocationService"
android:enabled="true"></service>

Note: I have done this because i need location after killed the app.If you dont want service.Then,you can call directly below code in class where location need to be update and remove locationservice.

 private GoogleLocationService googleLocationService;

googleLocationService = new GoogleLocationService(context, new LocationUpdateListener() {
@Override
public void canReceiveLocationUpdates() {
}

@Override
public void cannotReceiveLocationUpdates() {
}

//update location to our servers for tracking purpose
@Override
public void updateLocation(Location location) {
if (location != null ) {
Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude());

}
}

@Override
public void updateLocationName(String localityName, Location location) {

googleLocationService.stopLocationUpdates();
}
});
googleLocationService.startUpdates();

and call this onDestroy
if (googleLocationService != null) {
googleLocationService.stopLocationUpdates();
}

Remember Locationservice should be declare in manifest as well.
According to me this is the best solution.I have done alot of work on location.
Thanks hope this will help you

Getting Geolocation after every 30 seconds

Try this:

function success(position) {
//retrieve lat and long
var latitude = position.coords.latitude
var longitude = position.coords.longitude
}

function error(){
//error handling
}

setInterval(function(){
navigator.geolocation.getCurrentPosition(success, error);
}, 30000);

getting geolocation after 20 seconds

Note that you shouldn't be calling getLastKnownLocation() every second if you have a Location Listener set up (which it looks like you do). Just use the latest values given in the onLocationChanged() callback.

This code works for me, it registers a Location Listener, which updates the lat/lon member variables, and then the Runnable runs with an initial interval of one second, and then every five seconds (5000 milliseconds) and displays the most current location value.

I put in a Toast to make sure that the Runnable is being run every 5 seconds by handler.postDelayed().

Here is the full Activity code:

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements LocationListener {

LocationManager locationManager;
Handler handler;
Location location;

double latitude;
double longitude;

TextView lat;
TextView lon;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

handler = new Handler();

lat = (TextView) findViewById(R.id.latitudeTextView);
lon = (TextView) findViewById(R.id.longitudeTextView);

locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}

handler.postDelayed(runLocation, 1000);
}

public Runnable runLocation = new Runnable(){
@Override
public void run() {
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Toast.makeText(MainActivity.this, "location check", Toast.LENGTH_SHORT).show();

MainActivity.this.handler.postDelayed(MainActivity.this.runLocation, 5000);
}
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

@Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

Edit:

As an alternative, you could take out the use of postDelayed(), and just use the onLocationChanged() events.

In the example below, I used both NETWORK_PROVIDER and GPS_PROVIDER.

This is needed in the AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Here is the modified code, which registers the Activity as a Location Listener for both Network location callbacks and GPS location callbacks, with a minimum time interval of one second. Note that events can come in at a greater interval than one second, but with the GPS location enabled, I saw them coming in every second (it was taking longer with only Network location enabled).

public class MainActivity extends ActionBarActivity implements LocationListener {

LocationManager locationManager;
Handler handler;
Location location;

double latitude;
double longitude;

TextView lat;
TextView lon;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

handler = new Handler();

lat = (TextView) findViewById(R.id.latitudeTextView);
lon = (TextView) findViewById(R.id.longitudeTextView);

locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}

//handler.postDelayed(runLocation, 1000);
}
/*
public Runnable runLocation = new Runnable(){
@Override
public void run() {
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Toast.makeText(MainActivity.this, "location check", Toast.LENGTH_SHORT).show();

MainActivity.this.handler.postDelayed(MainActivity.this.runLocation, 5000);
}
};
*/

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

@Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();

lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Toast.makeText(MainActivity.this, "location changed: " + latitude + " " + longitude, Toast.LENGTH_SHORT).show();
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

getting latitude and longitude using gps every 10 minute in background android

I am using this way and solve my problem.

PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), PERIOD , pi);

I am don't know this is right or wrong.but work for me.
Thanks @Lucifer,@Maya mAku and @piotrpo for your guidline.

How to find my current location (latitude + longitude) in every 5 second in Android?

You can use this post to achieve what you are looking for. Look at the setInterval(5000) will do that

Sample Image

i want to trigger current location every 30 secs in google maps api

If you want just to run this method in intervals, try java class Timer

int delay = 5000;   // delay for 5 sec.
int interval = 30000; // iterate every 30 sec.
Timer timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
getCurrentLocation // Your method from above ..
}
}, delay, interval);


Related Topics



Leave a reply



Submit