import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;
public class LocationService extends Service {
private LocationDatabaseHelper mLocationDatabaseHelper;
private LocationModel mLocationModel;
private Date mDate;
private Handler mHandler = new Handler();
private Timer mTimer = null;
private int mCount = 0;
public static final long NOTIFY_INTERVAL = 30 * 1000;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
// cancel if already existed
if (mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
mLocationModel = LocationModel.getInstance();
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}
@Override
public void onDestroy() {
mTimer.cancel();
}
private class TimeDisplayTimerTask extends TimerTask implements LocationListener {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
//I send message to draw map here
sendMessage();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
TimeDisplayTimerTask.this);
}
});
}
@Override
public void onLocationChanged(Location location) {
// I get location and do work here
}
@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
}
}
private void sendMessage() {
Intent intent = new Intent("my-event");
intent.putExtra("message", "data");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
What I want is to get user location after every 30 seconds but this code does not work as I expected. It gets location very fast (I think every second).
I tried to get location this way because it can get my current location immediately after I start my app.I have tried getLastKnowLocation before, but it give me the last known location which is very far from where I am.
Please show me how fix this.Thank you!