【发布时间】:2018-11-07 10:39:22
【问题描述】:
我尝试通过 GPS 获取当前位置并显示出来。
首先我初始化 LocationManager,所以我总是使用方法 getLocation()
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, LocationListener {
private static final int REQUEST_LOCATION = 1;
private static int MY_PERMISSIONS_REQUEST_ACCESS;
TextView locationText;
LocationManager locationManager;
String lattitude,longitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Button buttonLocate = (Button) findViewById(R.id.buttonLocate);
locationText = (TextView)findViewById(R.id.locationText);
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
buttonLocate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(locationManager != null) {
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// ..DO SMTH
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
getLocation();
}
}
}
});
}
在getLocation()方法中,我正在检查权限,如果他们被授予,我请求位置更新并尝试获取纬度和经度,这是我的问题,因为位置始终为空,所以我无法获得坐标!
代码可能有什么问题,我该如何解决?...
void getLocation() {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
} else {
// REQUEST!
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, this);
Location location;
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
// LOCATION IS ALWAYS NULL!!!
double latti = location.getLatitude();
double longi = location.getLongitude();
lattitude = String.valueOf(latti);
longitude = String.valueOf(longi);
locationText.setText("Your current location is" + "\n" + "Lattitude = " + lattitude
+ "\n" + "Longitude = " + longitude);
} else {
Toast.makeText(this, "Unble to Trace your location", Toast.LENGTH_SHORT).show();
}
}
}
【问题讨论】:
-
getLastKnownLocation在没有缓存位置时为空。另外,你在执行OnLocationChanged吗? -
requestLocationUpdates()是一个需要一些时间的异步操作,因此在它之后立即调用getLastKnownLocation()不是可行的方法,尽管这是一种常见的反模式。 (并且在给定的代码中,您还混合了两个不同的位置提供程序。)
标签: java android locationmanager