title: Adding location permissions on marshmallow
body: <p>I am writing a code to get lastknownlocation from location manager and this prompted me to add runtime permissions.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>public class MainActivity extends AppCompatActivity implements LocationListener {
  
      LocationManager locationManager;
      String provider;
      private final int MY_PERMISSIONS_REQUEST_CODE=1;
      Location location;
      Boolean isPermissionGranted=false;
      @Override
      protected void onCreate(Bundle savedInstanceState)
      {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
  
          locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  
          provider = locationManager.getBestProvider(new Criteria(), false);
  
  
         if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &amp;&amp; ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  
             if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) {
                 requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},MY_PERMISSIONS_REQUEST_CODE);
             }
  
            // return;
          }
  
      }
  
      public void getlastknownposition()
      {
  
      }
  
      @Override
      public void onLocationChanged(Location location) {
  
      }
  
      @Override
      public void onStatusChanged(String provider, int status, Bundle extras) {
  
      }
  
      @Override
      public void onProviderEnabled(String provider) {
  
      }
  
      @Override
      public void onProviderDisabled(String provider) {
  
      }
  
  
      @Override
      public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
          super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  
  
          if(requestCode == MY_PERMISSIONS_REQUEST_CODE)
          {
              if(grantResults[0]==PackageManager.PERMISSION_GRANTED &amp;&amp; grantResults[1]==PackageManager.PERMISSION_GRANTED){
  
              Toast.makeText(MainActivity.this," granted "+grantResults[0]+"granted2"+grantResults[1], Toast.LENGTH_SHORT).show();
  
  
              location = locationManager.getLastKnownLocation(provider);}
  
          }
  
      }
  
  }
  </code></pre>
  
  <p>I am still getting an error "Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with <code>checkPermission</code>) or explicitly handle a potential <code>SecurityException</code>
  in <code>onRequestPermissionsResult</code>   on line <code>location = locationManager.getLastKnownLocation(provider);</code></p>