why getSpeed() always return 0 on android

前端 未结 11 1268
半阙折子戏
半阙折子戏 2020-11-28 07:35

I need to get the speed and heading from the gps. However the only number i have from location.getSpeed() is 0 or sometimes not available. my code:

         


        
11条回答
  •  温柔的废话
    2020-11-28 08:10

    Based on other suggestions here I put together this code with comments to why:

    public static float getSpeedKmh(Location newLocation, Location previousLocation)
    {
        if(newLocation == null) throw new IllegalArgumentException("newLocation must not be null");
        float speed = -1.0f;
        if(newLocation.hasSpeed()) /* gps doppler speed at the current moment preferred */
        {
            speed = newLocation.getSpeed();
        }else /* may be wifi or celltower based location: compute AVERAGE speed since last fix */
        {
           if(previousLocation == null) throw new IllegalArgumentException("Cannot compute speed without previousLocation (was null)");
           if(previousLocation.getTime()==newLocation.getTime())
               throw new IllegalArgumentException("Cannot compute speed from same time locations!"); /* diff by zero protection */
           speed = newLocation.distanceTo(previousLocation) * 1000.0f /* time diff in millis so multiply by 1000 */
               / Math.abs(newLocation.getTime() - previousLocation.getTime()); /* Math abs: so you can even swap new and older location without effect */
        }
           return speed * 3.6f; /* m/s -> km/h */
    }
    

提交回复
热议问题