Android make方法每X秒运行一次(涉及gps和服务器调用)
我有一个利基应用程序,需要每隔几秒向服务器发送一次其位置。 (不用担心手机的电池寿命)。我如何让线程或其他东西每隔几秒执行一次?我有一个 gpslistener,但它的子类的名称是 "onlocationchanged"
,它似乎只想在位置更改时提供信息,我需要每次都将更新的位置发送到服务器,尽管每隔一段时间我定义了
我该怎么做?
洞察力赞赏
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
How would I do this?
insight appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将其放置在服务的
onCreate
中。REFRESH_TIME
是运行
自身重复的频率或时间(以毫秒为单位)。Place this in
onCreate
of a service.REFRESH_TIME
is the frequency or time in milliseconds when therun
repeats itself.你不能只向 android 询问当前位置。 GPS 需要一些时间并且可能无法使用。这篇帖子中对此进行了说明。
您可以做的是使用像 user500865 提到的计时器,然后像这样请求最后一个已知位置。
您可以跟踪最后一个位置,并在新位置不同或相同时执行一些逻辑。
requestLocationUpdates 方法具有以下参数:
minTime - 通知的最小时间间隔,以毫秒为单位。该字段仅用作节省电量的提示,位置更新之间的实际时间可能大于或小于该值。
minDistance - 通知的最小距离间隔(以米为单位)
使用这些来自定义您想要获取位置更新的频率
You cannot just ask android for the current position. GPS takes some time and may not be available. 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
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:
minTime -the minimum time interval for notifications, in milliseconds. 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
Use these to customize how often you want to get a location update