我在Android编码中 n00b ,今天我想尝试使用位置服务。
我设置了一个简单的类和一个简单的主,只是为了有经度和纬度。
但是当我尝试调用构造以进行反复操作时,Android Studio会弹出错误:
"错误:(33,16)错误:无法从静态上下文引用非静态变量纬度"
这是我的位置类
public class AppLocationManager implements LocationListener {
private LocationManager locationManager;
private String latitude;
private String longitude;
private Criteria criteria;
private String provider;
public AppLocationManager(Context context) {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1,0,this);
setMostRecentLocation(locationManager.getLastKnownLocation(provider));
}
private void setMostRecentLocation(Location lastKnownLocation) {
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
/*
* (non-Javadoc)
*
* @see
* android.location.LocationListener#onLocationChanged(android.location.
* Location)
*/
@Override
public void onLocationChanged(Location location) {
double lon = (double) (location.getLongitude());/// * 1E6);
double lat = (double) (location.getLatitude());// * 1E6);
// int lontitue = (int) lon;
// int latitute = (int) lat;
latitude = lat + "";
longitude = lon + "";
}
/*
* (non-Javadoc)
*
* @see
* android.location.LocationListener#onProviderDisabled(java.lang.String)
*/
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see
* android.location.LocationListener#onProviderEnabled(java.lang.String)
*/
@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see android.location.LocationListener#onStatusChanged(java.lang.String,
* int, android.os.Bundle)
*/
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:1)
将变量声明为静态,如下所示:
private static String latitude;
private static String longitude;
答案 1 :(得分:0)
要访问非静态属性和方法,您将成为该类的Object。要了解阅读this so thread:
AppLocationManager appLocationManager=new AppLocationManager(context);
String latitude=appLocationManager.getLatitude();
String longitude=appLocationManager.getLongitude();