본문 바로가기

나의 플랫폼/안드로이드

[Android] image-chooser-library FileUriExposedException

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

앱에서 카메라나 이미지 파일 접근을 할 때 아래 Library를 사용하시는 분들이 있으실 겁니다.


https://github.com/coomar2841/image-chooser-library


위 라이브러리를 사용했는데 아래와 같은 에러가 발생 할 경우가 있습니다.


 FileUriExposedException: android.os.FileUriExposedException: file:///storage/emulated/0/AppName/AppName%20Pictures/061aafec-0acd-488d-b8b0-c7d5fb8c152a.jpg exposed beyond app through ClipData.Item.getUri()


위와 같이 FileUriExposedException  에러가 발생 한다.

어떻게 해야할까??


우선 원인을 Android sdk가 업데이트 되면서 Camera 부분에서 변경이 되었기 때문이다.

MediaStore.EXTRA_OUTPUT 을 통하여 저장할 파일을 지정해줘야 한다.


이 소스를 수정하기 위해선 라이브러리를 다운 받아야 한다.

즉, gradle이 아닌 오픈 소스로 다운 받으세요.


그 다음 ImageChooserManager 클래스를 아래와 같이 변경 하시면 됩니다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package -//-
 
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
 
import com.kbeanie.imagechooser.api.BChooser;
import com.kbeanie.imagechooser.api.ChosenImage;
import com.kbeanie.imagechooser.api.ChosenImages;
import com.kbeanie.imagechooser.api.ImageChooserListener;
import com.kbeanie.imagechooser.exceptions.ChooserException;
import com.kbeanie.imagechooser.threads.ImageProcessorListener;
import com.kbeanie.imagechooser.threads.ImageProcessorThread;
 
import java.util.ArrayList;
 
 
public class ImageChooserManagerFix extends BChooser implements ImageProcessorListener {
    private static final String TAG = com.kbeanie.imagechooser.api.ImageChooserManager.class.getSimpleName();
    private ImageChooserListener listener;
    private Uri cameraTempUri; // Capture 할 파일 URI 저장 변수
 
    public ImageChooserManagerFix(Activity activity, int type) {
        super(activity, type, true);
    }
 
    public ImageChooserManagerFix(Fragment fragment, int type) {
        super(fragment, type, true);
    }
 
    public ImageChooserManagerFix(android.app.Fragment fragment, int type) {
        super(fragment, type, true);
    }
 
    /**
     * @deprecated
     */
    @Deprecated
    public ImageChooserManagerFix(Activity activity, int type, String folderName) {
        super(activity, type, folderName, true);
    }
 
    /**
     * @deprecated
     */
    @Deprecated
    public ImageChooserManagerFix(Fragment fragment, int type, String folderName) {
        super(fragment, type, folderName, true);
    }
 
    /**
     * @deprecated
     */
    @Deprecated
    public ImageChooserManagerFix(android.app.Fragment fragment, int type, String folderName) {
        super(fragment, type, folderName, true);
    }
 
    public ImageChooserManagerFix(Activity activity, int type, boolean shouldCreateThumbnails) {
        super(activity, type, shouldCreateThumbnails);
    }
 
    public ImageChooserManagerFix(Fragment fragment, int type, boolean shouldCreateThumbnails) {
        super(fragment, type, shouldCreateThumbnails);
    }
 
    public ImageChooserManagerFix(android.app.Fragment fragment, int type, boolean shouldCreateThumbnails) {
        super(fragment, type, shouldCreateThumbnails);
    }
 
    /**
     * @deprecated
     */
    @Deprecated
    public ImageChooserManagerFix(Activity activity, int type, String foldername, boolean shouldCreateThumbnails) {
        super(activity, type, foldername, shouldCreateThumbnails);
    }
 
    /**
     * @deprecated
     */
    @Deprecated
    public ImageChooserManagerFix(Fragment fragment, int type, String foldername, boolean shouldCreateThumbnails) {
        super(fragment, type, foldername, shouldCreateThumbnails);
    }
 
    /**
     * @deprecated
     */
    @Deprecated
    public ImageChooserManagerFix(android.app.Fragment fragment, int type, String foldername, boolean shouldCreateThumbnails) {
        super(fragment, type, foldername, shouldCreateThumbnails);
    }
 
    public void setImageChooserListener(ImageChooserListener listener) {
        this.listener = listener;
    }
 
    public String choose() throws ChooserException {
        String path = null;
        if (this.listener == null) {
            throw new ChooserException("ImageChooserListener cannot be null. Forgot to set ImageChooserListener???");
        } else {
            switch (this.type) {
                case 291:
                    this.choosePicture();
                    break;
                case 294:
                    path = this.takePicture();
                    break;
                default:
                    throw new ChooserException("Cannot choose a video in ImageChooserManager");
            }
 
            return path;
        }
    }
 
    private void choosePicture() throws ChooserException {
        this.checkDirectory();
 
        try {
            Intent e = new Intent("android.intent.action.GET_CONTENT");
            e.setType("image/*");
            if (this.extras != null) {
                e.putExtras(this.extras);
            }
 
            e.addFlags(1);
            this.startActivity(e);
        } catch (ActivityNotFoundException var2) {
            throw new ChooserException(var2);
        }
    }
 
// Take Picture 함수를 아래와 같이 변경
    private String takePicture() throws ChooserException {
        this.checkDirectory();
 
        try {
            Intent e = new Intent("android.media.action.IMAGE_CAPTURE");
 
            ContentValues values = new ContentValues(1);
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
 
            cameraTempUri = getContext().getContentResolver()
                    .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            if (cameraTempUri == null) {
                throw new ActivityNotFoundException();
            }
 
// 여기서 URI의 string아닌 filepath를 받아야 합니다.
// 위 Real Path를 받아오는 소스 입니다. 참고 하세요.
            this.filePathOriginal = cameraTempUri.toString();
            e.putExtra("output", cameraTempUri);
            if (this.extras != null) {
                e.putExtras(this.extras);
            }
 
            this.startActivity(e);
        } catch (ActivityNotFoundException var2) {
            throw new ChooserException(var2);
        }
 
        return this.filePathOriginal;
    }
 
    public void submit(int requestCode, Intent data) {
        try {
            if (requestCode != this.type) {
                this.onError("onActivityResult requestCode is different from the type the chooser was initialized with.");
            } else {
                switch (requestCode) {
                    case 291:
                    case 294:
                        this.processImageFromGallery(data);
                        break;
                }
            }
        } catch (Exception var4) {
            this.onError(var4.getMessage());
        }
 
    }
 
    @SuppressLint({"NewApi"})
    private void processImageFromGallery(Intent data) {
        if (cameraTempUri != null || (data != null && data.getDataString() != null)) {
            Uri uri = cameraTempUri != null ? cameraTempUri : data.getData();
            String var7 = uri.toString();
            this.sanitizeURI(var7);
            if (this.filePathOriginal != null && !TextUtils.isEmpty(this.filePathOriginal)) {
                String var10 = this.filePathOriginal;
                ImageProcessorThread var11 = new ImageProcessorThread(var10, this.foldername, this.shouldCreateThumbnails);
                var11.clearOldFiles(this.clearOldFiles);
                var11.setListener(this);
                var11.setContext(this.getContext());
                var11.start();
            } else {
                this.onError("File path was null");
            }
        } else if (data != null && data.getClipData() == null && !data.hasExtra("uris")) {
            this.onError("Image Uri was null!");
        } else if (data != null) {
            String[] filePaths;
            int count;
            if (data.hasExtra("uris")) {
                ArrayList var8 = data.getParcelableArrayListExtra("uris");
                filePaths = new String[var8.size()];
 
                for (count = 0; count < var8.size(); ++count) {
                    filePaths[count] = ((Uri) var8.get(count)).toString();
                }
            } else {
                ClipData thread = data.getClipData();
                count = thread.getItemCount();
                filePaths = new String[count];
 
                for (int i = 0; i < count; ++i) {
                    ClipData.Item item = thread.getItemAt(i);
                    Log.i(TAG, "processImageFromGallery: Item: " + item.getUri());
                    filePaths[i] = item.getUri().toString();
                }
            }
 
            ImageProcessorThread var9 = new ImageProcessorThread(filePaths, this.foldername, this.shouldCreateThumbnails);
            var9.clearOldFiles(this.clearOldFiles);
            var9.setListener(this);
            var9.setContext(this.getContext());
            var9.start();
        }
 
    }
 
    public void onProcessedImage(ChosenImage image) {
        if (this.listener != null) {
            this.listener.onImageChosen(image);
        }
 
    }
 
    public void onError(String reason) {
        if (this.listener != null) {
            this.listener.onError(reason);
        }
 
    }
 
    public void onProcessedImages(ChosenImages images) {
        if (this.listener != null) {
            this.listener.onImagesChosen(images);
        }
 
    }
}
 
 
cs


위와 같이 수정 하면 문제 없이 동작 될 것 입니다.


참고 하세요.