Values are not updating in thread - android

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().

Related

Android LocationListner cannot find my location

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.

How to get location after every 5 minutes?

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);

android: locationManager onLocationChanged does not update Activity

I need your help.
I have a activity that get every 5 min the current lat lon gps = new GpsData(StartActivity.this);. That works fine! But when I left a county and the activity refresh. Then I do not get the current lon lat. I dont know why.
Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
btnShowLocation = (Button) findViewById(R.id.report_btn);
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(StartActivity.this, ReportActivity.class);
startActivity(intent);
finish();
}
});
}
#Override
public void onResume() {
super.onResume();
autoUpdate = new Timer();
autoUpdate.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//start GPS
gps = new GpsData(StartActivity.this);
//start json download
new task().execute();
}
});
}
}, 0, 300000); // updates each 5 min
}
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(StartActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Status Update...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
//get Location Data
double latitude = gps.latitude;
double longitude = gps.longitude;
String mlat = String.valueOf(latitude);
String mlon = String.valueOf(longitude);
//if (gps.latitude != 0.0) {
JSONObject json = jsonFunctions.getJSONfromURL("http://myurl);
Here is my GpsData
public class GpsData extends Service implements LocationListener {
public GpsData(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
// Get the location manager
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
return null;
}
/* Request updates at startup */
protected void onStart() {
}
/* Remove the locationlistener updates when Activity is paused */
protected void onPause() {
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
time = location.getTime();
speed = location.getSpeed();
}
It is simple: I want every 5 min the current lat lon and refresh the List view with the current data from the current county... How can I do this?
Change this
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
to
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300000, 0, this);

Can't find GPS Location

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!

Android: requestLocationUpdates throws exception

I'm trying to get periodically the user position via GPS in Android and send the data to a remote DB, but I get the exception: Can't create handler inside thread that has not called Looper.prepare().
The method that retrieves the position is in a remote service, and it's pretty basic:
private void dumpLocationLog() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Looper.myLooper().prepare();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f ,this);
retrieveUserId();
sendData(user_id);
}
I tried calling Looper.myLooper().prepare(); but it still does not work.
I guess I have to implement a Looper here but I don't know how as I'm still pretty newbie with Android.
This is the full code of my service:
public class LocationLoggingService extends Service {
String latString, lngString;
Double latitude, longitude;
Date durationDate;
String user_id;
public String username;
private Handler serviceHandler;
private Task myTask = new Task();
#Override
public IBinder onBind(Intent i) {
Log.d(getClass().getSimpleName(), "onBind()");
username = i.getStringExtra("username");
return myRemoteLocationServiceStub;
}
private IMyRemoteLocationLoggingService.Stub myRemoteLocationServiceStub = new IMyRemoteLocationLoggingService.Stub() {
public void dumpLocationLog() throws RemoteException {
LocationLoggingService.this.dumpLocationLog();
}
};
#Override
public void onCreate() {
super.onCreate();
Log.d(getClass().getSimpleName(), "onCreate()");
}
#Override
public void onDestroy() {
super.onDestroy();
serviceHandler.removeCallbacks(myTask);
serviceHandler = null;
Log.d(getClass().getSimpleName(), "onDestroy()");
}
#Override
public void onStart(Intent intent, int startId) {
username = intent.getStringExtra("username");
super.onStart(intent, startId);
serviceHandler = new Handler();
serviceHandler.postDelayed(myTask, 1000L);
Log.d(getClass().getSimpleName(), "onStart()");
}
class Task implements Runnable {
public void run() {
try {
myRemoteLocationServiceStub.dumpLocationLog();
} catch (RemoteException e) {
e.printStackTrace();
}
serviceHandler.postDelayed(this, 5000L);
Log.i(getClass().getSimpleName(), "Calling the dumpLocationLog");
}
}
public void retrieveUserId() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
"http://10.0.2.2/science/getUserId.php", postParameters);
String res = response.toString();
res = res.replaceAll("\\s+", "");
if (!res.equals("0")) {
Log.d(getClass().getSimpleName(),
"Successfully retrieved user_id");
user_id = res;
} else {
Log.d(getClass().getSimpleName(), "Error retrieving user_id");
}
} catch (Exception e) {
}
}
private void sendData(String user_id) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("user_id", user_id));
postParameters.add(new BasicNameValuePair("latitude", latString));
postParameters.add(new BasicNameValuePair("longitude", lngString));
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
"http://10.0.2.2/science/sendLocationData.php",
postParameters);
String res = response.toString();
res = res.replaceAll("\\s+", "");
if (res.equals("1")) {
Log.d(getClass().getSimpleName(), "Insertado en DB!");
} else {
Log.d(getClass().getSimpleName(), "Error insertando en la DB");
}
} catch (Exception e) {
}
}
LocationListener myLocationListener = new LocationListener () {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
android.os.Debug.waitForDebugger();
latitude = location.getLatitude();
longitude = location.getLongitude();
latString = Double.toString(latitude);
lngString = Double.toString(longitude);
Log.d("Location: ", getClass().getSimpleName());
Log.d(latString, getClass().getSimpleName());
Log.d(lngString, getClass().getSimpleName());
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void dumpLocationLog() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, myLocationListener);
retrieveUserId();
sendData(user_id);
}
public static String create_datestring(String timestring)
throws java.text.ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.US);
Date dt = null;
Calendar c = Calendar.getInstance();
try {
dt = sdf.parse("2011-03-01 17:55:15");
c.setTime(dt);
System.out.println(c.getTimeInMillis());
System.out.println(dt.toString());
} catch (ParseException e) {
System.err.println("There's an error in the Date!");
}
return dt.toString();
}
}
Thanks a lot in advance!
The proper way to use the message looper is described in its doc with a code sample here
Well finally the solution is:
Class LoggingService.java (this is my service):
private void dumpLocationLog() {
new DumpLocationLog(context, latString, lngString).start();
Log.d(latString, getClass().getSimpleName());
Log.d(lngString, getClass().getSimpleName());
retrieveUserId();
sendData(user_id);
}
Then in DumpLocationLog.java:
public class DumpLocationLog extends Thread {
LocationManager lm;
LocationHelper loc;
String latString, lngString = null;
public DumpLocationLog(Context context, String latString, String lngString) {
loc = new LocationHelper();
lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
public void run() {
Looper.prepare();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, loc);
Looper.loop();
}
}
Then finally the LocationHelper for the LocationListener interface:
public class LocationHelper implements LocationListener {
public String latString, lngString;
public Double latitude, longitude;
#Override
public void onLocationChanged(Location location) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
LocationLoggingService.latString = Double.toString(latitude);
LocationLoggingService.lngString = Double.toString(longitude);
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
It works like a charm but I have realized, that when listening for locations, it's creating threads non-stop and never closing the former ones; I mean that every time it checks for location, it creates a new thread and after X minutes, there are hundreds of threads.
Anybody knows why?
What I was suggesting you do was
class DumpLocationLog extends Thread
{
public void run()
{
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f ,/* FIXME this */);
retrieveUserId();
sendData(user_id);
}
}
Then, from wherever you had been calling dumpLocationLog(), use runOnUiThread(new DumpLocationLog()) instead.
You can use this approach:
class DumpLocationLog extends Thread
{
public void run()
{
Looper.prepare();
mLooper = Looper.myLooper();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f ,mLooper);
retrieveUserId();
sendData(user_id);
Looper.loop();
}
public void stop()
{
mLooper.quit();
}
}

Categories

Resources