Android

(์•ˆ๋“œ๋กœ์ด๋“œ ์ŠคํŠœ๋””์˜ค) ์นด๋ฉ”๋ผ ์ดฌ์˜ ์‚ฌ์ง„ ์—…๋กœ๋“œ ๊ถŒํ•œ ์„ค์ •, ์ด๋ฏธ์ง€ ์—…๋กœ๋“œํ•˜๋Š” ๊ธฐ๋Šฅ ๋งŒ๋“ค๊ธฐ

567Rabbit 2024. 6. 14. 17:33

fileprovider.xml ํŒŒ์ผ ์ƒ์„ฑ ํ›„ ์ž‘์„ฑ

 

 

 

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <root-path
        name="root"
        path="." />

    <cache-path
        name="cache"
        path="." /> <!--Context.getCacheDir() ๋‚ด๋ถ€ ์ €์žฅ์†Œ-->
    <files-path
        name="files"
        path="." /> <!--Context.getFilesDir() ๋‚ด๋ถ€ ์ €์žฅ์†Œ-->

    <external-path
        name="external"
        path="."/>  <!--  Environment.getExternalStorageDirectory() ์™ธ๋ถ€ ์ €์žฅ์†Œ-->
    <external-cache-path
        name="external-cache"
        path="."/> <!--  Context.getExternalCacheDir() ์™ธ๋ถ€ ์ €์žฅ์†Œ-->
    <external-files-path
        name="images"
        path="Pictures" /> <!--  Context.getExternalFilesDir() ์™ธ๋ถ€ ์ €์žฅ์†Œ-->
</paths>

 

 

 

 

 

AndroidManifest.xml ์„ค์ •

 

<uses-feature android:name="android.hardware.camera" android:required="true"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

 

 

 

๊ฒ€์ •์ƒ‰์œผ๋กœ ์ง€์šด ๋ถ€๋ถ„์€, ์ž๋™์™„์„ฑ ๋  ๊ฒƒ์ด๋‹ค.

 

 

<provider
    android:authorities="com.~.cameraapp.fileprovider"
    android:name="androidx.core.content.FileProvider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/fileprovider"/>
</provider>

 

 

 

 

 

๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์„ค์น˜

 

build.gradle.kts(:app) ์—์„œ, ๋งจ ์•„๋žซ์ค„ ์ž‘์„ฑ.

 

 

Sync now ํ•ด์ฃผ๊ธฐ.

 

 

 

 

 

activity_main.xml ์ž‘์„ฑํ•˜๊ธฐ

 

 

 

 

 

strings.xml ์ž‘์„ฑํ•˜๊ธฐ

 

resource -> strings.xml ์—์„œ ์ž‘์„ฑํ•ด์ค€๋‹ค. (alert-Dialog๋Š” ํŒ์—…์ฐฝ์ด๋‹ค.)

 

 

 

 

 

 

MainActivity.java

 

์ฝ”๋“œ ๋ฐ‘๋ถ€๋ถ„์˜ ํฌ์ŠคํŒ… ๊ธ€๊นŒ์ง€ ๋๊นŒ์ง€ ์ฐธ๊ณ ํ•ด์•ผ ํ•œ๋‹ค.

package com.~.cameraapp;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.Manifest;



public class MainActivity extends AppCompatActivity {

    Button button;
    ImageView imageView;

    File photoFile;

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

        button = findViewById(R.id.button);
        imageView = findViewById(R.id.imageView);

        // ๋ฒ„ํŠผ ๋ˆ„๋ฅด๋ฉด, ์นด๋ฉ”๋ผ๋กœ ์ฐ์„๊ฒƒ์ธ์ง€, ์•จ๋ฒ”์—์„œ ๊ณ ๋ฅผ๊ฒƒ์ธ์ง€์— ๋Œ€ํ•œ
        // ์•Œ๋ŸฌํŠธ ๋‹ค์ด์–ผ๋กœ๊ทธ ๋„์šด๋‹ค.

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog();
            }
        });
    }

    private void showDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(R.string.alert_title);
        builder.setItems(R.array.alert_photo, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if(i == 0){
                    // ์ฒซ๋ฒˆ์งธ ํ•ญ๋ชฉ ๋ˆŒ๋ €์„๋•Œ
                    // ์นด๋ฉ”๋ผ๋กœ ์‚ฌ์ง„์ฐ๊ธฐ
                    camera();

                }else if(i == 1){
                    // ๋‘๋ฒˆ์งธ ํ•ญ๋ชฉ ๋ˆŒ๋ €์„๋•Œ
                    album();
                }
            }
        });
        builder.show();
    }


    private void camera(){
        int permissionCheck = ContextCompat.checkSelfPermission(
                MainActivity.this, Manifest.permission.CAMERA);

        if(permissionCheck != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{android.Manifest.permission.CAMERA} ,
                    1000);
            Toast.makeText(MainActivity.this, "์นด๋ฉ”๋ผ ๊ถŒํ•œ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.",
                    Toast.LENGTH_SHORT).show();
            return;
        } else {
            Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if(i.resolveActivity(MainActivity.this.getPackageManager())  != null  ){

                // ์‚ฌ์ง„์˜ ํŒŒ์ผ๋ช…์„ ๋งŒ๋“ค๊ธฐ
                String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                photoFile = getPhotoFile(fileName);


                // ๊ผญ ์ˆ˜์ •ํ•ด์ค˜์•ผ ํ•  ๋ถ€๋ถ„!!!!!!
                Uri fileProvider = FileProvider.getUriForFile(MainActivity.this,
                        "com.~.cameraapp.fileprovider", photoFile);
                i.putExtra(MediaStore.EXTRA_OUTPUT, fileProvider);
                startActivityForResult(i, 100);

            } else{
                Toast.makeText(MainActivity.this, "์ดํฐ์—๋Š” ์นด๋ฉ”๋ผ ์•ฑ์ด ์—†์Šต๋‹ˆ๋‹ค.",
                        Toast.LENGTH_SHORT).show();
            }
        }


    }

    private void album(){
        if(checkPermission()){
            displayFileChoose();
        }else{
            requestPermission();
        }
    }

    private boolean checkPermission(){
        int result = ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if(result == PackageManager.PERMISSION_DENIED){
            return false;
        }else{
            return true;
        }
    }

    private void requestPermission() {
        if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            Log.i("DEBUGGING5", "true");
            Toast.makeText(MainActivity.this, "๊ถŒํ•œ ์ˆ˜๋ฝ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.",
                    Toast.LENGTH_SHORT).show();
        }else{
            Log.i("DEBUGGING6", "false");
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 500);
        }
    }

    private void displayFileChoose() {
        Intent i = new Intent();
        i.setType("image/*");
        i.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(i, "SELECT IMAGE"), 300);
    }

    private File getPhotoFile(String fileName) {
        File storageDirectory = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        try{
            return File.createTempFile(fileName, ".jpg", storageDirectory);
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1000: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "๊ถŒํ•œ ํ—ˆ๊ฐ€ ๋˜์—ˆ์Œ",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "์•„์ง ์Šน์ธํ•˜์ง€ ์•Š์•˜์Œ",
                            Toast.LENGTH_SHORT).show();
                }
                break;
            }
            case 500: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "๊ถŒํ•œ ํ—ˆ๊ฐ€ ๋˜์—ˆ์Œ",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "์•„์ง ์Šน์ธํ•˜์ง€ ์•Š์•˜์Œ",
                            Toast.LENGTH_SHORT).show();
                }

            }

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == 100 && resultCode == RESULT_OK){

            Bitmap photo = BitmapFactory.decodeFile(photoFile.getAbsolutePath());

            ExifInterface exif = null;
            try {
                exif = new ExifInterface(photoFile.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_UNDEFINED);
            photo = rotateBitmap(photo, orientation);

            // ์••์ถ•์‹œํ‚จ๋‹ค. ํ•ด์ƒ๋„ ๋‚ฎ์ถฐ์„œ
            OutputStream os;
            try {
                os = new FileOutputStream(photoFile);
                photo.compress(Bitmap.CompressFormat.JPEG, 25, os);
                os.flush();
                os.close();
            } catch (Exception e) {
                Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
            }

            photo = BitmapFactory.decodeFile(photoFile.getAbsolutePath());

            imageView.setImageBitmap(photo);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

            // ๋„คํŠธ์›Œํฌ๋กœ ๋ฐ์ดํ„ฐ ๋ณด๋‚ธ๋‹ค.



        }else if(requestCode == 300 && resultCode == RESULT_OK && data != null &&
                data.getData() != null){

            Uri albumUri = data.getData( );
            String fileName = getFileName( albumUri );
            try {

                ParcelFileDescriptor parcelFileDescriptor = getContentResolver( ).openFileDescriptor( albumUri, "r" );
                if ( parcelFileDescriptor == null ) return;
                FileInputStream inputStream = new FileInputStream( parcelFileDescriptor.getFileDescriptor( ) );
                photoFile = new File( this.getCacheDir( ), fileName );
                FileOutputStream outputStream = new FileOutputStream( photoFile );
                IOUtils.copy( inputStream, outputStream );

//                //์ž„์‹œํŒŒ์ผ ์ƒ์„ฑ
//                File file = createImgCacheFile( );
//                String cacheFilePath = file.getAbsolutePath( );


                // ์••์ถ•์‹œํ‚จ๋‹ค. ํ•ด์ƒ๋„ ๋‚ฎ์ถฐ์„œ
                Bitmap photo = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
                OutputStream os;
                try {
                    os = new FileOutputStream(photoFile);
                    photo.compress(Bitmap.CompressFormat.JPEG, 25, os);
                    os.flush();
                    os.close();
                } catch (Exception e) {
                    Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
                }

                imageView.setImageBitmap(photo);
                imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

//                imageView.setImageBitmap( getBitmapAlbum( imageView, albumUri ) );

            } catch ( Exception e ) {
                e.printStackTrace( );
            }

            // ๋„คํŠธ์›Œํฌ๋กœ ๋ณด๋‚ธ๋‹ค.
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //์•จ๋ฒ”์—์„œ ์„ ํƒํ•œ ์‚ฌ์ง„์ด๋ฆ„ ๊ฐ€์ ธ์˜ค๊ธฐ
    public String getFileName( Uri uri ) {
        Cursor cursor = getContentResolver( ).query( uri, null, null, null, null );
        try {
            if ( cursor == null ) return null;
            cursor.moveToFirst( );
            @SuppressLint("Range") String fileName = cursor.getString( cursor.getColumnIndex( OpenableColumns.DISPLAY_NAME ) );
            cursor.close( );
            return fileName;

        } catch ( Exception e ) {
            e.printStackTrace( );
            cursor.close( );
            return null;
        }
    }


    public static Bitmap rotateBitmap(Bitmap bitmap, int orientation) {

        Matrix matrix = new Matrix();
        switch (orientation) {
            case ExifInterface.ORIENTATION_NORMAL:
                return bitmap;
            case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                matrix.setScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.setRotate(180);
                break;
            case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                matrix.setRotate(180);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_TRANSPOSE:
                matrix.setRotate(90);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                matrix.setRotate(90);
                break;
            case ExifInterface.ORIENTATION_TRANSVERSE:
                matrix.setRotate(-90);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                matrix.setRotate(-90);
                break;
            default:
                return bitmap;
        }
        try {
            Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            bitmap.recycle();
            return bmRotated;
        }
        catch (OutOfMemoryError e) {
            e.printStackTrace();
            return null;
        }
    }

}

 

 

 

 

!!!!!! ๊ผญ ์ˆ˜์ •ํ•ด์•ผ ํ•  ๋ถ€๋ถ„ !!!!!  ๋นจ๊ฐ„ ๋ฐ‘์ค„ ์นœ ๋ถ€๋ถ„์„ ๋ฐ”๊ฟ”์ค˜์•ผํ•œ๋‹ค.

 

 

 

 

Manifest์—์„œ ํ˜•๊ด‘ํŽœ ๋ถ€๋ถ„์„ ๋ณต์‚ฌํ•˜์—ฌ ์œ„์˜ ๋นจ๊ฐ„ ๋ฐ‘์ค„ ๋ถ€๋ถ„์— ๋ถ™์—ฌ๋„ฃ๋Š”๋‹ค.