I read a lot of questions here, but couldn't figure out what the problem is.
I am writing a field service application for Android. In one of the operations (MyActivity.java) I have two buttons: "Start" and "Stop".
When the field worker clicks on the start, I need to get his current location using GPS and send it to the server at certain intervals (let's say that it will be 5 minutes by default, here I set it to 20 seconds for testing). The client wants this to show how long workers spend time on traffic, traffic in my city (Istanbul) is a mess.
I have an AlarmManager in my activity, when the start button is pressed, the alarm is set by AlarmManager.setRepeating() to start the service (ServiceClass.java).
Intent intent = new Intent (MyActivity.this, ServiceClass.class); mPendingIntent = PendingIntent.getService(MyActivity.this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mAlarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 20*1000, mPendingIntent);
I cancel the alarm using the "Stop" button.
It works fine so far, Service begins. Its methods onCreate() , onStart() and onDestroy() . But I canβt find a place. I am not working on a real device, so I use DDMS to send places. But the application skips this step and prints the longitude and latitude of my location as Lon: 0 Lat: 0.
Here's the code inside the service:
public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Log.d("Testing", "Service got started, calling location updates:"); mLocationManager.requestSingleUpdate(mCriteria, mLocationListener, getMainLooper()); Log.i("TESTING LOCATION UPDATE: LOCATION:", "\nLat:" + mLatitude + " Lon:" + mLongitude); stopSelf(startId); Log.d("Testing", "Service Stopped!");
And finally, here is my LocationListener:
mLocationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { if(location != null){ mLatitude = location.getLatitude(); mLongitude = location.getLongitude(); Log.i("onLocationChanged(Location location)", "Lat:"+mLatitude + " Lon:" + mLongitude); }
I also caught my eye when I ran the code:
mLocationProvider = mLocationManager.getBestProvider(mCriteria, true); Log.i("BEST PROVIDER IS:", mLocationProvider);
It says BEST PROVIDER: gps. But this log inside onProviderEnabled () is never displayed in logcat.
@Override public void onProviderEnabled(String s) { Log.v("onProviderEnabled", "ENABLED"); }
Two things to add if I use:
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
it doesn't work either.
This works, and I can get LastKnownLocation:
Location lastKnown = mLocationManager.getLastKnownLocation( LocationManager.GPS_PROVIDER);
First of all, is this a good approach for this? If this is, please check what I am missing. If this is not the case, can you tell me how I can implement this better?
Thanks.:)