0

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

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 英里。

4

1 回答 1

0

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

于 2013-07-19T10:13:58.020 回答