权限请求在OnResume中导致无限循环

时间:2017-04-28 13:02:50

标签: java android android-permissions

在API> = 23中,我们需要在运行时向用户请求权限。但由于某种原因,权限导致onResume被无限调用。是什么原因造成的?

  @Override
protected void onResume() {
    super.onResume();

     ActivityCompat.requestPermissions(MainActivity.this,
     new String[]{Manifest.permission.ANYPERMISSION},1);       

}

 @Override
public void onRequestPermissionsResult(int requestCode,
         String permissions[], int[] grantResults) {
     }  

3 个答案:

答案 0 :(得分:14)

当您显示权限问题对话框时,Acitvity将转到onPause,当对话框隐藏时,它会转到onResume。你必须改变请求许可的地方。

答案 1 :(得分:1)

用于完成先前响应的权限的一小段代码:)

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (Build.VERSION.SDK_INT >= 23)
        ensurePermissions(
                Manifest.permission.GET_ACCOUNTS,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        );
}

@TargetApi(23)
private void ensurePermissions(String... permissions) {
    boolean request = false;
    for (String permission : permissions)
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            request = true;
            break;
        }

    if (request) {
        requestPermissions(permissions, REQUEST_CODE_PERMISSION);
    }
}

答案 2 :(得分:0)

首先,您的应用需要在询问运行时权限之前检查您是否已被授予特定权限。

 if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    } else {
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
    }