이코드는 버튼을 클릭 시
사진찍기와 갤러리 불러오기에 대한 선택지를 주고 선택지에 따라
사진찍기 - > 카메라 열기
갤러리 불러오기 -> 나의 갤러리 불러오기
등을 사용할 수 있다.
package com.jhn.googlemaptest;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
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.hardware.Camera;
import android.media.ExifInterface;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
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.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class ResultActivity extends AppCompatActivity {
TextView txt1;
TextView txt2;
Button button;
ImageView imgPhoto;
String imgpath;
public static final int REQ_REGISTER_CHECK = 101;
public static final int REQ_LOGIN_CHECK = 102;
public static final int REQ_PHOTO_CAPTURE = 103;
public static final int REQ_PHOTO_SELECTION = 104;
Uri uri;
File file;
private ProgressDialog progressDialog;
String[] permissions = {
Manifest.permission.INTERNET,
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
};
private File photoFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
txt1 = findViewById(R.id.txt1);
txt2 = findViewById(R.id.txt2);
button = findViewById(R.id.button);
imgPhoto = findViewById(R.id.imgPhoto);
Intent intent = getIntent();
long duration = intent.getExtras().getLong("duration");
txt1.setText("이용시간 : " + (duration / 60000) + "분");
txt2.setText("이용금액 : " + (duration / 60000) * 200 + "원");
// 권한확인
if (!hasPermissions(this)) ActivityCompat.requestPermissions(this, permissions, 1);
// 사진촬영하기 버튼
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDialog();
}
});
}
private void camera(){
int permissionCheck = ContextCompat.checkSelfPermission(
ResultActivity.this, Manifest.permission.CAMERA);
if(permissionCheck != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(ResultActivity.this,
new String[]{Manifest.permission.CAMERA} ,
1000);
Toast.makeText(ResultActivity.this, "카메라 권한 필요합니다.",
Toast.LENGTH_SHORT).show();
return;
} else {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(i.resolveActivity(ResultActivity.this.getPackageManager()) != null ){
// 사진의 파일명을 만들기
String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
photoFile = getPhotoFile(fileName);
Uri fileProvider = FileProvider.getUriForFile(ResultActivity.this,
"com.jhn.googlemaptest.fileprovider", photoFile);
i.putExtra(MediaStore.EXTRA_OUTPUT, fileProvider);
startActivityForResult(i, 100);
} else{
Toast.makeText(ResultActivity.this, "이폰에는 카메라 앱이 없습니다.",
Toast.LENGTH_SHORT).show();
}
}
}
private void album(){
if(checkPermission()){
displayFileChoose();
}else{
requestPermission();
}
}
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;
}
}
private boolean checkPermission(){
int result = ContextCompat.checkSelfPermission(ResultActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(result == PackageManager.PERMISSION_DENIED){
return false;
}else{
return true;
}
}
private void displayFileChoose() {
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i, "SELECT IMAGE"), 300);
}
private void requestPermission() {
if(ActivityCompat.shouldShowRequestPermissionRationale(ResultActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(ResultActivity.this, "권한 수락이 필요합니다.",
Toast.LENGTH_SHORT).show();
}else{
ActivityCompat.requestPermissions(ResultActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 500);
}
}
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1000: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(ResultActivity.this, "권한 허가 되었음",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ResultActivity.this, "아직 승인하지 않았음",
Toast.LENGTH_SHORT).show();
}
break;
}
case 500: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(ResultActivity.this, "권한 허가 되었음",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ResultActivity.this, "아직 승인하지 않았음",
Toast.LENGTH_SHORT).show();
}
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
public boolean hasPermissions(Context context) {
if (context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
private void getPermission(){
ActivityCompat.requestPermissions(this, permissions, 1000);
}
/* 사진 찍기 메서드 */
public void showPhotoCaptureActivity(){
try {
file = createFile();
if (file.exists()){
file.delete();
}
file.createNewFile();
}catch (Exception e){
Log.e("createFile Err: ", e.getMessage());
}
// SDK 버전에 따른 파일 경로 설정
if (Build.VERSION.SDK_INT >= 24){
uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID, file);
}else {
uri = Uri.fromFile(file);
}
// 사진촬영
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, REQ_PHOTO_CAPTURE);
this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
Toast.makeText(this, "Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri ->" + uri, Toast.LENGTH_LONG).show();
} // showPhotoCaptureActivity() END
/* 이미지 파일 생성 메서드 */
public File createFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
imgpath = image.getAbsolutePath();
return image;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable 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, 50, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
// Intent intent = new Intent(ResultActivity.this, ResultphotoActivity.class);
// intent.putExtra("type", "camera");
// intent.putExtra("filePath", photoFile.getAbsolutePath());
// startActivity(intent);
}else if(requestCode == 300 && resultCode == RESULT_OK && data != null &&
data.getData() != null){
Uri albumUri = data.getData( );
// Intent intent = new Intent(ResultActivity.this, ResultphotoActivity.class);
// intent.putExtra("type", "album");
// intent.putExtra("imageUri", albumUri.toString());
// startActivity(intent);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void showProgress(String message) {
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage(message);
progressDialog.show();
}
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;
}
}
private void dismissProgress() {
progressDialog.dismiss();
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(ResultActivity.this);
builder.setTitle("선택하세요").setItems(R.array.camera_array, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
// 카메라로 사진찍는 함수 실행
camera();
} else if (i == 1) {
// 앨범에서 사진 가져오는 함수 실행
album();
}
}
}); AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
'프론트엔드 > 안드로이드 스튜디오' 카테고리의 다른 글
안드로이드 스튜디오 : 사진 찍으면 S3에 저장하기 / 갤러리에 사진을 S3에 저장하기 (0) | 2022.03.16 |
---|---|
안드로이드 스튜디오 : Multipart 이미지 전송하기 / 여러 데이터 전송하기 /@Part MultipartBody.Part (0) | 2022.03.16 |
안드로이드 스듀디오 : Intent 를 이용하여 다른 클래스에 string,int 보내기 (0) | 2022.03.15 |
안드로이드 스튜디오 : 시간 분 두자리 수 / mm 분 보이게 하기 (0) | 2022.03.15 |
안드로이드 스튜디오 : TimePicker 로 가져온 시간 , 현재 시간 / 타임 피커/ 두 시간 차 계산 / 두 시간 차이 / 두 시간 빼기 (0) | 2022.03.15 |