Android - Elegir imagen y compartirla en Gmail.

 
Vista:
sin imagen de perfil
Val: 2
Ha disminuido su posición en 2 puestos en Android (en relación al último mes)
Gráfica de Android

Elegir imagen y compartirla en Gmail.

Publicado por Mauro (2 intervenciones) el 25/10/2018 14:40:11
Buen día.
Estoy intentando realizar una aplicacion que permita seleccionar una imagen (de la galeria o cualquier lugar en donde haya imagenes) y enviarla por Gmail.
Estuve buscando por todos lados pero no consigo lograr mandar la imagen, mandar solo texto es sencillo...pero con la imagen se complica.
Les adjunto un codigo que creo que es el que más posibilidades tiene de andar. No es de mi propiedad, a continuacion dejo el link del creador. https://www.javacodegeeks.com/2013/10/send-email-with-attachment-in-android.html


Main
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
/**
 *
 * @author manish
 *
 */
public class MainActivity extends Activity implements OnClickListener {
 
    EditText editTextEmail, editTextSubject, editTextMessage;
    Button btnSend, btnAttachment;
    String email, subject, message, attachmentFile;
    Uri URI = null;
    private static final int PICK_FROM_GALLERY = 101;
    int columnIndex;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editTextEmail = (EditText) findViewById(R.id.editTextTo);
        editTextSubject = (EditText) findViewById(R.id.editTextSubject);
        editTextMessage = (EditText) findViewById(R.id.editTextMessage);
        btnAttachment = (Button) findViewById(R.id.buttonAttachment);
        btnSend = (Button) findViewById(R.id.buttonSend);
 
        btnSend.setOnClickListener(this);
        btnAttachment.setOnClickListener(this);
    }
 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
            /**
             * Get Path
             */
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
 
            Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
            cursor.moveToFirst();
            columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            attachmentFile = cursor.getString(columnIndex);
            Log.e("Attachment Path:", attachmentFile);
            URI = Uri.parse("file://" + attachmentFile);
            cursor.close();
        }
    }
 
    @Override
    public void onClick(View v) {
 
        if (v == btnAttachment) {
            openGallery();
 
        }
        if (v == btnSend) {
            try {
                email = editTextEmail.getText().toString();
                subject = editTextSubject.getText().toString();
                message = editTextMessage.getText().toString();
 
                final Intent emailIntent = new Intent(
                        android.content.Intent.ACTION_SEND);
                emailIntent.setType("plain/text");
                emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                        new String[] { email });
                emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                        subject);
                if (URI != null) {
                    emailIntent.putExtra(Intent.EXTRA_STREAM, URI);
                }
                emailIntent
                        .putExtra(android.content.Intent.EXTRA_TEXT, message);
                this.startActivity(Intent.createChooser(emailIntent,
                        "Sending email..."));
 
            } catch (Throwable t) {
                Toast.makeText(this,
                        "Request failed try again: " + t.toString(),
                        Toast.LENGTH_LONG).show();
            }
        }
 
    }
 
    public void openGallery() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.putExtra("return-data", true);
        startActivityForResult(
                Intent.createChooser(intent, "Complete action using"),
                PICK_FROM_GALLERY);

    }

}


Main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        android:padding="5dp" >
 
        <EditText
            android:id="@+id/editTextTo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_margin="5dp"
            android:hint="Email Address!"
            android:inputType="textEmailAddress"
            android:singleLine="true" />
 
        <EditText
            android:id="@+id/editTextSubject"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/editTextTo"
            android:layout_margin="5dp"
            android:hint="Subject"
            android:singleLine="true" />
 
        <EditText
            android:id="@+id/editTextMessage"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_below="@id/editTextSubject"
            android:layout_margin="5dp"
            android:gravity="top|left"
            android:hint="type message here!"
            android:inputType="textMultiLine" />
 
        <Button
            android:id="@+id/buttonSend"
            android:layout_width="80dp"
            android:layout_height="50dp"
            android:layout_below="@id/editTextMessage"
            android:layout_margin="5dp"
            android:text="Send" />
 
        <Button
            android:id="@+id/buttonAttachment"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:text="attachment" />
    </RelativeLayout>
</android.support.constraint.ConstraintLayout>

permisos en el manifiesto
1
2
3
4
5
<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Este codigo deberia realizar todo lo que deseo, pero al seleccionar la imagen me da un error, creo que es porque no esta obteniendo la direccion del archivo correctamente.
Les agradeceria si alguno me puede dar una mano con esto, o facilitarme alguna manera de enviar imagenes por gmail.
Gracias, espero sus respuestas.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Dionicio
Val: 6
Ha aumentado su posición en 22 puestos en Android (en relación al último mes)
Gráfica de Android

Elegir imagen y compartirla en Gmail.

Publicado por Dionicio (2 intervenciones) el 31/10/2018 21:48:07
Tienes que tomar en cuenta la versión de android en la cuál pruebas la aplicación, ya que a partir de Android 6.0 y superiores hay que usar un FileProvaider o proveedor de Archivos para realizar acciones que requieren de la compartición de contenido. Más que nada esto es por cuestiones de seguridad. Me pasó ya una vez, así que quizás sea la solución a tu problema.

Puedes ver este ejemplo para guiarte

Un saludo.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar