Programing

조각에서 권한을 확인하는 방법

lottogame 2020. 11. 19. 07:48
반응형

조각에서 권한을 확인하는 방법


조각 내에서 권한을 확인하고 싶습니다.

내 코드 :

        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {


            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    android.Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {

                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        1);



                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }

하지만 onRequestPermissionsResult허용하거나 거부 이후에 호출되지 않습니다.

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            Log.e("test","0");
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

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

                Log.e("test","1");

                Intent intent = new Intent(getActivity(), MapsActivity.class);
                intent.putExtra("latitude", 35.694828);
                intent.putExtra("longitude", 51.378129);
                startActivity(intent);

            } else {
                utilityFunctions.showSweetAlertWarning(getActivity(),r.getString(R.string.str_warning_title_empty),
                        r.getString(R.string.str_you_must_allow_this_permission_toast),
                        r.getString(R.string.str_warning_btn_login));

                Log.e("test","2");
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

조각 내부의 권한을 확인하기 위해 다음을 수행했습니다.

if (ActivityCompat.checkSelfPermission(getContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(getContext(),
                    android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
         requestPermissions(getActivity(),
                new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
                        android.Manifest.permission.ACCESS_FINE_LOCATION},
                REQUEST_LOCATION);
    } else {
        Log.e("DB", "PERMISSION GRANTED");
    }

이것이 제가 한 방식이며 저에게 효과적입니다. 감사!

활동 :

ActivityCompat.requestPermissions(this, permissionsList, REQUEST_CODE);

조각의 경우 :

requestPermissions(permissionsList, REQUEST_CODE);

조각에는 방법 requestPermissions()onRequestPermissionsResult()방법이 있습니다.

그러나 checkSelfPermission()에서 왔습니다 ActivityCompat(필요하지 않고 ActivityContext).

if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    requestPermissions( //Method of Fragment
        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
        REQUEST_PERMISSIONS_CODE_WRITE_STORAGE
    );
} else {
    downloadImage();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == REQUEST_PERMISSIONS_CODE_WRITE_STORAGE) {
        if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            proceedWithSdCard();
        }
    }
}

onRequestPermissionsResult조각이 아닌 활동에서 호출됩니다. onRequestPermissionsResult대신 활동에서 재정의하십시오 .


Kotlin을 사용 requestPermissions(arrayOf(Manifest.permission.THE_PERMISSION_CODE_YOU_WANT), PERMISSION_REQUEST_CODE)하여 다음 재정의를 호출 하고 조각에 추가합니다.

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out kotlin.String>, grantResults: IntArray): Unit {

}

설정에서 앱의 권한을 닫은 경우 코드 또는 Marshmallow보다 낮은 Android 버전에서 권한을 열 수 없습니다.

You can check this documentation https://developer.android.com/training/permissions/requesting.html And this is a example https://www.learn2crack.com/2015/10/android-marshmallow-permissions.html


What worked for me was calling the onRequestPermissionsResult method in the activity inside which fragment is implemented rather than calling it in fragment itself. Inside onCreateView method in fragment:

    Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int permissionCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);

            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_MEDIA);
            }else{
                //Do your work
                fetchMethod();
            }

        }
});

In the Activity which helps to implement fragment, outside of onCreate method:

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

            }else{
                Toast.makeText(getApplicationContext(), "Permission not granted!", Toast.LENGTH_SHORT).show();
            }
            break;

        default:
            break;
    }
}

To handle permissions in a Fragment call requestPermissions method. If you override onRequestPermissionsResult method in both fragment and activity, containing that fragment, make sure to call super.onRequestPermissionsResult(...) in the activity method to propagate call to the onRequestPermissionsResult method in the fragment.

참고URL : https://stackoverflow.com/questions/40760625/how-to-check-permission-in-fragment

반응형