0

我从 GPS 或网络获取位置。问题是我已经在 htc hope hd 上对其进行了测试,并且效果很好,但是现在我开始在三星银河位置的其他设备上进行测试,始终为空。

这是我获取位置的代码

  locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if( currentLocation == null){
    currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }

提前致谢

4

2 回答 2

0

您需要为位置更改注册一个侦听器。添加如下内容:

 LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                if (location != null) {
                    doSomethingWithLocation();
                }
            }

            public void onProviderDisabled(String provider) {
            }

            public void onProviderEnabled(String provider) {
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
            }
        };
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);

确保在请求位置更新时添加正确的等待时间。使用零而不是 1000,系统将没有足够的时间获取新位置。

运行上述代码后调用 getLastKnownLocation() 应该可以消除您的 null 问题。

于 2011-12-13T04:39:58.890 回答
0

你有任何 GPS 工作的 API 示例吗?如果应用程序已经设置了位置侦听器并等待第一个位置到达,我认为某些手机只会为应用程序提供最后一个已知位置。你的代码不会这样做。

public class YourActivity extends Activity implements LocationListener {
    private LocationManager lm;
    @Override public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

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

        startLocating();
    }
    private void startLocating(){
        lm.requestLocationUpdates("gps", 0, 10, this);  
    }
    @Override
    public void onLocationChanged(Location arg0) {
        lm.removeUpdates(this);
        /*
         * put your code here
         */
    }
    @Override public void onProviderDisabled(String arg0) {}
    @Override public void onProviderEnabled(String provider) {}
    @Override public void onStatusChanged(String provider, int status, Bundle extras) {}

}
于 2011-05-07T06:19:01.507 回答