我正在尝试制作一个Android应用程序,它以一定的间隔获取位置数据,例如: - 5秒,1分钟等。这是我的代码: -
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
if(loc!=null)
{
//Required Interval
tInterval =(minInterval*60*1000) + (secInterval)*1000 - 1000;
//The app also supports interval mode
RadioButton sel = (RadioButton) findViewById(mode.getCheckedRadioButtonId());
//Code for Manual Functionality
if(sel.getText().equals(MANUAL_RADIO))
{
Time t = new Time();
t.setToNow();
db.addLocationAtTime(loc, t);
Toast.makeText(getApplicationContext(), "Location Added to Database",Toast.LENGTH_SHORT).show();
locate.removeUpdates(this);
b.setText(MANUAL_BUTTON);
d.setEnabled(true);
}
//Code for Interval functionality
else if(sel.getText().equals(INTERVAL_RADIO))
{
//count is object of Countdown class which is a Thread object
if(count == null)
{
//t is a Time object
t.setToNow();
//SQLiteDatabase object for logging Location with Time
db.addLocationAtTime(loc, t);
Toast.makeText(getApplicationContext(), "Location Added to Database",Toast.LENGTH_SHORT).show();
count = new CountDown( tInterval);
count.start();
}
else if(count.getState().toString().equals("TERMINATED"))
{
t.setToNow();
db.addLocationAtTime(loc, t);
Toast.makeText(getApplicationContext(), "Location Added to Database",Toast.LENGTH_SHORT).show();
count = new CountDown(tInterval);
count.start();
}
}
}
}
以下是Countdown类的代码: - 此类用于将间隔添加到应用程序
public class CountDown extends Thread
{
long time;
public CountDown(long duration)
{
time = duration;
}
public void run()
{
long t1 = System.currentTimeMillis();
long t2 = 0;
do
{
t2 = System.currentTimeMillis();
}while(t2 - t1 < time);
}
}
问题是使用上面的代码我没有得到准确的间隔。我总是得到额外的1秒(因为我在公式中减去了1000),但这1秒并不总是发生。那么有人可以告诉我我做错了吗?
答案 0 :(得分:2)
查看LocationManager.requestLocationUpdates,只需在参数..
中传递您的时间间隔LocationManager mLocationManager = (LocationManager).getSystemService(mActivity.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, new GeoUpdateHandler());
答案 1 :(得分:1)
我认为您需要使用默认功能,无需使用Timer
<强> NETWORK_PROVIDER 强>
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0, networkLocationListener);
<强> GPS_PROVIDER 强>
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, gpsLocationListener);
在这里,
minTime(2nd field) => minimum time interval between location updates, in milliseconds
minDistance(3rd field) => minimum distance between location updates, in meters
答案 2 :(得分:0)
我认为requestLocationUpdates(...)方法的minTime参数根本不做任何事情。它似乎不会阻止基于距离的更新以较短的间隔进行,并且它肯定不会导致更新以指定的间隔出现,正如许多人似乎认为的那样。我在Android 2.3.6到4.0.4的设备上尝试过它。