我看了看一些教程,然后跟随一个教程制作了一个应用程序来获取用户的位置,但是在写完它之后,我遇到了大约4个错误,其中有3个已修复。现在,该应用程序开始启动,但是它无法获取位置或无法输出。这是我的代码。当我按下按钮时,没有任何反应,它不会崩溃或发出错误,所以我无法弄清楚问题出在哪里。
Java
<tr>
XML
private Button button;
private TextView textView;
private LocationManager locationManager;
private LocationListener locationListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
textView.append("\n" +location.getLatitude() +""+location.getLongitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.INTERNET
},10);
return;
}else{
configureButton();
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 10:
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
configureButton();
}
}
private void configureButton() {
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
locationManager.requestLocationUpdates("gps", 3000, 3, locationListener);
}
});
}