获取Android上的当前GPS位置

Swi*_*tch 4 java gps android locationmanager locationlistener

我正试图通过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;
    }

}
Run Code Online (Sandbox Code Playgroud)

从一个简单的动作我正在访问这些经度和纬度值

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);
Run Code Online (Sandbox Code Playgroud)

但它总是返回0.0作为结果.不能解决问题.

Sté*_*ane 19

位置更新实际上是异步的.这意味着API不会让您的调用线程等到新位置可用; 相反,您使用特定方法(回调)注册一个观察者对象,只要计算新位置就会调用该方法.

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

这是一个试图解释这一点的图表(希望这有助于而不是混淆你!)

序列图

所以从你目前的代码:

  • 将mlocListener声明为Activity子类的成员
  • 在LocationListener实现中添加日志输出(Logcat行)
  • 保持其余代码不变.
  • 如果尚未执行,则在清单中添加正确的权限(GPS需要FINE_LOCATION).
  • 尝试将手机连接到互联网和窗户附近,以获得相当快的GPS定位(应该是~30s).

然后启动应用程序并观察logcat中发生的情况.在初始请求之后,您将看到状态更改和位置更新不会立即显示,从而解释了textview始终显示的原因(0.0,0.0).

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