确认应用程序是否已获取ACCESS_COARSE_LOCATION权限。
如果应用程序已获得ACCESS_COARSE_LOCATION权限,则需要在AndroidManifest.xml中将uses-permission修改为以下方式:
在应用程序中添加以下代码:
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { //Location permission not granted, request permission ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1); }
在onRequestPermissionsResult回调方法中添加以下代码:
@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case 1: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //Location permission granted, proceed with your work } else { Toast.makeText(this, "Location permission required for this feature", Toast.LENGTH_SHORT).show(); } return; } } }
通过这些步骤,您的应用程序应该能够在用户允许近似位置权限时正常运行,而不会崩溃。