onRequestPermissionResult的switch case上的常量表达式需要错误

时间:2018-01-02 17:04:22

标签: android android-permissions

我正在写一个简单的代码来询问位置访问

 private static int MY_PERMISSIONS_REQUEST_LOCATION = 99;

 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    myview = inflater.inflate(R.layout.add_device,container,false);

    // fragment manager for passing values
    final FragmentManager fragmentManager = getFragmentManager();

    // checking location permission and asking for permission
    int permissionCheck = ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.ACCESS_FINE_LOCATION);
    if(permissionCheck != 0){
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
    }

当我调用onRequestPermissionsResult函数并在请求代码上应用switch case时,编译器会显示错误'所需的常量表达式'

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch(requestCode){
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }
    }
}

可能是什么问题? 请注意,oncreateview完全复制到此处

1 个答案:

答案 0 :(得分:1)

MY_PERMISSIONS_REQUEST_LOCATION成为最终版,您的问题将得到解决:

private static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

案例声明中,必须始终具有最终价值。