简体   繁体   English

使用GPS获取我在android中的当前位置

[英]Getting my current location in android using GPS

I am trying to get a current location using the GPS. 我正在尝试使用GPS获取当前位置。

Given the following code: 给出以下代码:

    LocationManager manager = (LocationManager)this.
            getSystemService(Context.LOCATION_SERVICE);

    Location loc = manager.getLastKnownLocation(
            LocationManager.GPS_PROVIDER);

    loc=manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    double la=loc.getLatitude();
    double lon=loc.getLongitude();

When using the AVD emulator with defined fix coordinates, or when tested with my android smartphone, it does not work. 当使用具有定义的固定坐标的AVD模拟器时,或在我的android智能手机上进行测试时,它不起作用。

While in Android Studios trying to debug it with the emulator, it get stuck on the loc.getLatitude . 在Android Studios中尝试使用模拟器进行调试时,它卡在了loc.getLatitude Overall, at the end, I got a Java RuntimeException as shown below: 总的来说,最后,我得到了一个Java RuntimeException ,如下所示:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.social.gps/com.example.social.gps.MainActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
        .
        .
        .

I guess its because the loc reference is null. 我猜是因为loc引用为空。

I have: 我有:

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

in the manifest. 在清单中。

So how can I get it to work? 那么我怎样才能使它工作呢?

This is because your loc variable is null - it happens when there are no last location in the cache. 这是因为loc变量为null-当缓存中没有最后一个位置时,它将发生。

getLastKnownLocation() doesn't return the current location, it returns location obtained previously by your or some other app. getLastKnownLocation()不会返回当前位置,它会返回您或其他应用先前获得的位置。 To receive current location, you need to subscribe for location updates using locationManager.requestLocationUpdates() . 要接收当前位置,您需要使用locationManager.requestLocationUpdates()订阅位置更新。 That will start mentioned provider (GPS, Network or Passive) if it is enabled by user and send location updates via callback. 如果用户启用了该提供程序(GPS,网络或无源),它将通过回调发送位置更新。

预先设置DDMS并将纬度和经度手动发送到模拟器,因为模拟器不会检索位置状态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM