4

可能重复:
检测android中的速度

我正在进入 Android 开发,我想开始搞乱 GPS 和捕捉速度。有没有一种方法可以让我使用 GPS 轻松捕捉速度并在屏幕上显示该速度?我可以使用任何简单的框架或内置函数吗?

4

2 回答 2

29

您将不得不使用LocationManager,它用于通过 GPS 获取用户位置,返回的 GPS 数据包括速度。您将不得不使用LocationListeneronLocationChanged(Location location)的功能。

要获得速度,您需要执行以下操作:

int speed = location.getSpeed();

以 m/s 为单位,如果您需要将其转换为 km/h,请使用:

int speed=(int) ((location.getSpeed()*3600)/1000);

如果您需要将其转换为 mph,请使用以下命令:

int speed=(int) (location.getSpeed()*2.2369);
于 2012-07-24T06:27:55.727 回答
2

我认为有两种方法可以实现这一目标:

首先,如果你在android中引用Location类,你会发现它有一个名为的方法 getSpeed。它说:

Returns the speed of the device over ground in meters/second. 
If hasSpeed() is false, 0.0f is returned. 

所以,你可以写,像这样

if (locationObj.hasSpeed()) {
    float speed = locationObj.getSpeed();
    // process data
} else {
    // Speed information not available.
}

其次,您可以跟踪 gps 位置更新,以便您存储该更新发生的先前位置和时间。现在,每次有新的更新时,您都可以使用类的distanceTo方法找到行进的距离Location。因此,要知道当前速度,您可以使用公式,distance travelled / time difference between the updates

于 2012-07-24T06:26:11.993 回答