Android

FileProvider 사용법

aucd29 2017. 2. 15. 13:35

어제 폰을 누가로 업그레이드 한 이후에 확인차 CAMERA Intent 를 호출했더니 오류 발생 ..

찾아보니 누가 (API24) 부터는 외부 앱과 파일 연동을 임의로 사용할 수 없고 FileProvider 를 통해서만 처리하도록 변경되었다.


관련글들을 수집 하였고 코드만 수정하면 되었는데 두번째 링크를 기준으로 생성하기로 하고 작업 했다. 

https://developer.android.com/training/secure-file-sharing/setup-sharing.html

https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en

http://stackoverflow.com/questions/1910608/android-action-image-capture-intent


일단 버전 별로 Uri 를 얻는 방법을 다르게 하고 

public static Uri fromFile(@NonNull Context context, @NonNull File file) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

        return FileProvider.getUriForFile(context, AUTH, file);

    }


    return Uri.fromFile(file);

}


Uri 정보에서 실제 파일 경로를 얻는 방법을 생성했다. 

public static String getFilePath(@NonNull Uri uri) {

    if (CONTENT.equals(uri.getScheme())) {

        return getFileNameFromUri(uri);

    }


    return PathUtils.stripFileProtocol(uri.toString());

}


private static String getFileNameFromUri(@NonNull Uri uri) {

    String fullUri      = uri.toString();

    String partialPath  = fullUri.split(EXTERNAL_FILES)[1];

    File extStorage     = Environment.getExternalStorageDirectory();


    return extStorage.getAbsolutePath() + partialPath;

}


만들라는 provider_paths.xml 을 하나 만들고 

<?xml version="1.0" encoding="utf-8"?>

<paths xmlns:android="http://schemas.android.com/apk/res/android">

    <external-path name="external_files" path="." />

</paths>


카메라를 호출 할 때 플래그를 추가해주고


Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

}


완료 ~