位置管理器android问题

时间:2011-08-01 15:29:02

标签: android location type-conversion logcat

我试图在点击按钮时获取用户的位置。
我的按钮onclick监听器中有以下代码:


locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
Location currentLocation = locationManager.getLastKnownLocation(bestProvider);
Log.e(tag,"reached till here");
location = Double.toString(currentLocation.getLatitude()) + " " + Double.toString(currentLocation.getLongitude());
Toast.makeText(getApplicationContext(), location, Toast.LENGTH_LONG);
MyLocation.setText(location);

我在logcat中获取输出 reached till here。之后应用程序停止并要求我强行关闭它。我最初做了一些搜索,发现getLatitude和getLongitude返回double值。所以我纠正了代码。但我仍然得到一个错误。我做错了什么?

编辑: logcat错误:
 得到RemoteException向pid 796 uid 10036发送setActive(false)通知  
我认为currentLocation返回null

2 个答案:

答案 0 :(得分:3)

如果您正在Emulator中测试您的应用,那么您可能没有任何提供商且currentLocation对象为空,这就是为什么getLatitude()getLongitude()会给NPE。

编辑:正如@grinnner所说,从DDMS的角度来看,你可以模拟位置坐标的发送。在eclipse中打开DDMS Perspective,在LocationControls选项卡中设置经度和纬度,然后单击发送。确保“设备”选项卡中的焦点位于您运行应用程序的模拟器上。

答案 1 :(得分:1)

如果您没有最后一个已知位置(只需对返回的值执行简单的空检查),则需要添加位置侦听器以获取位置。像这样:

// Start listening for a new location.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String bestProvider = lm.getBestProvider(new Criteria(), true);    
mMyLocationListener = new MyLocationListener();
lm.requestLocationUpdates(bestProvider, 0, 0, mMyLocationListener);

private class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location location) {
        // Do what you need to do with the longitude and latitude here.
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
}

您还应该记得在不再需要时立即删除位置监听器:

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.removeUpdates(mMyLocationListener);
mMyLocationListener = null;
相关问题