没有wifi可以获得坐标吗?

时间:2014-12-24 14:29:42

标签: android gps location

我的代码在这里:

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
    List<String> providers = lm.getProviders(false);
    Location l = null;

    for (int i=providers.size()-1; i>=0; i--) {
            l = lm.getLastKnownLocation(providers.get(i));
            if (l != null) break;
    }

    double[] gps = new double[2];
    if (l != null) {
            gps[0] = l.getLatitude();
            gps[1] = l.getLongitude();
    }
    return gps;

我连接到互联网时只能获得坐标。

1 个答案:

答案 0 :(得分:0)

您也可以使用Android GPS服务获得Longitute和Latitute,

AndroidMenifest.xml

中添加权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

初​​始化,

// saving the context for later use
    private final Context mContext;

    // if GPS is enabled
    boolean isGPSEnabled = false;

    // Location and co-ordinates coordinates
    Location mLocation;
    double mLatitude;
    double mLongitude;

    // Minimum time fluctuation for next update (in milliseconds)
    private static final long TIME = 30000;
    // Minimum distance fluctuation for next update (in meters)
    private static final long DISTANCE = 20;

    // Declaring a Location Manager
    protected LocationManager mLocationManager;

   // This is constructor to get System Location services,
    public GPSService(Context context) {
        this.mContext = context;
        mLocationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

    }

检查GPS是否设法获取数据,

try {

            // Getting GPS status
            isGPSEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // If GPS enabled, get latitude/longitude using GPS Services
            if (isGPSEnabled) {
                mLocationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
                if (mLocationManager != null) {
                    mLocation = mLocationManager
                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (mLocation != null) {
                        mLatitude = mLocation.getLatitude();
                        mLongitude = mLocation.getLongitude();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }