Search code examples
javaandroidandroid-studiolocation

Android Studio request location permission popup


I want to have some code within a android studio application which, will popup a dialog box to request the users permission to enable location on the phone and, to allow the application to access permission. At the moment I have to manually turn on location and, then in the application settings enable location.

I want a popup dialog box to enable this.

This question is now resolved via an answer.

Thanks


Solution

  • At first, define your permission in AndroidManifest.xml file

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    

    Then add those two methods in your activity file.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        checkPermission();
    
    }
    
    public void checkPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                
                doWhatEveryYouWant :)
    
            } else {
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION,}, 1);
            }
        }
    }
    
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
            
            doWhatEveryYouWant :)
    
        }
    }