Permission Requests causes infinite loop in OnResume

前端 未结 3 1934
春和景丽
春和景丽 2021-01-17 12:21

In API >= 23, we are required to ask users for permission at run-time. But for some reason, the permissions are causing onResume to be called infinitely. What causes this?

相关标签:
3条回答
  • 2021-01-17 12:36

    first, your app needs to check whether you have been granted a particular permission before asking runtime permission.

     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);
        }
    
    0 讨论(0)
  • 2021-01-17 12:49

    A small piece of code for permissions to complete previous response :)

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

    and:

    @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);
        }
    }
    
    0 讨论(0)
  • 2021-01-17 12:54

    When you show dialog of permission question, Acitvity goes to onPause, and when dialog hides, it goes to onResume. You have to change place of asking of permission.

    0 讨论(0)
提交回复
热议问题