Android - Fused Location Provider API 卫星信息(计数、信号等)问题

Android - Fused Location Provider API issues with satellite information (count, signal, etc)

我正在做一个项目,我们试图跟踪设备的位置并保留数据以备后用。在谈论这个问题之前,我想提供一些背景知识。

通过搜索 StackExchange 和 Google 以及其他任何地方,我得出的结论是,使用 Fused Location API 几乎不可能获得有关卫星的信息(干得好 Google).

大多数人使用的方法是在 Fused 位置旁边实际使用 LocationManager 来获取 GPS 状态。我的第一个问题来了: 我们如何才能 100% 确定 LocationManager 提供的数字与 Fused Location 提供给我们的数字同步? Fused Location 是否在内部使用 Manager?

现在是问题。该应用程序正在使用 "always on" 粘性服务来获取位置。当没有卫星时,一切都按预期工作。将设备放在可以看到卫星的位置似乎没有锁。使用调试器 GpsStatus.getSatellites() 会带来一个空列表。现在,在不移动设备的情况下,我启动了具有 GPS 类型罗盘方案的应用程序罗盘(Catch.com,因为有很多)。那个锁定卫星,速度非常快,从那一刻起,我的应用程序也报告了卫星。如果指南针关闭,则应用程序会卡在指南针提供的最后一个数字上!!!我个人用于测试的设备是 Nexus 7 2013 及其最新的官方更新 (Android 6.0.1)。

这是一些代码:

public class BackgroundLocationService extends Service implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    GpsStatus.Listener,
    LocationListener {

// Constants here....

private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private LocationManager locationManager;
// Flag that indicates if a request is underway.
private boolean mInProgress;

private NotificationManagement myNotificationManager;
private Boolean servicesAvailable = false;

//And other variables here...

@Override
public void onCreate()
{
    super.onCreate();

    myNotificationManager = new NotificationManagement(getApplicationContext());
    myNotificationManager.displayMainNotification();

    mInProgress = false;
    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Set the update interval
    mLocationRequest.setInterval(PREFERRED_INTERVAL);
    // Set the fastest update interval
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);

    servicesAvailable = servicesConnected();

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.addGpsStatusListener(this);

    setUpLocationClientIfNeeded();
}

/**
 * Create a new location client, using the enclosing class to
 * handle callbacks.
 */
protected synchronized void buildGoogleApiClient()
{
    this.mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

private boolean servicesConnected()
{

    // Check that Google Play services is available
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

    // If Google Play services is available
    if (ConnectionResult.SUCCESS == resultCode)
    {
        return true;
    }
    else
    {
        return false;
    }
}

public int onStartCommand(Intent intent, int flags, int startId)
{
    super.onStartCommand(intent, flags, startId);

    if (!servicesAvailable || mGoogleApiClient.isConnected() || mInProgress)
        return START_STICKY;

    setUpLocationClientIfNeeded();
    if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting() && !mInProgress)
    {
        mInProgress = true;
        mGoogleApiClient.connect();
    }
    return START_STICKY;
}


private void setUpLocationClientIfNeeded()
{
    if (mGoogleApiClient == null)
        buildGoogleApiClient();
}

public void onGpsStatusChanged(int event)
{

}

// Define the callback method that receives location updates
@Override
public void onLocationChanged(Location location)
{
    simpleGPSFilter(location);
}

// Other fancy and needed stuff here...

/**
 * "Stupid" filter that utilizes experience data to filter out location noise.
 * @param location Location object carrying all the needed information
 */
private void simpleGPSFilter(Location location)
{
    //Loading all the required variables
    int signalPower = 0;
    satellites = 0;
    // Getting the satellites
    mGpsStatus = locationManager.getGpsStatus(mGpsStatus);
    Iterable<GpsSatellite> sats = mGpsStatus.getSatellites();
    if (sats != null)
    {
        for (GpsSatellite sat : sats)
        {
            if (sat.usedInFix())
            {
                satellites++;
                signalPower += sat.getSnr();
            }
        }
    }
    if (satellites != 0)
        signalPower = signalPower/satellites;
    mySpeed = (location.getSpeed() * 3600) / 1000;
    myAccuracy = location.getAccuracy();
    myBearing = location.getBearing();
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    Log.i("START OF CYCLE", "START OF CYCLE");
    Log.i("Sat Strength", Integer.toString(signalPower));
    Log.i("Locked Sats", Integer.toString(satellites));

    // Do the math for the coordinates distance
    /*
     * Earth's radius at given Latitude.
     * Formula: Radius = sqrt( ((equatorR^2 * cos(latitude))^2 + (poleR^2 * sin(latitude))^2 ) / ((equatorR * cos(latitude))^2 + (poleR * sin(latitude))^2)
     * IMPORTANT: Math lib uses radians for the trigonometry equations so do not forget to use toRadians()
     */
    Log.i("Lat for Radius", Double.toString(latitude));
    double earthRadius = Math.sqrt((Math.pow((EARTH_RADIUS_EQUATOR * EARTH_RADIUS_EQUATOR * Math.cos(Math.toRadians(latitude))), 2)
            + Math.pow((EARTH_RADIUS_POLES * EARTH_RADIUS_POLES * Math.cos(Math.toRadians(latitude))), 2))
            / (Math.pow((EARTH_RADIUS_EQUATOR * Math.cos(Math.toRadians(latitude))), 2)
            + Math.pow((EARTH_RADIUS_POLES * Math.cos(Math.toRadians(latitude))), 2)));
    Log.i("Earth Radius", Double.toString(earthRadius));

    /*
     * Calculating distance between 2 points on map using the Haversine formula (arctangent writing) with the following algorithm
     * latDifference = latitude - lastLatitude;
     * lngDifference = longitude - lastLongitude;
     * a = (sin(latDifference/2))^2 + cos(lastLatitude) * cos(latitude) * (sin(lngDifference/2))^2
     * c = 2 * atan2( sqrt(a), sqrt(1-a) )
     * distance = earthRadius * c
     */
    double latDifference = latitude - lastLatitude;
    double lngDifference = longitude - lastLongitude;
    double a = Math.pow((Math.sin(Math.toRadians(latDifference / 2))), 2) + (Math.cos(Math.toRadians(lastLatitude))
            * Math.cos(Math.toRadians(latitude))
            * Math.pow((Math.sin(Math.toRadians(lngDifference / 2))), 2));
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double distance = earthRadius * c;
    Log.i("New point distance", Double.toString(distance));

    // Filter logic
    // Make an initial location log
    if ((!isInit) && (myAccuracy < ACCEPTED_ACCURACY))
    {
        isInit = true;
        lastLatitude = latitude;
        lastLongitude = longitude;
        logLocations(location);
    }
    else
    {
        // Satellite lock (use of GPS) on the higher level
        if (satellites == 0)
        {
            // Accuracy filtering at the second level
            if (myAccuracy < ACCEPTED_ACCURACY)
            {
                if ((distance > ACCEPTED_DISTANCE))
                {
                    lastLatitude = latitude;
                    lastLongitude = longitude;
                    logLocations(location);
                    Log.i("Location Logged", "No Sats");
                    /*
                    // Calculate speed in correlation to perceived movement
                    double speed = distance / (PREFERRED_INTERVAL / 1000);  // TODO: Need to make actual time dynamic as the fused location does not have fixed timing
                    if (speed < ACCEPTED_SPEED)
                    {
                        lastLatitude = latitude;
                        lastLongitude = longitude;
                        logLocations(location);
                    } */
                }
            }
        }
        else if ((satellites < 4) && (signalPower > ACCEPTED_SIGNAL))
        {
            if (myAccuracy < (ACCEPTED_ACCURACY + 50))
            {
                logLocations(location);
                Log.i("Location Logged", "With Sats");
            }
        }
        else
        {
            if (myAccuracy < (ACCEPTED_ACCURACY + 100))
            {
                lastSpeed = mySpeed;
                lastBearing = myBearing;
                lastLatitude = latitude;
                lastLongitude = longitude;
                logLocations(location);
                Log.i("Location Logged", "With Good Sats");
            }
        }
    }
    Log.i("END OF CYCLE", "END OF CYCLE");
}

private void logLocations(Location location)
{
    String myprovider = "false";

    String temp = timestampFormat.format(location.getTime());
    MySQLiteHelper dbHelper = new MySQLiteHelper(getApplicationContext());

    try
    {
        dbHelper.createEntry(latitude, longitude, allschemes, temp, mySpeed, myAccuracy, myBearing, myprovider, satellites);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    CheckAutoArrive(String.valueOf(latitude), String.valueOf(longitude));

}

这是我认为可能需要的代码部分。我把所有的过滤代码和计算地球半径的数学一起留在那里,给定纬度和地图上两点之间的距离。如果需要,请随意使用。

事实上,Compass 应用程序实际上可以使系统获得卫星,而我的应用程序不能。有没有办法真正强制读取位置服务?是否有可能 Fused Location 实际上使用了 GPS 但 Location Manager 不知道?

最后我想提一下,该应用程序已经在具有不同版本 Android 的其他设备(手机,而非平板电脑)上进行了测试,并且似乎可以正常运行。

我们非常欢迎任何想法。当然,继续问任何我可能忘记提及的问题。

编辑:我的实际问题隐藏在文本中,因此将它们列出来:

1) 我们从 Fused Location 获得的位置数据和我们只能从同步位置管理器获得的其余 GPS 数据是否同步,或者是否有可能获得一个位置但错误的锁定数量特定点的卫星?

2) 应用程序无法锁定卫星但如果锁定来自另一个应用程序似乎被应用程序正确使用的奇怪行为背后的原因可能是什么?更奇怪的是,这种情况发生在 Nexus 7 (Android 6.0.1) 上,但不会发生在使用不同 Android 版本测试的其他设备上。

据我了解:

1)

FusedLocationApi returns 一个新位置 每次 客户端设备上有来自 任何 相关提供商的新读数(WiFi、CellTower、GPS、蓝牙)。该读数与先前的位置估计融合(可能使用扩展卡尔曼滤波器或类似滤波器)。生成的位置更新是多个来源的融合估计,这就是为什么没有附加来自各个提供商的元数据的原因。

因此,您从 API 获得的 Location 数据可能与从 LocationManager 获得的纯 GPS 读数一致(如果 GPS 是最新且相关的位置源),但它不必如此。因此,从最后一次纯 GPS 读数中获得的卫星数量可能适用于 FusedLocationApi 返回的最新位置,也可能不适用。

简而言之:

无法保证从 LocationManager 获取的位置读数与从 FusedLocationApi 获取的位置同步

2)

首先:要查明此问题的根本原因,您需要在多个位置使用多个设备进行测试。既然你问了

What could be the reason behind the weird behavior?

我将抛出一个理论:假设 LocationManager 和 FusedLocationApi 完全分开工作,LocationManager 可能很难获得修复,因为您仅依赖 GPS。 尝试使用 NETWORK_PROVIDER in addition to GPS to speed up the time-to-first-fix (thus enabling the LocationManager to make use of Assisted GPS)。其他应用程序(如 Compass 应用程序)几乎肯定会这样做,这可以解释为什么它们能更快地得到修复。 注意:开始接收GPS数据后,您当然可以注销网络供应商。或者你保持它打开但忽略它的更新。

这是对奇怪行为的一种可能解释。您可能知道位置行为取决于设备、OS、GPS 芯片组、固件和您所处的位置在 - 所以如果你打算手动(即不使用 FusedLocationApi),你将不得不做很多实验。


除了答案之外,让我对您的问题提供一个自以为是的看法(持保留意见 ;-):我认为您正在尝试将两种用途非常不同的东西结合起来案例,并不意味着合并。

获取卫星数量完全是技术性的事情。 除非您的应用程序教会他们有关 GNSS 的知识,否则没有最终用户会对此类信息感兴趣。如果您想出于内部分析目的记录它,那很好,但是您必须能够处理这些信息不可用的情况。

场景 1:出于某种原因,您决定绝对需要 GPS 读数的详细(技术)细节。在这种情况下,自己构建逻辑,采用老派的方式。 IE。通过 LocationManager 请求 GPS 读数(并可能通过使用网络提供商加快此过程),然后自行融合这些东西。但是,在这种情况下 永远不要触及 FusedLocationApi。 尽管现在看起来过时和神秘,但将 LocationManager 与 DIY 融合逻辑结合使用对于少数用例仍然非常有意义。这就是 API 仍然存在的原因。

场景 2:您只是想快速准确地更新客户端的位置。在这种情况下,指定您想要的更新频率和准确性,并让 FusedLocationApi 完成它的工作。 FusedLocationApi 在过去的几年里取得了长足的进步,现在它很可能比任何 DIY 逻辑更快更好地弄清楚如何获取位置信息。这是因为获取位置信息是一个非常复杂的问题,它取决于客户端设备的能力(芯片组、固件、OS、GPS、WiFi、GSM/LTE、蓝牙等)物理环境(WiFi/CellTower/Bluetooth 信号附近,内部或外部,晴空或城市峡谷等)。 在这种情况下,不要接触手动提供程序。如果这样做,不要指望对单个提供者的读数与融合结果之间的关系做出任何有意义的推论。


最后两点: