【问题标题】:Allow fine location permission to replace fragment允许精细位置权限替换片段
【发布时间】:2016-10-06 00:43:08
【问题描述】:

我想问用户他是否要授予访问其精细位置的权限,并且只有当他授予它时,我才想替换片段并打开定位器片段。在定位器片段中,用户可以根据他的位置看到一些商店。如果他不允许访问良好的位置,我想向他展示正确的信息。这是代码:

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

应用程序当前正在崩溃,因为它将立即开始替换片段,并且它将崩溃,因为它在用户选择批准或不批准位置之前替换。

所以基本上我需要一些循环想法或一些东西,如果他选择不允许许可并向他显示足够的信息,它将忽略用户请求。如果他选择授予,那么我需要像普通一样替换片段。

【问题讨论】:

  • 将片段代码移动到onRequestPermissionsResult..!!
  • 我做到了它的工作,但第一次当我授予权限应用程序关闭.O
  • 你的意思是有任何错误,所以应用程序关闭或它只是你的要求关闭应用程序?
  • 当我授予权限时它会自动关闭,然后当我重新启动时它会像魅力一样工作,因为它有权限
  • 请检查您的日志。应该有一些错误。如果可能,请在此处添加您的logcat..!!

标签: android android-fragments android-studio android-permissions


【解决方案1】:

请检查以下解决方案,希望它对您正常工作。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    相关资源
    最近更新 更多