I have a singelton thread-class that sends the gps point to my server. The class holds and refresh the gps position.
FinderThread:
public class FinderThread extends Thread {
private static FinderThread SINGLETON;
public boolean isinterrupt = true;
public int maxage;
public int minage;
public int distance;
public String gender;
public String latitude;
public String longitude;
public String sid;
public Context ctx;
LocationManager gps;
boolean nav;
SharedPreferences pref;
private Handler dlh;
private Handler myLocationHandler;
boolean pause=false;
private FinderThread(Context ctx,Handler dlh, Handler myLocationHandler) {
this.ctx = ctx;
gps = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
gps.requestLocationUpdates( LocationManager.GPS_PROVIDER,60000, 20, llistener);
pref = ctx.getSharedPreferences("NFF", 0);
sid = pref.getString("sid", "");
this.dlh = dlh;
if (myLocationHandler!=null)
{
this.myLocationHandler = myLocationHandler;
}
if(myLocationHandler != null)
{
myLocationHandler.sendEmptyMessage(0);
}
}
public static synchronized FinderThread getInstance(Context ctx,Handler dlh, Handler myLocationHandler)
{
if (SINGLETON == null) // falls null
{
SINGLETON = new FinderThread (ctx,dlh,myLocationHandler);//instanzieren
}
else
{
SINGLETON.myLocationHandler= myLocationHandler;
SINGLETON.dlh = dlh;
myLocationHandler.sendEmptyMessage(0);
}
return SINGLETON;
}
/*
#Override
public synchronized void start() {
if(SINGLETON != null)
{
SINGLETON.start();
}
}
public synchronized void pause()
{
if(SINGLETON.getState()==State.RUNNABLE || SINGLETON.getState()==State.WAITING)
{
SINGLETON.pause = true;
}
}
public synchronized void tcontinue ()
{
if(SINGLETON.getState()==State.RUNNABLE || SINGLETON.getState()==State.WAITING)
{
SINGLETON.pause = false;
}
}
public synchronized boolean isPaused()
{
return SINGLETON.pause;
}
*/
public synchronized void pause()
{
this.pause = true;
}
public synchronized boolean isPaused()
{
return this.pause;
}
public synchronized void tcontinue ()
{
this.pause = false;
}
#Override
public void run() {
//String locationProvider = LocationManager.GPS_PROVIDER;
//Location lastpoint = gps.getLastKnownLocation(locationProvider);
//longitude = String.valueOf(lastpoint.getLongitude());
//latitude = String.valueOf(lastpoint.getLatitude());
try
{
while (isinterrupt) {
if(!pause)
{
Log.e("NFF", "Finder Thread Begin");
RestConnection r = new RestConnection("finder", dlh, "POST");
r.setParameter("minage", String.valueOf(minage));
r.setParameter("maxage", String.valueOf(maxage));
r.setParameter("distance", String.valueOf(distance));
r.setParameter("gender", String.valueOf(gender));
r.setParameter("latitude", String.valueOf(latitude));
r.setParameter("longitude", String.valueOf(longitude));
r.setParameter("sid", sid);
Log.e("NFF Finder Paramater", String.valueOf(minage)+" "+String.valueOf(maxage)+" "+String.valueOf(distance)+" "+String.valueOf(gender) + " "+String.valueOf(latitude)+" " +String.valueOf(longitude)+ " " + sid );
r.start();
}
Thread.sleep(10000);
}
}
catch (InterruptedException e) {
Log.e("NFF FT", "InterruptedException");
isinterrupt = false;
}
}
private LocationListener llistener = new LocationListener (){
#Override
public void onLocationChanged(Location location) {
if(String.valueOf(location.getLatitude())!= null)
{
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLongitude());
if(myLocationHandler != null)
{
myLocationHandler.sendEmptyMessage(0);
}
}
}
#Override
public void onProviderDisabled(String provider) {
Log.e("NFF", "GPS Disabled");
isinterrupt = true;
}
#Override
public void onProviderEnabled(String provider) {
Log.e("NFF", "GPS Enabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
public void saveProperties ()
{
Editor editor = pref.edit();
editor.putInt("maxage", maxage);
editor.putInt("minage", minage);
editor.putInt("distance", distance);
editor.putString("gender", gender);
editor.putString("lat", latitude);
editor.putString("long", longitude);
editor.commit();
}
public void loadProperties ()
{
maxage = pref.getInt("maxage", -1);
minage = pref.getInt("minage", -1);
distance = pref.getInt("distance", -1);
gender = pref.getString("gender", "f");
latitude = pref.getString("lat", "f");
longitude = pref.getString("long", "f");
}
public synchronized void pushSettings()
{
SINGLETON.maxage = maxage;
SINGLETON.minage = minage;
SINGLETON.distance = distance;
SINGLETON.gender = gender;
SINGLETON.latitude = latitude;
SINGLETON.longitude = longitude;
}
}
When i test my app on the emulator and set the position with the emulator control everthing work fine. When i test it on my phone, the droid don't find the position. I have testet the app "GPS Test", there it finds the position within 3 minutes with 5 sattelites.
Please help
It sure looks like you have everything there.
You give yourself the permission in the manifest for FINE_LOCATION, right?
The one suggestion I would make is change your requestLocationUpdates() so that it requests fixes with 0 time between them and 0 distance between them. All GPS recievers I have seen will give you fixes about once a second with this setting, which is pretty much how most gps engines work. Just on the off-chance that the one-minute and 20 m you put in your request are screwing you up. If you get fixes with this suggestion, you can work from there to minimize amount of time gps is on.
Good luck!
Related
i have made a background service which fetches value to database every 40 seconds but here longitude and latitude values are not updating, while in GPSTracker service, the values are updating every 30 second. This Service only fetches the first value of coordinates it get..
BackService.java:
public class BackService extends Service {
static double latitude,longitude;
GPSTracker gpsTracker;
private static final String DATA_URL = "http://"+Userstate.IP+"/spytracem/enter_loc.php";
public BackService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
gpsTracker = new GPSTracker(getApplicationContext());
if (gpsTracker.canGetLocation()) {
longitude = gpsTracker.getLongitude();
latitude = gpsTracker.getLatitude();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Runnable r = new Runnable() {
#Override
public void run() {
for (int a = 0; a < 10; a++) {
if (!getSharedPreferences(Userstate.STATESAVE,Context.MODE_PRIVATE).getBoolean(Userstate.status,false))
{
long futuretime = System.currentTimeMillis() + 40000;
while (System.currentTimeMillis() < futuretime) {
synchronized (this) {
try {
wait(futuretime - System.currentTimeMillis());
System.out.println(getSharedPreferences(Userstate.SHARED_PREF_NAME,Context.MODE_PRIVATE).getString(Userstate.EMAIL_SHARED_PREF,"No User"));
System.out.println(longitude);
System.out.println(latitude);
enter(getSharedPreferences(Userstate.SHARED_PREF_NAME,Context.MODE_PRIVATE).getString(Userstate.EMAIL_SHARED_PREF,"No User"), String.valueOf(longitude), String.valueOf(latitude));
if (a == 9) {
a = 0;
}
} catch (Exception e) {
}
}
}
}
else
{
getSharedPreferences(Userstate.STATESAVE, Context.MODE_PRIVATE).edit().putBoolean(Userstate.status,true);
stopSelf();
break;
}
}
}
};
Thread thread = new Thread(r);
thread.start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
getSharedPreferences(Userstate.STATESAVE,Context.MODE_PRIVATE).edit().putBoolean(Userstate.status,true);
}
private void enter( String email, String longitude, String latitude) {
class Enter extends AsyncTask<String, Void, String> {
Locationhander ruc11 = new Locationhander();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
System.out.println("Location Entered Boss!");
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data2 = new HashMap<String,String>();
data2.put("email",params[0]);
data2.put("longitude",params[1]);
data2.put("latitude",params[2]);
String result2 = ruc11.sendPostRequest(DATA_URL,data2);
return result2;
}
}
Enter ru2 = new Enter();
ru2.execute(email, longitude, latitude);
}
}
Try to make latitude,longitude volatile:
static volatile double latitude,longitude;
And also your code:
longitude = gpsTracker.getLongitude();
latitude = gpsTracker.getLatitude();
Must be called every time, you call it only in onCreate().
I am making an android app where I am trying to get location using location manager and then I push that location to a server. When I try to do this I am getting the following error.
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:223)
at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:223)
at android.location.LocationManager.wrapListener(LocationManager.java:851)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:864)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:459)
at com.pickingo.fe.services.gps.AppLocationService.getLocation(AppLocationService.java:30)
at com.pickingo.fe.gps.CurrentLocationPusher.run(CurrentLocationPusher.java:60)
at java.lang.Thread.run(Thread.java:818)
This is my appLocationService
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 50;
private static final long MIN_TIME_FOR_UPDATE = 1000*60*2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
This is the code I use to push the location after getting the location from the LocationManager.
public class CurrentLocationPusher implements Runnable {
private static CurrentLocationPusher _singleInstance;
private CurrentLocationPusher() {
this.apiClient = ApiClient.getInstance();
this.appLocationService = new AppLocationService(appContext);
this.runningThread = new Thread(this);
}
public static CurrentLocationPusher getInstance() {
if (_singleInstance == null)
synchronized (CurrentLocationPusher.class) {
if (_singleInstance == null)
_singleInstance = new CurrentLocationPusher();
}
return _singleInstance;
}
private boolean isStopThread = false;
public static final long ONE_MINUTE = 60 * 1000;
private static Context appContext;
private AppLocationService appLocationService;
private ApiClient apiClient;
private Thread runningThread;
public static void init(Context applicationContext) {
appContext = applicationContext;
}
#Override
public void run() {
Location location = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
while (!isStopThread) {
try {
if (location != null)
if (CommonUtils.isActiveToInternet(appContext))
apiClient.getApi(appContext).pushLocation(String.valueOf(location.getLatitude()),
String.valueOf(location.getLongitude()),String.valueOf(System.currentTimeMillis()),
String.valueOf(location.getAccuracy()));
Thread.sleep(ONE_MINUTE);
} catch (InterruptedException e) {
} catch (Exception e) {
Log.e(PickingoConstant.TAG, "error" + e.getMessage());
}
}
}
public void startPushingLocation() {
if (this.runningThread.getState() == Thread.State.NEW) {
runningThread.start();
isStopThread = false;
} else if (this.runningThread.getState() == Thread.State.TERMINATED) {
(runningThread = new Thread(this)).start();
isStopThread = false;
} else if (this.runningThread.getState() == Thread.State.RUNNABLE) {
return;
}
}
public void stopPushingLocation() {
isStopThread = true;
}
}
I am getting error at the following line in CurrentLocationPusher
.getLocation(LocationManager.GPS_PROVIDER);
If someone could give a hint or some assistance I would really appreciate it. Thanks in advance !!
As pointed out by Michael adding this code at starting of my run() method worked.
if (Looper.myLooper() == null) {
Looper.prepare();
}
I am using google fused location api but still its showing high battery use. I am developing an app where I need to fetch user current location after that I don't need the fetch the location. Am an fetching the current location as below
public class MyLocationManager implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener {
private static MyLocationManager locationManager;
private static LocationClient locationclient;
public static final int LAT_KNOW_NLOCATION = 1005;
public static final int CURRENT_LOCATION = 1006;
public static final int CRON_LOCATION_UPDATE = 1007;
private static String LOCATION_CLIENT_NOT_FOUND_MESSAGE = "Error... Location client not found!";
private static Context context;
private static Activity currentActivity;
private static ProgressDialog progressDialog;
private static ILocationUpdator iLocationUpdator;
private static final int UPDATE_INTERVAL = 1000 * 30;
private static LocationManager androidLocationManager;
private static int CURRENTLY_LOOKING_FOR = 0;
private MyLocationManager(Context context) {
locationclient = new LocationClient(context, this, this);
MyLocationManager.context = context;
androidLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
public static synchronized MyLocationManager getLocationManagerInstance(Context context, ILocationUpdator iLocationUpdator, Activity activity) {
currentActivity = activity;
if (locationManager == null) {
locationManager = new MyLocationManager(context);
}
progressDialog = new ProgressDialog(currentActivity);
progressDialog.setCancelable(false);
progressDialog.setMessage("Please wait looking for current location");
MyLocationManager.iLocationUpdator = iLocationUpdator;
return locationManager;
}
public void getCurrentLocation() {
CURRENTLY_LOOKING_FOR = MyLocationManager.CURRENT_LOCATION;
callForLocationUpdate();
}
public void getlastKnownLocation() {
CURRENTLY_LOOKING_FOR = MyLocationManager.LAT_KNOW_NLOCATION;
callForLocationUpdate();
}
public void getCronLocationUpdate() {
CURRENTLY_LOOKING_FOR = MyLocationManager.CRON_LOCATION_UPDATE;
callForLocationUpdate();
}
private void callForLocationUpdate() {
System.out.println("callForLocationUpdate " + isProviderEnabled());
if (isProviderEnabled()) {
getReliventLocation(CURRENTLY_LOOKING_FOR);
}
else {
DialogUtility.showCallbackMessage("Please turn on GPS/Location service.", currentActivity, new AlertDialogCallBack() {
#Override
public void onSubmit() {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
currentActivity.startActivity(intent);
}
#Override
public void onCancel() {
}
#Override
public void onSubmitWithEditText(String text) {
}
});
}
}
private boolean isProviderEnabled() {
boolean gps_enabled = androidLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean network_enabled = androidLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gps_enabled && network_enabled) {
return true;
}
else {
return false;
}
}
private void getReliventLocation(int lookingFor) {
Location location = null;
if (locationclient != null) {
currentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.show();
}
});
if (!locationclient.isConnected()) {
locationclient.connect();
}
else {
LocationRequest locationrequest = LocationRequest.create();
locationrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
sendLocationUpdate(location, this);
}
};
switch (lookingFor) {
case MyLocationManager.LAT_KNOW_NLOCATION:
location = locationclient.getLastLocation();
sendLocationUpdate(location, null);
break;
case MyLocationManager.CURRENT_LOCATION:
locationrequest.setInterval(UPDATE_INTERVAL);
locationclient.requestLocationUpdates(locationrequest, locationListener);
break;
case MyLocationManager.CRON_LOCATION_UPDATE:
Intent mIntentService = new Intent(context, LocationService.class);
PendingIntent mPendingIntent = PendingIntent.getService(context, 1, mIntentService, 0);
locationrequest.setInterval(100);
locationclient.requestLocationUpdates(locationrequest, mPendingIntent);
break;
}
}
}
else {
showErrorMessage(LOCATION_CLIENT_NOT_FOUND_MESSAGE);
}
}
private void sendLocationUpdate(Location location, LocationListener locationListener) {
if (location != null) {
double lat = location.getLatitude();
double lon = location.getLongitude();
iLocationUpdator.getLocation(new LatLng(lat, lon), 0, "success..");
}
else {
iLocationUpdator.getLocation(new LatLng(0.0, 0.0), 1, "Some error occured..");
}
if (progressDialog != null) {
progressDialog.dismiss();
}
if (CURRENTLY_LOOKING_FOR == MyLocationManager.CURRENT_LOCATION) {
locationclient.removeLocationUpdates(locationListener);
}
}
private static void showErrorMessage(String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (iLocationUpdator != null)
iLocationUpdator.getLocation(new LatLng(0.0, 0.0), 1, "Connection Result...Error!");
if (progressDialog != null) {
progressDialog.dismiss();
}
}
#Override
public void onConnected(Bundle bundle) {
getReliventLocation(CURRENTLY_LOOKING_FOR);
}
#Override
public void onDisconnected() {
if (iLocationUpdator != null)
iLocationUpdator.getLocation(new LatLng(0.0, 0.0), 1, "Connection Disconnected...Error!");
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
Please point out what I am doing wrong.
I am unfamiliar with android location services, however I think you would be able to diagnose your battery usage using this free tool provided by AT&T.
Application Resource Optimizer:
https://developer.att.com/application-resource-optimizer
It looks like you might be polling for current location updates, each of these will effect battery life. ATT ARO can help identify this.
I have the below location listner to get the users current location. I wait for aproximately 45 seconds before giving up, using both network and GPS. The problem is that sometimes (about 15% of the time) I get a null position even after 45 seconds. I have found no patterns on to when this happens. Can anyone shed some light on what might be happening?
public class MyLocationListener implements LocationListener {
private static final float DELTA_ACURACIDADE = 30;
public static final long DEFAULT_TIME_UPDATES = 0;
public static final float DEFAULT_DISTANCE_UPDATES = 0;
private static final long TIME_CONSIDERED_OLD_LOCATION = 1000 * 150;
private Location location;
#Override
public void onLocationChanged(Location newLocation) {
if (newLocation != null && newLocation.getLatitude() != 0.0d && newLocation.getLongitude() != 0.0d) {
boolean isOk = false;
if (this.location == null) {
this.location = newLocation;
} else {
long deltaTime = newLocation.getTime() - this.location.getTime();
boolean isNewer = deltaTempo > 0;
boolean isAlotNewer = deltaTempo > TIME_CONSIDERED_OLD_LOCATION;
int deltaAcuracidade = (int) (this.location.getAccuracy() - newLocation.getAccuracy());
boolean isEqualOrMoreAccurate = deltaAcuracidade >= DELTA_ACURACIDADE;
if ((isNewer && isEqualOrMoreAccurate) || isAlotNewer) {
aceitarNovaLocation = true;
}
if (aceitarNovaLocation) {
this.location = newLocation;
}
}
}
}
public Location getLocation() {
return this.location;
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
public class checkInActivity extends Activity {
private long WAIT_FOR_LOCATION = 1000 * 40;
private Location roteiroLocation;
private MyLocationListener locationListner;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
this.locationListner = new MyLocationListener();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MyLocationListener.DEFAULT_TIME_UPDATES,
MyLocationListener.DEFAULT_DISTANCE_UPDATES, this.locationListner);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MyLocationListener.DEFAULT_TIME_UPDATES, MyLocationListener.DEFAULT_DISTANCE_UPDATES,
this.locationListner);
}
protected void processLocation() {
new AsyncTask<Void, Void, Void>() {
private boolean wasLocationAccepted = false;
private ProgressDialog dialog = new ProgressDialog(checkInActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("message");
this.dialog.setCancelable(false);
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
Long t = Calendar.getInstance().getTimeInMillis();
Location location = null;
while (Calendar.getInstance().getTimeInMillis() - t < WAIT_FOR_LOCATION) {
location = locationListner.getLocation();
if (location != null && location.getAccuracy() < MIN_ACCURACY_LOCATION
&& location.distanceTo(place) < MIN_ACCURACY_LOCATION) {
wasLocationAccepted = true;
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
locationManager.removeUpdates(locationListner);
if (this.dialog.isShowing(){
this.dialog.dismiss();
}
SigoMobileHelper.performOnBackgroundThread(runnable);
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(TAG, "AsyncTask.onPostExecute");
finish();
}
}.execute();
}
#Override
protected void onStart() {
processLocation();
super.onStart();
}
}
Your code is OK.
You're not getting location, because there can be low GPS signal or no answer from satellite and app is unable to download location.
I am using this link for location service and it works
Now I want to create BackgroundService that make calls to a function that gets location after every 5 minutes.
I think I need to use Timer for this, please tell me how to manage this 5 minutes gap in between this location class gets called.
public class LocationService extends Service {
private Timer timer;
private long UPDATE_INTERVAL ;
public static final String Stub = null;
LocationManager mlocmag;
LocationListener mlocList ;
private double lat,longn;
#Override
public void onCreate() {
super.onCreate();
webService = new WebService();
mlocmag = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocList = new MyLocationList();
Location loc = mlocmag.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc == null) {
loc = mlocmag.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
timer = new Timer(); // location.
UpdateWithNewLocation(loc); // This method is used to get updated
mlocmag.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,mlocList);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
if (timer != null) {
timer.cancel();
}
mlocmag.removeUpdates(mlocList);
}
#Override
public boolean stopService(Intent name) {
return super.stopService(name);
}
private void UpdateWithNewLocation(final Location loc) {
final SharedPreferences prefs = getSharedPreferences(Const.COMMON_SHARED, Context.MODE_PRIVATE);
userId = prefs.getString(Const.COMMON_USERID, null);
gps = prefs.getInt(Const.COMMON_GPS, 0);
UPDATE_INTERVAL = 500000;
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (loc != null) {
final double latitude = loc.getLatitude(); // Updated lat
final double longitude = loc.getLongitude(); // Updated long
String response = null ;
if (lat != latitude || longn != longitude ) {
response = webService.updateLatandLong(userId, latitude, longitude);
lat = latitude;
longn = longitude;
}
}
else {
String latLongStr = "No lat and longitude found";
}
}
}, 0, UPDATE_INTERVAL);
}
public class MyLocationList implements LocationListener {
public void onLocationChanged(Location arg0) {
UpdateWithNewLocation(arg0);
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "GPS Disable ",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "GPS enabled",
Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
use This:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
//your code to get lat long
}
}, 0, 500000);