Requesting Location Permissions at Runtime
The issue you're facing is that you need to explicitly request permissions for location access. Follow these steps to resolve it:
Here's an updated version of your code that incorporates the permission request logic:
public class MainActivity extends AppCompatActivity implements LocationListener { private static final int REQUEST_LOCATION_PERMISSION = 10; // ... Other code ... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION); return; } // Perform location-related task if permission is granted // ... } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case REQUEST_LOCATION_PERMISSION: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission granted, perform location-related task // ... } else { // Permission denied } } } } // ... Other methods ... }
The above is the detailed content of How to Request Location Permissions at Runtime in Android?. For more information, please follow other related articles on the PHP Chinese website!