[android] SecurityException을 던지지 않고 런타임에 권한을 어떻게 확인할 수 있습니까?

SD에서 리소스를 가져 오거나 설정할 수있는 함수를 설계하고 sd에서 찾을 수없는 경우 자산에서 가져와 가능한 경우 자산을 다시 SD에 기록합니다.
이 함수는 SD가 마운트되고 액세스 가능한 경우 메서드 호출로 확인할 수 있습니다.

boolean bSDisAvalaible = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);

내가 디자인 한 기능은 한 앱 (프로젝트)에서 다른 앱 (android.permission.WRITE_EXTERNAL_STORAGE 포함 또는 제외)으로 사용될 수 있습니다.

그런 다음 현재 응용 프로그램에 SecurityException을 사용하지 않고 특정 권한이 있는지 확인하고 싶습니다.

런타임에 현재 정의 된 권한을 참조하는 “좋은”방법이 있습니까?



답변

이를 위해 Context.checkCallingorSelfPermission()기능을 사용할 수 있습니다 . 다음은 그 예입니다.

private boolean checkWriteExternalPermission()
{
    String permission = android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
    int res = getContext().checkCallingOrSelfPermission(permission);
    return (res == PackageManager.PERMISSION_GRANTED);
}


답변

이것은 또 다른 해결책입니다

PackageManager pm = context.getPackageManager();
int hasPerm = pm.checkPermission(
    android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
    context.getPackageName());
if (hasPerm != PackageManager.PERMISSION_GRANTED) {
   // do stuff
}


답변

다음을 사용할 수도 있습니다.

private boolean doesUserHavePermission()
{
    int result = context.checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    return result == PackageManager.PERMISSION_GRANTED;
}


답변

Google 문서 처럼 :

// Assume thisActivity is the current activity
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE);


답변

누군가 필요한 경우 내 방법 공유 :

 /** Determines if the context calling has the required permission
 * @param context - the IPC context
 * @param permissions - The permissions to check
 * @return true if the IPC has the granted permission
 */
public static boolean hasPermission(Context context, String permission) {

    int res = context.checkCallingOrSelfPermission(permission);

    Log.v(TAG, "permission: " + permission + " = \t\t" +
    (res == PackageManager.PERMISSION_GRANTED ? "GRANTED" : "DENIED"));

    return res == PackageManager.PERMISSION_GRANTED;

}

/** Determines if the context calling has the required permissions
 * @param context - the IPC context
 * @param permissions - The permissions to check
 * @return true if the IPC has the granted permission
 */
public static boolean hasPermissions(Context context, String... permissions) {

    boolean hasAllPermissions = true;

    for(String permission : permissions) {
        //you can return false instead of assigning, but by assigning you can log all permission values
        if (! hasPermission(context, permission)) {hasAllPermissions = false; }
    }

    return hasAllPermissions;

}

그리고 그것을 부르기 위해 :

boolean hasAndroidPermissions = SystemUtils.hasPermissions(mContext, new String[] {
                android.Manifest.permission.ACCESS_WIFI_STATE,
                android.Manifest.permission.READ_PHONE_STATE,
                android.Manifest.permission.ACCESS_NETWORK_STATE,
                android.Manifest.permission.INTERNET,
        });


답변

다음과 같은 방법으로 권한을 확인해야합니다 (여기에 설명 된 Android 권한 ).

int result = ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_PHONE_STATE);

그런 다음 결과를 다음 중 하나와 비교하십시오.

result == PackageManager.PERMISSION_DENIED

또는:

result == PackageManager.PERMISSION_GRANTED


답변

1 단계 -권한 요청 추가

    String[] permissionArrays = new String[]{Manifest.permission.CAMERA,
    Manifest.permission.WRITE_EXTERNAL_STORAGE};
    int REQUEST_CODE = 101;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(permissionArrays, REQUEST_CODE );
        } else {
             // if already permition granted
            // PUT YOUR ACTION (Like Open cemara etc..)
        }
    }

2 단계 -권한 결과 처리

     @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    boolean openActivityOnce = true;
    boolean openDialogOnce = true;
    if (requestCode == REQUEST_CODE ) {
        for (int i = 0; i < grantResults.length; i++) {
            String permission = permissions[i];

            isPermitted = grantResults[i] == PackageManager.PERMISSION_GRANTED;

            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                // user rejected the permission

            }else {
                //  user grant the permission
                // you can perfome your action 
            }
        }
    }
}