我在我的应用程序中使用 TimerTask 将当前 GPS 更新到服务器。我已经扩展了 TimerTask 并重写了 run 方法来做到这一点。我在屏幕上有一个停止计时器按钮,一旦单击它就应该停止计时器。但我的问题是,即使timerobject.cancel()
正在执行,但计时器仍在运行。
任何人都可以分享您对单击特定按钮时停止计时器的看法。下面是我为运行计时器任务而编写的代码。
PointMyLocation.java
public class PointMyLocation
{
private String log;
double longi;
double lati;
public String email, city;
private HttpServiceCommunication mHttpService;
// Default Constructor
public PointMyLocation(int value){
new LocationTracker(value).StopTimer();
}
public PointMyLocation(String email, String city)
{
this.email = email;
this.city = city;
new LocationTracker();
//mHttpService = new HttpServiceCommunication();
}
public boolean onClose()
{
Application.getApplication().requestBackground();
return false;
}
class LocationTracker extends TimerTask {
private double longitude, latitude;
private Timer timer;
private LocationProvider provider;
private BeaconingBean mBb;
int mTimeinterval;
Criteria cr;
public LocationTracker() {
cr= new Criteria();
this.run(); // Calling the run
}
public void run() {
timer = new Timer();
resetGPS();
//mTimeinterval = mBb.getmTimeInterval();
//System.out.println("Time Interval :" + mTimeinterval);
timer.schedule(this, 0, 150000);
}
public void StopTimer(){
// Terminates the timer
this.timer.cancel(); // Though this statement gets executed, the timer starts again
}
public void resetGPS()
{
try
{
provider = LocationProvider.getInstance(cr);
if(provider != null)
{
provider.setLocationListener(new MyLocationListener(), 3, -1, -1);
}
} catch(Exception e){ }
}
private class MyLocationListener implements LocationListener
{
public void locationUpdated(LocationProvider provider, Location location)
{
if(location != null && location.isValid())
{
QualifiedCoordinates qc = location.getQualifiedCoordinates();
try
{
lati = location.getQualifiedCoordinates().getLatitude();
System.out.println("latitude :: "+lati);
longi = location.getQualifiedCoordinates().getLongitude();
System.out.println("longitude ::"+longi);
System.out.println("Email :: " + email);
System.out.println("City ::" + city);
}
catch(Exception e)
{
}
}
}
public void providerStateChanged(LocationProvider provider, int newState)
{
//LocationTracker.this.resetGPS();
if(newState == LocationProvider.TEMPORARILY_UNAVAILABLE)
{
provider.reset();
provider.setLocationListener(null, 0, 0, -1);
}
}
}
}
}
非常感谢任何帮助