我在使用 Google Play Location API 的时候也遇到了这个问题,希望对你有帮助。
返回 0 是因为您的设备无法锁定 GPS,或无法连接到 GPS。
我尝试使用较旧的 lenovo 设备获取速度,但它返回 0,因为它无法锁定 gps。
我尝试使用三星 Galaxy nexus,它返回了我的速度(具有更好的 GPS 传感器)。
您手机中的 GPS 传感器可能不好,或者您位于 GPS 信号较弱的区域,例如房屋或建筑物内。
如果 location.hasSpeed 为 false,我所做的是计算速度,如果 location.hasSpeed 为 true,则使用 location.getSpeed。
我也尝试过使用活动识别来在计算时获得更好的速度准确度。
//Computation for speed
cur_time = System.currentTimeMillis() / 1000L;
if (location.hasSpeed()) {
loc_Speed = location.getSpeed();
//counter goes back to 0
count_OnFoot = 0;
Toast.makeText(getBaseContext(), "has speed", Toast.LENGTH_SHORT).show();
} else {
float[] result = new float[1];
location.distanceBetween(prev_latitude, prev_longitude,
loc_Latitude, loc_Longitude,
result);
float loc_distance = result[0];
//speed if location.getSpeed is null
loc_Speed = loc_distance/(cur_time - prev_time);
//if activity type is on foot
//estimate AVE_RUNNING_SPEED = 3m/s
if (act_ActivityType.equals(ActivityRecognitionService.ACT_ON_FOOT) && loc_Speed > AVE_RUNNING_SPEED) {
count_OnFoot++;
if (count_OnFoot < 2) {
Toast.makeText(getBaseContext(), "on foot and 1st > 3m/s", Toast.LENGTH_SHORT).show();
/*
* Since the speed is more than
* the average running speed,we will
* assume that its not a correct value
* and a fault that it detected a very far signal from the previous one.
* (This happens sometimes)
* We will assign the previous speed
* as its current speed.
*/
loc_Speed = prev_Speed;
} else {
Toast.makeText(getBaseContext(), "on foot and TWICE > 3m/s in a row", Toast.LENGTH_SHORT).show();
/*
* Do Nothing
* loc_Speed is equals the computed speed
* if it happens twice or more in a row.
* We will assume that its running fast.
*/
}
}else {
count_OnFoot = 0;
}
}
prev_Speed = loc_Speed;
/*
* If more than 60% sure that its still.
*
* Let your speed and direction be 0
* latitude and longitude should not change
*/
if (act_ActivityType.equals(ActivityRecognitionService.ACT_STILL)) {
loc_Speed = 0;
loc_Direction = 0;
if (prev_latitude != 0 && prev_longitude != 0) {
loc_Latitude = prev_latitude;
loc_Longitude = prev_longitude;
}
}
prev_time = cur_time;
prev_latitude = loc_Latitude;
prev_longitude = loc_Longitude;
//Note: My activity type will return on foot or still if its more than 60% sure
//otherwise null.