Allow fine location permission to replace fragment

痴心易碎 提交于 2019-12-04 05:51:08

问题


I want to ask user does he want to grant a permission to accces his fine location and only if he grant it I want to replace a fragment and open the locator fragment. In locator fragments there are some stores that user can see based on his location. If he doesn't allow access to fine location I want to show him proper message. This is the code:

else if (id == R.id.nav_locator) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                1);
        fragment = new LocatorFragment();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.fragmentlayout, fragment);
        ft.commit();

Application is currently crashing because it will instantly start to replace fragment and it will crash because it replace before the user choose to approve or not approve location.

So basically i need some loop idea or something that will ignore user request if he choose not to allow permission and show him adequate message. And if he choose to grant then I need to replace fragment like ordinary.


回答1:


Please check below solution, hope it will work properly for you.

 else if (id == R.id.nav_locator) 
 {
    int result = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
   if (result == PackageManager.PERMISSION_GRANTED){

       goToNextFragment();

   } else {

       requestForLocationPermission(); 
   }
 }


   private void requestForLocationPermission()
   {

      if (ActivityCompat.shouldShowRequestPermissionRationale(activity,Manifest.permission.ACCESS_FINE_LOCATION))
      {
      } 
      else {

          ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},PERMISSION_REQUEST_CODE);
      }
   }

  @Override
  public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) 
  {
      switch (requestCode) {
       case PERMISSION_REQUEST_CODE:
           if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
           goToNextFragment();
        } 
        break;
  }
}


  public void goToNextFragment()
  {
      Fragment fragment = new LocatorFragment();
      FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
      ft.replace(R.id.fragmentlayout, fragment);
      ft.commit();
  }


来源:https://stackoverflow.com/questions/37656898/allow-fine-location-permission-to-replace-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!