返回的网络位置错误

时间:2013-07-19 09:26:11

标签: android location

我想使用网络获取用户的位置。这是我的代码

package com.example.locationtest;

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;

public class WhereAmI extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LocationManager locationManager;
        String context = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) getSystemService(context);

        Criteria crta = new Criteria();
        crta.setAccuracy(Criteria.ACCURACY_FINE);
        crta.setAltitudeRequired(false);
        crta.setBearingRequired(false);
        crta.setCostAllowed(true);
        crta.setPowerRequirement(Criteria.POWER_LOW);
        String provider = locationManager.getBestProvider(crta, true);

        // String provider = LocationManager.GPS_PROVIDER;
        Location location = locationManager.getLastKnownLocation(provider);
        updateWithNewLocation(location);

        locationManager.requestLocationUpdates(provider, 1000, 0,
                locationListener);
    }

    private final LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            updateWithNewLocation(location);
        }

        @Override
        public void onProviderDisabled(String provider) {
            updateWithNewLocation(null);
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

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

    };

    private void updateWithNewLocation(Location location) {
        String timeStamp = (String) DateFormat.format("hh:mm:ss",
                new java.util.Date());
        String locationString = location.getLatitude() + ", "
                + location.getLongitude();

        Log.i("Main", "Time = " + timeStamp + " Location = " + locationString);
    }
}

此代码适用于我的nexus 4,但如果我将它与我的Galaxy Gio一起使用,那么它的位置将会超过30英里..

1 个答案:

答案 0 :(得分:0)

网络位置基于手机所连接的最近的手机信号塔。您的Nexus4可能连接到一个Cell塔,而Galaxy Gio可能连接到另一个可能远离设备所在位置的蜂窝塔。要获得准确的修复,请使用GPS_PROVIDER。我在使用NETWORK_PROVIDER之前遇到过这个问题。当我开始使用GPS_PROVIDER时,摆脱它,这给了我准确的修复