Android: what to choose for requestcode values?

后端 未结 1 1335
一向
一向 2020-12-01 06:17

Methods like ActivityCompat.requestPermissions require that I pass them a requestcode that I can later test in a callback (in this case onRequestPermissio

相关标签:
1条回答
  • 2020-12-01 06:32

    Documenting the findings for future reference:

    The following are code from android.support.v4.app.FragmentActivity

     /**
     * Modifies the standard behavior to allow results to be delivered to fragments.
     * This imposes a restriction that requestCode be <= 0xffff.
     */
    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        if (requestCode != -1 && (requestCode&0xffff0000) != 0) {
            throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
        }
        super.startActivityForResult(intent, requestCode);
    }
    


    @Override
    public final void validateRequestPermissionsRequestCode(int requestCode) {
        // We use 16 bits of the request code to encode the fragment id when
        // requesting permissions from a fragment. Hence, requestPermissions()
        // should validate the code against that but we cannot override it as
        // we can not then call super and also the ActivityCompat would call
        // back to this override. To handle this we use dependency inversion
        // where we are the validator of request codes when requesting
        // permissions in ActivityCompat.
        if (!mRequestedPermissionsFromFragment
                && requestCode != -1 && (requestCode & 0xffff0000) != 0) {
            throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
        }
    }
    


    RANGE
    startActivityForResult() in FragmentActivity requires the requestCode to be of 16 bits, meaning the range is from 0 to 65535.

    Also, validateRequestPermissionsRequestCode in FragmentActivity requires requestCode to be of 16 bits, meaning the range is from 0 to 65535.

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