Home > Java > javaTutorial > How to Request Location Permissions at Runtime in Android?

How to Request Location Permissions at Runtime in Android?

Barbara Streisand
Release: 2024-12-08 04:17:10
Original
347 people have browsed it

How to Request Location Permissions at Runtime in Android?

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:

  1. Check for permissions: Use ActivityCompat.checkSelfPermission() to determine if the app has the necessary permissions.
  2. Request permissions: If permissions are not granted, use ActivityCompat.requestPermissions() to prompt the user for permission.
  3. Handle user response: Override onRequestPermissionsResult() to handle the user's response. If permission is granted, perform the location-related task.

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 ...
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template