在 Android 上获取当前 GPS 位置

发布于 2024-10-16 03:26:55 字数 1806 浏览 8 评论 0原文

我试图通过 GPS 功能获取用户的当前位置,

编写了一个实现 LocationListener 的简单类

public class LocationManagerHelper implements LocationListener {

    private static double latitude;
    private static double longitude;

    @Override
    public void onLocationChanged(Location loc) {
        latitude = loc.getLatitude();
        longitude = loc.getLongitude();
    }

    @Override
    public void onProviderDisabled(String provider) { }

    @Override
    public void onProviderEnabled(String provider) { }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    public static double getLatitude() {
        return latitude;
    }

    public static double getLongitude() {
        return longitude;
    }

}

,并通过一个简单的操作访问这些经度和纬度值,

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /** create a TextView and write Hello World! */
    TextView tv = new TextView(this);

    LocationManager mlocManager = 
                    (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    LocationListener mlocListener = new LocationManagerHelper();

    mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
            mlocListener);

    if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            tv.append("Latitude:- " + LocationManagerHelper.getLatitude()
                    + '\n');
            tv.append("Longitude:- " + LocationManagerHelper.getLongitude()
                    + '\n');
    } else {
        tv.setText("GPS is not turned on...");
    }

    /** set the content view to the TextView */
    setContentView(tv);

但它总是返回 0.0 作为结果.无法找出问题所在。

I'm trying to get the user's current location via GPS capability,

Wrote a simple class that implements LocationListener

public class LocationManagerHelper implements LocationListener {

    private static double latitude;
    private static double longitude;

    @Override
    public void onLocationChanged(Location loc) {
        latitude = loc.getLatitude();
        longitude = loc.getLongitude();
    }

    @Override
    public void onProviderDisabled(String provider) { }

    @Override
    public void onProviderEnabled(String provider) { }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    public static double getLatitude() {
        return latitude;
    }

    public static double getLongitude() {
        return longitude;
    }

}

and from a simple Action I'm accessing these longitude and latitude values

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /** create a TextView and write Hello World! */
    TextView tv = new TextView(this);

    LocationManager mlocManager = 
                    (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    LocationListener mlocListener = new LocationManagerHelper();

    mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
            mlocListener);

    if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            tv.append("Latitude:- " + LocationManagerHelper.getLatitude()
                    + '\n');
            tv.append("Longitude:- " + LocationManagerHelper.getLongitude()
                    + '\n');
    } else {
        tv.setText("GPS is not turned on...");
    }

    /** set the content view to the TextView */
    setContentView(tv);

But it always returns 0.0 as the result.Couldn't figure out the problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

微凉徒眸意 2024-10-23 03:26:55

位置更新实际上是异步。这意味着 API 不会让您的调用线程等到新位置可用为止;相反,您使用特定方法(回调)注册观察者对象,每当计算新位置时都会调用该方法。

Android LocationManager API 中,观察者是一个 LocationListener 对象,位置更新的主要回调是 onLocationChanged()

这是一个试图解释这一点的图表(希望这有助于而不是让您感到困惑!)

Sequence diagram

因此,从您当前的代码中:

  • 将 mlocListener 声明为 Activity 子类的成员
  • 添加LocationListener 实现中的日志输出(Logcat 行)
  • 保持其余代码不变。
  • 在清单中添加正确的权限(GPS 需要 FINE_LOCATION )如果还没有这样做。
  • 尝试将手机连接到互联网并靠近窗户,以获得相当快的 GPS 定位(应该约为 30 秒)。

然后启动应用程序并观察 logcat 中发生的情况。您将看到状态更改和位置更新在初始请求后不会立即进行,从而解释了为什么您的文本视图始终显示 (0.0,0.0)。

更多:http://developer.android.com/guide/topics /location/获取-user-location.html

Location updates are in fact asynchronous. This means the API does not make your calling thread wait until a new location is available ; instead you register an observer object with a specific method (callback) that gets called whenever a new location gets computed.

In the Android LocationManager API, the observer is a LocationListener object, and the main callback for location updates is onLocationChanged()

Here is a diagram trying to explain this point (hope this helps rather than confuse you!)

Sequence diagram

So from your current code :

  • Declare mlocListener as a member of your Activity subclass
  • Add log outputs (Logcat lines) in your LocationListener implementation
  • Keep the rest of the code as is.
  • Add the right permissions in the manifest (FINE_LOCATION is needed for GPS) if not done so yet.
  • Try to have the phone connected to Internet and near a window, in order to get a quite fast GPS fix (should be ~30s).

Then launch the app and watch what happens in the logcat. you will see that status changes and location updates are not immediate after the initial request, thus explaining why your textview always shows (0.0,0.0).

More: http://developer.android.com/guide/topics/location/obtaining-user-location.html

甩你一脸翔 2024-10-23 03:26:55

在 onCreate() 返回之前,您的位置更新回调无法被触发。如果将纬度/经度变量初始化为虚拟值,您可能会看到正在打印这些值。

在 onLocationChanged 中添加一些日志记录,以便您可以看到它正在被触发,然后阅读一些有关 Android 应用程序如何在回调和更新 UI 方面工作的信息。

还要确保您的应用程序在其清单中具有适当的权限。

Your location update callbacks can't be fired until after onCreate() returns. If you initialize your lat/long variables to dummy values you will probably see you are printing those values.

Put some logging in your onLocationChanged so that you can see it's being fired, then read up a bit on how android applications work with regard to callbacks and updating the UI.

Also make sure your application has appropriate permissions in its manifest.

内心旳酸楚 2024-10-23 03:26:55

获得 mLocListener 后 - 设置条件,如下所示


字符串 mlocProvider;
标准 hdCrit = new Criteria();
hdCrit.setAccuracy(Criteria.ACCURACY_COARSE);
mlocProvider = mlocManager.getBestProvider(hdCrit, true);

然后使用 getLastKnownLocation


tv.append("\n\n位置(从最后已知的位置开始):");
位置 currentLocation = mlocManager.getLastKnownLocation(mlocProvider);

确保您的清单中包含这些
<代码>
使用权限 android:name="android.permission.ACCESS_COARSE_LOCATION"
使用权限 android:name="android.permission.ACCESS_FINE_LOCATION"

如果您使用的是模拟器 - 在 DDMS 视角中,请在“模拟器控制”选项卡中查找“位置控制”。然后使用“手动”选项卡设置经度和纬度,然后单击发送 - 在程序运行时执行此操作,您会看到对 onLocationchanged 的​​调用。最好在 onLocationChanged 上登录。

顺便说一句,requestLocationUpdates 中的参数设置为“... 0,0...” - 它将耗尽您的电池 - 我看到手机在 6 - 8 小时内就没电了 - 将其更改为“...30000, 100 ...” - 第一个参数以毫秒为单位,另一个参数以米为单位。

After you get mLocListener - set the Criteria as shown below


String mlocProvider;
Criteria hdCrit = new Criteria();
hdCrit.setAccuracy(Criteria.ACCURACY_COARSE);
mlocProvider = mlocManager.getBestProvider(hdCrit, true);

and then use getLastKnownLocation


tv.append("\n\nLocations (starting with last known):");
Location currentLocation = mlocManager.getLastKnownLocation(mlocProvider);

Make sure you have these in your manifest

uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"

If you are using Emulator - In DDMS Perspective, look for Location Controls in Emulator Control tab. Then use Manual tab to set the Longitude and Latitude and click send - do this when your program is running you see a call to onLocationchanged. It is good idea to have log in onLocationChanged.

BTW, the parameters in requestLocationUpdates are set to "... 0,0..." - it will drain your battery - I have seen the phone go dead in 6 - 8 hours - change it to "...30000, 100..." - the first parameter in millisec and the other is in meters.

凤舞天涯 2024-10-23 03:26:55

当你在模拟器上检查它时,它会给出 0.0.0.0。您必须将位置传递给模拟器。
您可以从 C:\android-sdk_r06\android-sdk-windows\tools\ddms.bat 文件传递​​此文件。

在 ddms 中有一个名为模拟器控件的选项卡。从那里您可以将位置传递给模拟器。
试试这个。希望它会起作用。

When you check it on emulator it will give 0.0. you have to pass the locations to emulator.
you can pass this from C:\android-sdk_r06\android-sdk-windows\tools\ddms.bat file.

in ddms there is a tab named emulator controls. from there you can pass the locations to emulator.
try this. hope it will work.

哭泣的笑容 2024-10-23 03:26:55

如何创建应用程序?

通过action获取当前位置坐标(get Location)
纬度/经度

将位置发布到网络服务器以显示在地图上。(提交)
清除按钮清除旧位置(清除位置)或在(提交)时它变得清晰(0.0.0.0)

获取 Android 上的当前 GPS 位置
http://developer.android.com/guide/topics/ location/获取-user-location.html

how to create app ?

Getting current location co-ordinates by action (get Location)
Lat/long

Post the location to the webserver to be displayed on the map.(Submit)
Clear button to clear the old location(Clear Location) or on (submit) it becomes clear (0.0.0.0)

Getting the current GPS location on Android
http://developer.android.com/guide/topics/location/obtaining-user-location.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文