每次运行此程序时,我都会收到错误消息"java.lang.IllegalStateException:在onCreate()之前,系统服务不可用于Activities"
我需要获得用户的经度和纬度,这样我就可以在应用程序的其余部分使用它,但我不知道如何克服这个错误。
public class map extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private FloatingActionButton plus;
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
plus = (FloatingActionButton) findViewById(R.id.newPlace);
plus.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
startActivity(new Intent(map.this, newPlacePop.class));
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng currentPosition = new LatLng(latitude, longitude);
float zoomLevel = 16; //This goes up to 21
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, zoomLevel));
}
}
java.lang.IllegalStateException: System services not available to Activities before onCreate()
您有一个字段初始值设定项,它正在调用getSystemService()
:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
您不能拨打getSystemService()
—或您从Activity
继承的大多数其他方法—在onCreate()
方法中调用super.onCreate()
之前。
所以,改变:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
至:
LocationManager lm;
Location location;
double longitude;
double latitude;
并在onCreate()
方法中的super.onCreate()
之后添加以下行:
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location==null) {
// do something
}
else {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
我需要获得用户的经度和纬度,这样我就可以在我的应用的其余部分使用它
您的代码不太可能得到纬度和经度。getLastKnownLocation()
经常返回null
,在上面显示的代码中,如果没有if
检查,就会导致NullPointerException
崩溃。您可能希望阅读有关获取位置数据的文档。
此外,你提到了"API 23"。如果您的targetSdkVersion
为23或更高,则需要该代码在运行时请求您的位置权限。