本文介绍了允许精细位置权限来替换片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问用户他是否要授予访问其精细位置的权限,并且只有在他授予该权限后,我才想替换一个片段并打开定位器片段.在定位器片段中,用户可以根据自己的位置看到一些商店.如果他不允许访问精确的位置,我想向他显示正确的消息.这是代码:

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.

推荐答案

请检查以下解决方案,希望它能为您正常工作.

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();
  }

这篇关于允许精细位置权限来替换片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 04:57