[英]Android make method run every X seconds (involves gps and server call)
I have a niche application that needs to send a server its location every few seconds. 我有一个利基应用程序,需要每隔几秒发送一个服务器的位置。 (Don't worry about a mobile phone's battery life). (不要担心手机的电池寿命)。 How would I make a thread or something execute every few seconds? 我如何每隔几秒钟创建一个线程或某个东西? I have a gpslistener but the name of its subclass is "onlocationchanged"
which seems to only want to provide information if the location changed, I will need an updated location sent to the server every time though on an interval that I define 我有一个gpslistener,但其子类的名称是"onlocationchanged"
,似乎只想提供信息,如果位置发生变化,我需要每次都发送到服务器的更新位置,但是我定义的间隔
How would I do this? 我该怎么做?
insight appreciated 洞察力赞赏
Place this in onCreate
of a service. 将其放在onCreate
服务中。
mTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// What you want to do goes here
}
}, 0, REFRESH_TIME);
REFRESH_TIME
is the frequency or time in milliseconds when the run
repeats itself. REFRESH_TIME
是run
重复自身的频率或时间(以毫秒为单位)。
You cannot just ask android for the current position. 你不能只是向android询问当前的位置。 GPS takes some time and may not be available. GPS需要一些时间,可能无法使用。 This is stated in this post . 这是在此规定后 。
What you can do is use a timer like the one mentioned by user500865, and then request the last known location like this 你可以做的是使用像user500865提到的计时器,然后请求像这样的最后一个已知位置
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 1, this);
Location l = null;
l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
You can keep track of the last location and do some logic if the new location is different or the same. 如果新位置不同或相同,您可以跟踪最后位置并执行一些逻辑。
The method requestLocationUpdates has the following parameters: requestLocationUpdates方法具有以下参数:
minTime -the minimum time interval for notifications, in milliseconds. minTime - 通知的最小时间间隔,以毫秒为单位。 This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value. 此字段仅用作节省电量的提示,位置更新之间的实际时间可能大于或小于此值。
minDistance -the minimum distance interval for notifications, in meters minDistance - 通知的最小距离间隔,以米为单位
Use these to customize how often you want to get a location update 使用这些来自定义您希望获得位置更新的频率
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.