2014-06-28 221 views
0

我的查詢如下。考慮我想創建一個API來獲取使用Android應用程序的用戶的當前位置。我無法得到解決方案。我需要在應用程序代碼中做什麼?或者有什麼預定義的android參考中獲取我開發的應用程序的位置?Android當前位置

回答

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(); 
} 
+0

謝謝你的答案,但我應該已經在我的問題更詳盡。我擴展到我的問題,如果我想要獲取特定用戶的位置作爲應用程序將由多個設備安裝? –