Android当前位置

时间:2014-06-28 15:01:43

标签: android api

我的查询如下。考虑我想创建一个api来获取用户的当前位置使用Android应用程序。我无法得到解决方案。我在应用程序代码中需要做什么?或者是否有预定义的Android参考资料来获取我开发的应用程序的位置?

1 个答案:

答案 0 :(得分:1)

public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 2; // 2 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 5000 * 1 ; // 5seconds 

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

private Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled)  //&& !isNetworkEnabled) {
            Log.e("GPS", "no network provider is enabled");            
        else 
        {
            this.canGetLocation = true;
            // First get location from Network Provider
            setupRequestLocationUpdates();            

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }      
}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}
}

// To consume it in activity:
gps = new GPSTracker(this);
@Override
protected void onResume() {
    super.onResume();
    gps.setupRequestLocationUpdates();
}

@Override
protected void onPause() {
    super.onPause();
    gps.stopUsingGPS();
}