본문 바로가기
개발/Android

[안드로이드 앱 개발] 외부에 이미지 공유하기 (java)

by 즐거운 개발 인생 2022. 2. 9.
728x90
반응형

[안드로이드 앱 개발] 외부에 이미지 공유하기 (java)

[android app develop] android share image to other app

카카오톡에 이미지 공유하기


Manifest에 외부 저장소 접근 권한 및 provier 작성

Declare external storage access and provier in Manifest

//manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application>
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="your app package name"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
            
    </provider>
</application>

외부 저장소 경로 설정

external storage path setting

file paths 경로

//file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="files" path="."/>
    <external-files-path name="external_files_path" path="." />
    <external-path name="external_files" path="."/>

</paths>

공유 아이콘 눌러 이미지 외부 앱에 공유

share image to external app

****** 주의사항 : 외부 앱에 이미지를 공유할때는 해당 이미지 파일이 외부 저장소에 저장된 파일이여야 외부 앱에서 파일에 접근이 가능하다! (공유 사진 폴더와 같은 외부 저장소에 있는 이미지 파일이여야 한다. 내부 저장소에 저장된 이미지는 백날 해도 전달 할 수 없다)

caution : when you share image file to external apps, image file must was saved in external storage!

(like public picture folder)

//Imageview share = findViewById(R.id.share)
share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            //현재 화면을 이미지 파일로 저장하기 위한 작업
                rootView.layout(0, 0, rootView.getMeasuredWidth(), rootView.getMeasuredHeight());
                rootView.buildDrawingCache();

                Bitmap bitmap = Bitmap.createBitmap(rootView.getMeasuredWidth(), rootView.getMeasuredHeight(),
                        Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(bitmap);
                rootView.draw(canvas);

                String fileName = getString(R.string.app_name) + System.currentTimeMillis() + ".jpeg";
               
               //외부 저장소에 이미지 파일 저장하기
                File file = Utils.saveImageIntoFileFromUri(getApplicationContext(), bitmap, fileName, Utils.getExternalFilePath(getApplicationContext()));
               
               //다른 앱에 이미지 공유하기
               Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);

                Uri photoURI = FileProvider.getUriForFile(getApplicationContext(),
                        getApplicationContext().getPackageName(),
                        file);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, photoURI);
                    shareIntent.setType("image/jpg");
                    startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
            }
        });

외부 저장소 경로

get external file path

//외부 저장소 경로
//get external file path
public static String getExternalFilePath(Context context) {
    String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +"/";
    return filePath;
}

외부 저장소에 파일 저장하기

save file to external storage

//외부 저장소에 파일 저장하기
//save file to external storage
public static File saveImageIntoFileFromUri(Context context, Bitmap bitmap, String fileName, String path) {
    File file = new File(path, fileName);

    try {
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        switch(file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".") + 1)){
            case "jpeg":
            case "jpg":
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                break;
            case "png":
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
                break;
        }

        fileOutputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.e("Utils","saveImageIntoFileFromUri FileNotFoundException : "+ e.toString());
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("Utils","saveImageIntoFileFromUri IOException : "+ e.toString());
    }
    return file;
}

 

파일 저장되는 외부 저장소 위치

 

728x90
반응형

댓글