从 Android 检索 GPS 修复中使用的卫星数量

2023-11-25

我正在尝试检索 GPS 修复中使用的卫星数量。我实现了两种不同的方法,如下所示:

package ti.utils;

import android.app.Activity;
import android.content.Context;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class Gps {

    private static final int TWO_MINUTES = 1000 * 60 * 2;
    private static Location Location;
    public static int Satellites = -1;

    public static void StartTracking(Activity activity)
    {
        final LocationManager locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);

        //listen for gps status changes.
        GpsStatus.Listener gpsStatusListener = new GpsStatus.Listener() {
            public void onGpsStatusChanged(int event) {
                Log("In onGpsStatusChanged event: " + event);
                if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS || event == GpsStatus.GPS_EVENT_FIRST_FIX) {
                    GpsStatus status = locationManager.getGpsStatus(null);
                    Iterable<GpsSatellite> sats = status.getSatellites();
                    // Check number of satellites in list to determine fix state
                    Satellites = 0;
                    for (GpsSatellite sat : sats) {
                        //if(sat.usedInFix())
                        Satellites++;
                    }
                    Log("Setting Satellites from GpsStatusListener: " + Satellites);
                }
            }
        };
        locationManager.addGpsStatusListener(gpsStatusListener);

        //listen for location changes.
        LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                // Called when a new location is found by the network location provider.
                try
                {
                    Log("Location changed! Speed = " + location.getSpeed() + " & Satellites = " + location.getExtras().getInt("satellites"));
                    boolean isBetter = isBetterLocation(location, Location);
                    if(isBetter)
                    {
                        Log("Set to new location");
                        Location = location;
                        Satellites = location.getExtras().getInt("satellites");
                        Log("Setting Satellites from LocationListener: " + Satellites);
                    }
                }
                catch(Exception exc)
                {
                    Log(exc.getMessage());
                }
            }
            public void onStatusChanged(String provider, int status, Bundle extras) {}
            public void onProviderEnabled(String provider) {}
            public void onProviderDisabled(String provider) {}
        };
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    }

    /** Determines whether one Location reading is better than the current Location fix
      * @param location  The new Location that you want to evaluate
      * @param currentBestLocation  The current Location fix, to which you want to compare the new one
      */
    protected static boolean isBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location, use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
        // If the new location is more than two minutes older, it must be worse
        } else if (isSignificantlyOlder) {
            return false;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                currentBestLocation.getProvider());

        // Determine location quality using a combination of timeliness and accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return true;
        }
        return false;
    }

    /** Checks whether two providers are the same */
    private static boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
          return provider2 == null;
        }
        return provider1.equals(provider2);
    }

    private static void Log(String message) {
        if(message != null && message.length() > 0) {
            //android.util.Log.i(LCAT, message);
            org.appcelerator.kroll.common.Log.i("SygicModule", message);
        }
    }

}

尽管我的手机上启用了独立 GPS,但侦听器事件(onGpsStatusChanged 和 onLocationChanged)都不会触发。我有 ACCESS_FINE_LOCATION 权限集:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

我下载了一个名为 GPS Status 的第 3 方应用程序,它能够正确显示卫星数量,所以我知道这不是我的 Droid X2 的问题。

有任何想法吗?


这是最终运行的代码。

package ti.utils;

import android.app.Activity;
import android.content.Context;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class Gps {

    private static final int TWO_MINUTES = 1000 * 60 * 2;
    private static Location Location;
    public static int Satellites = -1;

    public static void StartTracking(Activity activity)
    {
        final LocationManager locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);

        //listen for gps status changes.
        GpsStatus.Listener gpsStatusListener = new GpsStatus.Listener() {
            @Override
            public void onGpsStatusChanged(int event) {
                Log("In onGpsStatusChanged event: " + event);
                if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS || event == GpsStatus.GPS_EVENT_FIRST_FIX) {
                    GpsStatus status = locationManager.getGpsStatus(null);
                    Iterable<GpsSatellite> sats = status.getSatellites();
                    // Check number of satellites in list to determine fix state
                    Satellites = 0;
                    for (GpsSatellite sat : sats) {
                        //if(sat.usedInFix())
                        Satellites++;
                    }
                    Log("Setting Satellites from GpsStatusListener: " + Satellites);
                }
            }
        };
        locationManager.addGpsStatusListener(gpsStatusListener);

        //listen for location changes.
        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // Called when a new location is found by the network location provider.
                /*try
                {
                    Log("Location changed! Speed = " + location.getSpeed() + " & Satellites = " + location.getExtras().getInt("satellites"));
                    boolean isBetter = isBetterLocation(location, Location);
                    if(isBetter)
                    {
                        Log("Set to new location");
                        Location = location;
                        Satellites = location.getExtras().getInt("satellites");
                        Log("Setting Satellites from LocationListener: " + Satellites);
                    }
                }
                catch(Exception exc)
                {
                    Log(exc.getMessage());
                }*/
            }
            public void onStatusChanged(String provider, int status, Bundle extras) {}
            public void onProviderEnabled(String provider) {}
            public void onProviderDisabled(String provider) {}
        };
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    }

    /** Determines whether one Location reading is better than the current Location fix
      * @param location  The new Location that you want to evaluate
      * @param currentBestLocation  The current Location fix, to which you want to compare the new one
      */
    protected static boolean isBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location, use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
        // If the new location is more than two minutes older, it must be worse
        } else if (isSignificantlyOlder) {
            return false;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                currentBestLocation.getProvider());

        // Determine location quality using a combination of timeliness and accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return true;
        }
        return false;
    }

    /** Checks whether two providers are the same */
    private static boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
          return provider2 == null;
        }
        return provider1.equals(provider2);
    }

    private static void Log(String message) {
        if(message != null && message.length() > 0) {
            //android.util.Log.i(LCAT, message);
            org.appcelerator.kroll.common.Log.i("UtilsModule", message);
        }
    }

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 Android 检索 GPS 修复中使用的卫星数量 的相关文章

  • EditText 中的验证允许 IP 或 Web Url 主机

    我需要对我的 EditText 进行验证 以便它允许我输入有效的 IP 地址格式 即示例 132 0 25 225 or 网址格式 www 例如 www example com 逻辑是 如果用户首先输入任何数值 则验证 IP 将执行操作 否
  • Android 上的 Firebase:如何检查 Firebase 身份验证失败原因?

    我在 Android 上使用 Firebase 和 Firebase Auth 功能 I try FirebaseAuth signInWithEmailAndPassword如果失败 我想知道为什么登录过程失败 The signInWit
  • 检索子值 -firebase-

    System out println ref child email protected cdn cgi l email protection child email 我正在尝试获取 child 的值 但我始终获取该值的 URL 当我尝试使
  • 我可以在 firebase android 中加载另一个用户个人资料图像吗?

    如果我有其他用户的电子邮件但我以其他用户身份登录 我是否可以加载其他用户的个人资料图像 如果您使用 Firebase Storage 那么从技术上讲是的 它只是一个您可以从中检索任何文件的文件系统 如果不伪造您的应用程序 获取 api 密钥
  • AppCompat v21 工具栏更改徽标大小

    我正在从以前的操作栏迁移到 appcompat v21 中的新工具栏功能 我仍然想将徽标保留在操作栏 工具栏 的左上角 为此 我在布局中添加了支持工具栏 并为其创建了一个新的工具栏 app theme style NewToolBarSty
  • 如何将 EditText 传递给另一个活动?

    Intent intent new Intent this Name class intent putExtra key et getText toString startActivity intent Intent intent getI
  • 如何使用闹钟音量和 setAudioAttributes 来播放铃声?

    所以我正在尝试了解音频属性 这是我到目前为止所拥有的 alarm getSound will return a proper URI to pick a ringtone Ringtone tone RingtoneManager getR
  • Android-工具栏中的SearchView

    我只想在我的应用程序中添加 searchview 但我不想搜索任何东西 只是我想要用户输入的查询 到目前为止 我尝试了这段代码 但是当我运行我的应用程序时它崩溃了 Update 我尝试了这个 但即使我的应用程序崩溃了 main menu x
  • 从多个选项卡中的编辑文本字段获取文本

    我正在尝试创建一个使用选项卡作为输入表单的 Android 应用程序 基本上 我希望对其进行设置 以便用户可以在一个选项卡上输入一些信息 然后提交该信息 或者转到另一个选项卡并输入更多信息 然后从两个选项卡提交信息 我正在使用操作栏和片段来
  • Android Web Intent 问题

    G day 免责声明 我不是 Android 开发人员 我正在对我所描述的问题进行质量检查 我用来描述这个问题的技术术语可能是错误的 我正在测试一个 Android 应用程序 该应用程序在其清单中描述它可以使用 type 的地址处理 Web
  • Google 移动广告和 Kindle Fire

    我最近用 Google 移动广告替换了 AdMob 库 对此我有一个疑问 广告会出现在 Amazon Kindle Fire 设备上吗 我问这个是因为我知道 Google 移动广告依赖于 Google Play 服务 所以我有点困惑 Goo
  • 在 AppAuth-Android 中注销

    我有一个用JAVA开发的Android应用程序 对于这个应用程序 我使用的是身份服务器4 https github com IdentityServer IdentityServer4作为我的 STS 一切正常 但我找不到任何注销的实现Ap
  • ACCESS_BACKGROUND_LOCATION 不适用于低于 Q (29) 的 Android 版本

    我的应用程序面向 Android API 28 根据文档 https developer android com preview privacy location target android 10 我应该要求ACCESS BACKGROU
  • 内部存储的安全性如何?

    我需要的 对于 Android 我需要永久保存数据 但也能够编辑 并且显然是读取 它 用户不应访问此数据 它可以包含诸如高分之类的内容 用户不得对其进行编辑 我的问题 我会 并且已经 使用过Internal Storage 但我不确定它实际
  • 如何获取android手机型号、版本、sdk详细信息?

    如何获取android手机型号 版本 sdk详细信息 首先 看看 android sdk 页面上的这些 Build 类 http developer android com reference android os Build html h
  • 检测 ListView(或 ScrollView)内的滚动位置

    我正在构建一个聊天室应用程序 其中每 X 秒就会轮询一次新事件 每次发生这种情况时 此代码都会使用新数据更新 RoomAdapter ArrayAdapter 的自定义子类 并将其滚动到底部 RoomAdapter adapter Room
  • Android:确定 2.2 及更高版本上的摄像头数量

    我的应用程序需要在 Android 2 2 及更高版本上运行 我需要一种方法来确定可用摄像机的数量 有很多帖子解决了这个问题 但我找不到一个有效的 一种解决方案是简单地检测操作系统版本 任何 2 2 版本的设备都仅限于 1 个摄像头 即使该
  • 更改Android菜单的背景颜色[重复]

    这个问题在这里已经有答案了 我正在尝试将标准浅灰色更改为浅绿色 似乎没有一个简单的方法可以做到这一点 例如 通过 Android 主题 但我找到了一个解决方法 如本页所述 http tinyurl com 342dgn3 http tiny
  • Android:无法发送http post

    我一直在绞尽脑汁试图弄清楚如何在 Android 中发送 post 方法 这就是我的代码的样子 public class HomeActivity extends Activity implements OnClickListener pr
  • 通过powershell运行ADB命令

    所以我尝试通过 powershell 脚本运行一些 ADB 命令 这是我正在尝试做的一个简单示例 adb shell echo in adb shell su root echo you are now root ls cd data da

随机推荐