2011-09-19 38 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