2011-09-19 81 views
0

我有GetURL方法定義從網絡提供商找到我的位置,您可以發送下面的代碼。getSystemService未定義類型GetLocation

如果我使用Activity在主類中定義了代碼段,這很好地工作,但是當我想創建一個單獨的類(例如GetLocation類)時,我無法使用getSystemService方法,並且在主題中收到錯誤(getSystemService是未定義爲GetLocation的類型)。有幾個關於這個話題的條目,但我不完全理解。

這是一個菜鳥問題,所以在回答時考慮到這一點:)謝謝你們。

public String GetURL() { 
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
    Criteria criteria = new Criteria(); 
    criteria.setAccuracy(Criteria.ACCURACY_FINE); 
    String locationProvider = LocationManager.NETWORK_PROVIDER; 
    mostRecentLocation = locationManager.getLastKnownLocation(locationProvider); 
    if(mostRecentLocation != null) { 
     double lat = mostRecentLocation.getLatitude(); 
     double lng = mostRecentLocation.getLongitude(); 
     currentLocation = "Lat: " + lat + " Lng: " + lng; 
     Log.e("LOCATION -------------", currentLocation + ""); 
    } 
    return currentLocation; 
} 

回答

5

方法getSystemService()屬於Context類。

因此,如果你想移動getUrl()成爲其他地方的實用方法,你需要在Context對象傳遞,如當前Activity(因爲它從Context繼承)。

例如:
Util.java

public static String getUrl(Context context) { 
    LocationManager lm = (LocationManager) 
     context.getSystemService(Context.LOCATION_SERVICE); 

    // ... your existing code ... 
    return currentLocation; 
} 

MyActivity.java

public void onCreate() { 
    // ... usual stuff ... 

    String url = getUrl(this); 
} 
+0

感謝克里斯託弗。我使用getBaseContext而不是這個來調用方法,它很好地工作。 – DuyguK