[Android/Training] 사진을 외부앱으로 전송하기

2023. 5. 9. 21:33Android/튜토리얼 및 가이드

728x90
반응형

1. AndroidManifest.xml 파일에 FileProvider를 등록합니다.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application>
        ...
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.myapp.fileprovider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
        ...
    </application>
</manifest>

2. res/xml/ 폴더에 provider_paths.xml 파일을 생성하고 파일 제공자가 제공할 경로를 지정합니다.

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="cache" path="/" />
    <external-cache-path name="external_cache" path="/" />
    <external-path name="external" path="/" />
</paths>

3. 소스코드

이 코드는 안드로이드 앱에서 이미지를 캡처한 후,

캐시에 저장하고 해당 이미지 파일을 다른 앱으로 공유하는 기능을 구현하고 있습니다.

private void saveToCache(String title, Bitmap bitmap) {
	File storage = getCacheDir();

	try{
		File file = new File(storage, title+".jpg");

		FileOutputStream fos = new FileOutputStream(file);
		bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
		fos.flush();
		fos.close();

		sendAppLink(file);
	} catch (Exception e){
		e.printStackTrace();
		PushController.writeAppLog("Android Log : Error for captureReceipt Share", "IOException e");
	}
}

먼저 캐시 디렉토리를 가져온 다음, 해당 디렉토리에 이미지 파일을 저장합니다.

이 때, 이미지를 JPEG 형식으로 압축하고, 파일명은 title 매개변수에 지정된 값에 .jpg 확장자를 붙인 것을 사용합니다.

 

private void sendAppLink(File imageFile) {
	Uri photoURI = FileProvider.getUriForFile(getApplicationContext(),
			getApplicationContext().getPackageName()+".fileprovider",
			imageFile);

	Intent shareIntent = new Intent();

	shareIntent.setAction(Intent.ACTION_SEND);
	shareIntent.setType("image/jpg");
	shareIntent.putExtra(Intent.EXTRA_STREAM, photoURI);

	startActivity(Intent.createChooser(shareIntent, "test"));
}

FileProvider를 사용하여 imageFile 매개변수에 전달된 파일을 공유합니다.

이 때, getApplicationContext().getPackageName()+".fileprovider"를 인자로 전달하여 FileProvider 객체를 생성하고,

생성된 Uri 객체를 Intent.EXTRA_STREAM에 추가하여 Intent.ACTION_SEND 액션을 수행합니다.

마지막으로, createChooser 메서드를 사용하여 여러 앱 중에서 어떤 앱으로 이미지를 전송할지 선택할 수 있도록 합니다.

728x90
반응형