He tenido varios problemas al intentar generar una aplicación que tome una foto y la muestre dentro de un ImageView
de mi Activity
. Estoy trabajando en API 26
y he notado que mi código falla cuando se ejecuta la siguiente opción:
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(newFile));
Soy realmente nuevo programando en Android
y tengo la duda si es por cómo estoy enviando la Uri
.
Éste es el código.
public class ChangeImg extends AppCompatActivity {
private static String APP_DIRECTORY = "Ahorr-oink/";
private static String MEDIA_DIRECTORY = APP_DIRECTORY + "Img_perfil";
private final int MY_PERMISSIONS = 100;
private final int PHOTO_CODE = 200;
private final int SELECT_PICTURE = 300;
private ImageView mSetImage;
private Button mOptionButton;
private RelativeLayout mRlView;
private String mPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_change_img);
mSetImage = (ImageView) findViewById(R.id.set_picture);
mOptionButton = (Button) findViewById(R.id.show_options_button);
mRlView = (RelativeLayout) findViewById(R.id.rl_view);
if(mayRequestStoragePermission())
mOptionButton.setEnabled(true);
else
mOptionButton.setEnabled(false);
mOptionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showOptions();
}
});
}
private boolean mayRequestStoragePermission() {
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
return true;
if((checkSelfPermission(WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) &&
(checkSelfPermission(CAMERA) == PackageManager.PERMISSION_GRANTED))
return true;
if((shouldShowRequestPermissionRationale(WRITE_EXTERNAL_STORAGE)) || (shouldShowRequestPermissionRationale(CAMERA))){
Snackbar.make(mRlView, "Los permisos son necesarios para poder usar la aplicación",
Snackbar.LENGTH_INDEFINITE).setAction(android.R.string.ok, new View.OnClickListener() {
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onClick(View v) {
requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE, CAMERA}, MY_PERMISSIONS);
}
});
}else{
requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE, CAMERA}, MY_PERMISSIONS);
}
return false;
}
private void showOptions() {
final CharSequence[] option = {"Tomar foto", "Elegir de galeria", "Cancelar"};
final AlertDialog.Builder builder = new AlertDialog.Builder(ChangeImg.this);
builder.setTitle("Elige una opción");
builder.setItems(option, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(option[which] == "Tomar foto"){
openCamera();
}else if(option[which] == "Elegir de galeria"){
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent, "Selecciona app de imagen"), SELECT_PICTURE);
}else {
dialog.dismiss();
}
}
});
builder.show();
}
private void openCamera() {
final File file = new File(Environment.getExternalStorageDirectory(), MEDIA_DIRECTORY);
boolean isDirectoryCreated = file.exists();
if(!isDirectoryCreated)
isDirectoryCreated = file.mkdirs();
if(isDirectoryCreated){
Long timestamp = System.currentTimeMillis() / 1000;
final String imageName = timestamp.toString() + ".jpg";
mPath = Environment.getExternalStorageDirectory() + File.separator + MEDIA_DIRECTORY
+ File.separator + imageName;
final File newFile = new File(mPath);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(newFile));
startActivityForResult(intent, PHOTO_CODE);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("file_path", mPath);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mPath = savedInstanceState.getString("file_path");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
switch (requestCode){
case PHOTO_CODE:
MediaScannerConnection.scanFile(this,
new String[]{mPath}, null,
new MediaScannerConnection.OnScanCompletedListener() {
@Override
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> Uri = " + uri);
}
});
Bitmap bitmap = BitmapFactory.decodeFile(mPath);
mSetImage.setImageBitmap(bitmap);
break;
case SELECT_PICTURE:
Uri path = data.getData();
mSetImage.setImageURI(path);
break;
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == MY_PERMISSIONS){
if(grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(ChangeImg.this, "Permisos aceptados", Toast.LENGTH_SHORT).show();
mOptionButton.setEnabled(true);
}
}else{
showExplanation();
}
}
private void showExplanation() {
AlertDialog.Builder builder = new AlertDialog.Builder(ChangeImg.this);
builder.setTitle("Permisos denegados");
builder.setMessage("Para usar las funciones de la app necesitas aceptar los permisos");
builder.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
});
builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
builder.show();
}
}
XML
:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:id="@+id/rl_view"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".ChangeImg">
<Button
android:id="@+id/show_options_button"
android:layout_width="80dp"
android:layout_height="80dp"
android:text="Foto"
android:layout_centerHorizontal="true"/>
<ImageView
android:id="@+id/set_picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:contentDescription="@string/contentDescriptionImagenSet"
android:layout_below="@+id/show_options_button"/>
</RelativeLayout>
En el Manifest agregué los siguiente permisos:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<protected-broadcast android:name="android.intent.action.MEDIA_MOUNTED"/>