I'm trying to resolve a small problem:
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000, 0, mLocationListener);
So I assumed that mLocationListener should wait for 2 mainutes before calling it's onLocationChanged method. However, the method is called right after I send geo fix updates to emulator, every time I do it. Did I misunderstand the android developers guide, and do I have to to use timers or anything similar for organizing update rate I need?
I think you're confused as to how the updates work. You can't tell the GPS hardware to send you an update at a specific time in the future. You can only give it guidelines on when you'd like to be updated. With the minTime you're saying you don't want updates more frequently than every 2 minutes, but then you're using a min distance of zero when you setup your listener. That tells the underlying GPS driver to send you an update whenever the location changes distance by any amount. That's why you're getting updates immediately when you send in a new point.
Well after some research and meditation :) I've come up with something like this: a service that can run in two modes (depending on the listenPeriod variable): 1) simply process coordinates once and shut self down afterwards (listenPeriod=0); 2) and process coordinates with specified rate (listenPeriod>0) until the service will be shut down.
GPSTracer.listenPeriod = 120000;
comp = new ComponentName(context.getPackageName(), GPSTracer.class.getName());
GPSTracer.iGPSTracer = new Intent(context, GPSTracer.class.getClass());
GPSTracer.iGPSTracer.setComponent(comp);
service=context.startService(GPSTracer.iGPSTracer);
So I have to initialize the listenPeriod variable before I start my service. And the service part looks like this:
public class GPSTracer extends Service {
public static Intent iGPSTracer;
public static volatile Location mLocation = null;
public static volatile LocationListener mLocationListener = null;
public static LocationManager mLocationManager = null;
public static long listenPeriod = 0;
Timer mTimer = null;
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
if(msg.arg1 == 1)
{
if(GPSTracer.mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
GPSTracer.mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000, 100, GPSTracer.mLocationListener);
}
else if(GPSTracer.mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
GPSTracer.mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 120000, 100, GPSTracer.mLocationListener);
}
else
{
List<NameValuePair> gpsData = new ArrayList<NameValuePair>();
gpsData.add(new BasicNameValuePair("Error", "No location provider"));
stopSelf();
}
}
else if(msg.arg1 == 0)
{
GPSTracer.mLocationManager.removeUpdates(GPSTracer.mLocationListener);
}
};
};
TimerTask selfStopTask = new TimerTask() {
#Override
public void run() {
stopSelf();
}
};
TimerTask mTimerTask = new TimerTask() {
#Override
public void run() {
//Message mMessage = new Message();
//mHandler.sendMessage(mMessage);
if(mLocation == null)
{
mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(mLocation == null)
{
mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
if(mLocation != null)
{
List<NameValuePair> gpsData = new ArrayList<NameValuePair>();
gpsData.add(new BasicNameValuePair("Latitude", (new Double(mLocation.getLatitude())).toString()));
gpsData.add(new BasicNameValuePair("Longitude", (new Double(mLocation.getLongitude())).toString()));
gpsData.add(new BasicNameValuePair("Provider", mLocation.getProvider()));
}
else
{
List<NameValuePair> gpsData = new ArrayList<NameValuePair>();
gpsData.add(new BasicNameValuePair("Error", "Location is unknown"));
}
}
};
#Override
public void onCreate() {
mLocationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
mLocationListener = new GPSListener(getApplicationContext());
};
#Override
public void onStart(Intent intent, int startId) {
Message mMessage = new Message();
mMessage.arg1 = 1;
mHandler.sendMessage(mMessage);
if(listenPeriod == 0)
{
mTimer = new Timer("GPSTask");
mTimer.schedule(mTimerTask, 0);
mTimer.schedule(selfStopTask, 60000);
}
else if(listenPeriod>0)
{
mTimer = new Timer("GPSTask");
mTimer.schedule(mTimerTask, 0, listenPeriod);
}
};
#Override
public void onDestroy() {
Message mMessage = new Message();
mMessage.arg1 = 0;
mHandler.sendMessage(mMessage);
//GPSTracer.mLocationManager.removeUpdates(GPSTracer.mLocationListener);
iGPSTracer = null;
mTimer.cancel();
mTimerTask.cancel();
mTimer = null;
mTimerTask = null;
mLocationListener = null;
mLocationManager = null;
};
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
and implementation of LocationListener:
public class GPSListener implements LocationListener{
Context context;
public GPSListener(Context appContext) {
context = appContext;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
//GPSTracer.mLocationManager.removeUpdates(GPSTracer.mLocationListener);
GPSTracer.mLocation = location;
}
}
I hope it will help someone...)
P.S. thanks to Dave MacLean and EboMike!; and feel free to ask questions;)
Related
I try to make a locationing service but somehow i cant make it work.
Lat and Lng are always NULL.
I had some exceptions on locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener); so i put it inside a run() method, now exception is gone. What could be the problem?
So what is the solution to make a locationing service work?
Code:
public class LocationService extends Service {
private Timer timer = new Timer();
private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();
private String latitude;
private String longitude;
private String providerToSend;
Messenger messenger;
Timer t = new Timer();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public void onCreate() {
super.onCreate();
locListener = new MyLocationListener();
locationProviderInit();
startService();
}
#Override
public void onDestroy() {
super.onDestroy();
shutdownService();
}
private void startService() {
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
String token = new SharedPreffer(this).loadPreferences("token");
Log.d("Debug - token: ", "Van Token: " + token);
t.schedule(new TimerTask() {
#Override
public void run() {
locationProviderInit();
if (latitude != null && longitude != null) {
Log.d("Debug - lat: ", latitude);
Log.d("Debug - lng: ", longitude);
} else {
Log.d("Debug - lat and lng are: ", "NULL");
}
}
}, 0, 5000);
}
private void locationProviderInit() {
new Runnable() {
#Override
public void run() {
try {
boolean gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
providerToSend = LocationManager.GPS_PROVIDER;
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
providerToSend = LocationManager.NETWORK_PROVIDER;
}
} catch (Exception e) {
Log.d("Debug", e.toString());
}
}
};
}
class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
if (location != null) {
longitude = Double.toString(location.getLongitude());
latitude = Double.toString(location.getLatitude());
}
}
public void onProviderDisabled(String arg) {
}
public void onProviderEnabled(String arg) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
private void shutdownService() {
if (timer != null)
timer.cancel();
Log.i(getClass().getSimpleName(), "Timer stopped!!!");
}
}
you don't execute the Runnable in locationProviderInit...
Have you tried to put a debug message inside the method run() within the Runnable object, and see if it has been ever executed?
Defining a Runnable instance without using it ,e.g. within a thread, won't work.
Here are few examples of open source GPS logging services that you can use as guide.
GPSLoggerService
GPSLoggingService
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);
What I'm attempting to do is when receiving a c2dm message, start a service that asks for location for 'x' amount of time and then hands that location off to our server. The c2dm message starts the service correctly, and the GPS location turns on, but it never updates. It just sits there for the length of time I specify (currently 12 seconds) in the thread and does nothing. I'm using the exact same code somewhere else in my app (not as a service) and it works perfectly. What am I doing wrong?
This starts the service when receiving a c2dm message.
context.startService(new Intent(context, ServicePingLocation.class));
This is the code for the service itself. All that ever gets called, is "onCreate" and "onStart".
public class ServicePingLocation extends Service implements LocationListener {
private final String DEBUG_TAG = "[GPS Ping]";
private boolean xmlSuccessful = false;
private boolean locationTimeExpired = false;
private LocationManager lm;
private double latitude;
private double longitude;
private double accuracy;
#Override
public void onLocationChanged(Location location) {
Log.d(DEBUG_TAG, "onLocationChanged");
latitude = location.getLatitude();
longitude = location.getLongitude();
accuracy = location.getAccuracy();
}
#Override
public void onProviderDisabled(String provider) {
Log.d(DEBUG_TAG, "onProviderDisabled");
Toast.makeText(
getApplicationContext(),
"Attempted to ping your location, and GPS was disabled.",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Log.d(DEBUG_TAG, "onProviderEnabled");
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10f, this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(DEBUG_TAG, "onStatusChanged");
}
#Override
public void onCreate() {
Log.d(DEBUG_TAG, "onCreate");
}
#Override
public void onDestroy() {
Log.d(DEBUG_TAG, "onDestroy");
}
#Override
public IBinder onBind(Intent intent) {
Log.d(DEBUG_TAG, "onBind");
return null;
}
#Override
public void onStart(Intent intent, int startid) {
Log.d(DEBUG_TAG, "onStart");
lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10f, this);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000,
300f, this);
Log.d(DEBUG_TAG, lm.toString());
new SubmitLocationTask(ServicePingLocation.this).execute();
}
private void locationTimer() {
new Handler().postDelayed(new Runnable() {
// #Override
#Override
public void run() {
locationTimeExpired = true;
}
}, 12000);
}
private class SubmitLocationTask extends AsyncTask<String, Void, Boolean> {
/** application context. */
private Context context;
private Service service;
public SubmitLocationTask(Service service) {
this.service = service;
context = service;
}
#Override
protected void onPreExecute() {
locationTimer(); // Start 12 second timer
}
#Override
protected void onPostExecute(final Boolean success) {
if (success && xmlSuccessful) {
lm.removeUpdates(ServicePingLocation.this);
onDestroy();
} else {
if (!GlobalsUtil.DEBUG_ERROR_MSG.equals(""))
Toast.makeText(getBaseContext(),
GlobalsUtil.DEBUG_ERROR_MSG, Toast.LENGTH_SHORT)
.show();
GlobalsUtil.DEBUG_ERROR_MSG = "";
}
}
#Override
protected Boolean doInBackground(final String... args) {
try {
DateFormat df = null;
df = new SimpleDateFormat("M/d/yy h:mm a");
Date todaysDate = new Date();// get current date time with
// Date()
String currentDateTime = df.format(todaysDate);
while ((accuracy > 100f || accuracy == 0.0)
&& !locationTimeExpired) {
// We just want it to sit here and wait.
}
return xmlSuccessful = SendToServerUtil.submitGPSPing(
0, longitude,
latitude, accuracy, currentDateTime);
} catch (Exception e) {
return false;
}
}
}
}
[Edit]
Fixed the issue I was having. Code was actually working. I added the network provider, adjusted the onDestroy() method to stop the service, and tweaked the time used to grab GPS signal.
Thank you for the advice, CommonsWare
Fixed the issue I was having. Code was actually working. I added the network provider, adjusted the onDestroy() method to stop the service, and tweaked the time used to grab GPS signal.
Thank you for the advice, CommonsWare
I have created a service running in background which saves gps points on the phone db.
I have created the service using also a broadcast listener to the on-off screen, because when the screen is off I want to save points every 5 minutes, when the screen is on I want to save them every minute.
Yesterday I tried the app on my cell phone, and, in 10h it saved more than 12000 points!!!!
After looked deeply I found out that the same point is saved in more copies, from 0 to over 250, and also that the frequency of point saving (withouth the copies) is one every 36 seconds less or more...
Here is the code of the service:
public class MonitorGpsService extends Service {
private String sharedPreferences= "Settings";
private String viaggio_in_corso = "viaggio_in_corso";
private long id;
private boolean firstStart = true;
private int minTime = 300000; //(5 minuti)
private static String startScan = "dateStart";
private GpsListener gpsListener;
private BroadcastReceiver mReceiver;
private Travel travel;
#Override
public void onCreate() {
id = this.getSharedPreferences(sharedPreferences, MODE_PRIVATE).getLong(viaggio_in_corso, -1);
travel = new Travel(this);
travel.load(id);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
gpsListener = new GpsListener(travel);
gpsListener.startListener(minTime,0);
this.getSharedPreferences(sharedPreferences, MODE_PRIVATE).edit().putLong(startScan, DateManipulation.getCurrentTimeMs()).commit();
this.getSharedPreferences(sharedPreferences, MODE_PRIVATE).edit().putBoolean("service", true).commit();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
this.getSharedPreferences(sharedPreferences, MODE_PRIVATE).edit().putBoolean("service", false).commit();
gpsListener.stopListener();
unregisterReceiver(mReceiver);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if ((flags & START_FLAG_RETRY) == 0) {
// TODO If it’s a restart, do something.
}
else {
// TODO Alternative background process.
}
boolean screenOn;
try {
screenOn = intent.getBooleanExtra("screen_state", false);
} catch (NullPointerException e) { screenOn = false; }
if ((!screenOn) && (!firstStart)) {
gpsListener.stopListener();
gpsListener.startListener(60000, 0);
this.getSharedPreferences(sharedPreferences, MODE_PRIVATE).edit().putLong(startScan, DateManipulation.getCurrentTimeMs()).commit();
}
else if (!firstStart) {
gpsListener.startListener(minTime, 0);
MediaScan mediaScan = new MediaScan(travel);
try {
mediaScan.scanImages();
} catch (URISyntaxException e) {e.printStackTrace();}
}
firstStart = false;
return Service.START_STICKY;
}
Here is the code of the gpsListener:
public class GpsListener {
private LocationManager locationManager;
private String bestProvider;
private LocationListener myLocationListener = null;
private String serviceString = Context.LOCATION_SERVICE;
private Travel travel;
public GpsListener(Travel travel) {
locationManager = (LocationManager)travel.getContext().getSystemService(serviceString);
bestProvider = locationManager.getBestProvider(setCriteria(), true);
this.travel=travel;
}
public void stopListener() {
locationManager.removeUpdates(myLocationListener);
}
public void startListener(int time, int space) {
myLocationListener = new LocationListener() {
Location location1 = null;
public void onLocationChanged(Location location) {
if ((location != null) && (location != location1)) {
try {
savePosition(location);
location1 = location;
} catch (SQLException e) { e.printStackTrace(); }
}
}
public void onProviderDisabled(String provider){
// Update application if provider disabled.
}
public void onProviderEnabled(String provider){
// Update application if provider enabled.
}
public void onStatusChanged(String provider, int status, Bundle extras){
// Update application if provider hardware status changed.
}
};
locationManager.requestLocationUpdates(bestProvider, time, space, myLocationListener);
}
// salva la posizione passatagli nel db
private void savePosition(Location location) throws SQLException {
Points point = new Points();
point.setLatitude((int) (location.getLatitude() * 1E6));
point.setLongitude((int) (location.getLongitude() * 1E6));
point.setDataRilevamento(DateManipulation.getCurrentTimeMs());
travel.addPoints(point);
}
// criteri globali per la gestione del gps
private Criteria setCriteria() {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(false);
return criteria;
}
}
And here i the code for the ScreenReceiver
public class ScreenReceiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
Intent i = new Intent(context, MonitorGpsService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
Thank you for the help.
yeah this is normal I think Ive made an app which saved the position every 100m and 20 seconds the result was I had 5-8 points after the 100m and 20 seconds that was on Android 1.6
just check the distance from the last point and compare it to a min distance variable if its greater then save it
there is a function for distance calculation in the Android api .
EDIT:
its the
float distanceTo(Location dest) function of a location instance
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();
}
}