Search code examples
javaandroidgoogle-mapspermissionslocation

How to ask for location permission in Android?


I have tried so many codes and solutions but none of them worked. I want to ask the user for permission and get the pop-up window. Even though I used the code the window won't show? I think the code can get changed but I don't know exactly where to place it. Also, I'm new to Android Studio



public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {


    private GoogleMap mMap;
    private LatLngBounds PODGORICA = new LatLngBounds(
            new LatLng(42.400334, 19.227705), new LatLng(42.470269, 19.323107));

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;


    private static final String TAG = "MapActivity";

    LocationManager locationManager;
    String provider;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);

        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);


        Button btnQR = (Button) findViewById(R.id.skener);


        btnQR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                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_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
                        ,10);
            }
            return;
        }


    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {


        mMap = googleMap;

        mMap.setLatLngBoundsForCameraTarget(PODGORICA);
        mMap.setMinZoomPreference(5.0f);
        mMap.setMaxZoomPreference(25.0f);

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(42.441332, 19.262953))
                .zoom(15)
                .bearing(0)
                //.tilt(45)
                .build();
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));



     //   mMap.setMyLocationEnabled(true);

    }

I even tried codes from Googles official page but got same result...


Solution

  • From API level 23 (Android 6.0 Marshmallow) we need to ask Run-time permission from the user-end. You can do this in two steps.

    1. Add these two permissions in AndroidManifest.xml file.

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

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

    Example:

    <manifest xlmns:android...>
     ...
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
     <application ...
    </manifest>
    
    1. Put this code block inside class where you need to get current location
        if ( Build.VERSION.SDK_INT >= 23){
                  if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
                              PackageManager.PERMISSION_GRANTED  ){
                       requestPermissions(new String[]{
                                          android.Manifest.permission.ACCESS_FINE_LOCATION},
                                  REQUEST_CODE_ASK_PERMISSIONS);
                          return ;
                      }
                  }
    
                  getLocation();
                
      }
      //get access to location permission
      final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
    
    
    
      @Override
      public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
          switch (requestCode) {
              case REQUEST_CODE_ASK_PERMISSIONS:
                  if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                      getLocation();
                  } else {
                      // Permission Denied
                      Toast.makeText( this,"your message" , Toast.LENGTH_SHORT)
                              .show();
                  }
                  break;
              default:
                  super.onRequestPermissionsResult(requestCode, permissions, grantResults);
          }
      }
    
    //Get location
    public  void getLocation(){
          LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
              Location myLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                  if (myLocation == null) 
                  {
                      myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
    
                  }
      }