这只是一个简单的GPS定位器,向我显示了经度和纬度。但是,当我第一次运行该应用程序时,一切正常,但是在启用和禁用手机上的GPS后,它无法跟踪我,并且我的位置对象(位置)为空。它变得更加时髦,因为我安装了一个伪造的GPS应用程序,然后将其设置到另一个国家,并且我的应用程序向我显示了这个伪造的GPS国家的经度和纬度。我试图重新安装我的应用程序,但是第一次运行又一次为空,并且该应用程序无法跟踪我的GPS。是我的代码有问题还是我住所所在位置的GPS信号微弱?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getLoc(View v) {
TextView txtLong = findViewById(R.id.textViewLong);
TextView txtLat = findViewById(R.id.textViewLat);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location loc = locationManager.getLastKnownLocation(bestProvider);
if (loc == null){
Toast.makeText(getApplicationContext(), "GPS signal not found", Toast.LENGTH_SHORT).show();
}
if(loc != null){
txtLong.setText("Longitude: " + loc.getLongitude());
txtLat.setText("Latitude: " + loc.getLatitude() );
}
if(loc == null) {
txtLong.setText("loc is = null!");
}
}
最佳答案
不要像这样使用getLastKnownLocation。它不可靠,或者意味着可靠。它可能有一个值,但该值超时并经常返回null-实际上比其他任何东西都返回null。如果需要获取位置,请使用requestSingleUpdate或requestLocationUpdates。
如果系统已经知道,可以将getLastKnownLocation用作优化来更快地获取位置一到两秒。它不能用于其他任何用途。
关于java - GPS定位应用首次运行,但再次尝试后,找不到我的经度和纬度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60592737/