Sending Email from an Android app is not difficult if you want to open up another Email App that handles sending the Email. We can just achi...

Sending Email from an Android app is not difficult if you want to open up another Email App that handles sending the Email. We can just achieve that by adding an ACTION_SEND intent and we can also set content type and use extras such as EXTRA_EMAIL, EXTRA_CC and more. If we start this intent, all the apps that can handle emails such as Gmail app, default Email app will be shown in a chooser dialog if you haven't chosen a default already. Then your user can easily manage the creation and sending of the email from the third party app. But that's not always the case, some times we are required to send an Email from our own App with a fixed Email address to a specific Email address, for example if we need to send a password recovery link on the click of Forgot Password, recovery link to the user should be sent by email from within our app with our own Email Address. In this post we will learn how we can send Email directly from an Android App without and Intent. So let us begin.

sending-emails-directly-from-app
Screenshot of final App of this tutorial

Steps in sending Email from Android App directly without Intent: 

 

  • We require 3 jar libraries for allowing us to send Emails, download the three libraries (LINK BELOW)
  • We create a JSSEProvider class.
  • We create a MailSender class that handles Authentication for our Email and sends Email directly without intent.
So now that we have the steps laid out, let's dig deeper on how to send Email Directly form our App, here's a sample video of the Email app that we will create:


Step 1
First of all download the 3 files- Activation.jarAdditional.jarMail.jar.
These are libraries that allow us to send Email in Java.
Once you've downloaded theses files, put it in the libs folder inside your app directory. If you don't have a libs folder inside your app folder, create one and place these files inside the folder.

Step 2
Now that you've copied the files in libs directory, it's time to include those libraries as dependencies. You'll need to do some changes in the app level Gradle file.  Add the following lines in you dependencies section:

compile files('libs/activation.jar')
compile files('libs/additional.jar')
compile files('libs/mail.jar')

Now you are done with libraries part and are ready to code the Email Sender App.

Step 3
Create a new class called JSSEProvider it should extend Provider class. JSSE provides a framework and an implementation for the SSL and TLS security and also provides some other functionalities like encryption and more. You can learn more about it here. Now add the following code in the class. Import all the required classes:


public JSSEProvider() {
        super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
        AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
            public Void run() {
                put("SSLContext.TLS",
                        "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
                put("Alg.Alias.SSLContext.TLSv1", "TLS");
                put("KeyManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
                put("TrustManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
                return null;
            }
        });
}
 


Step 4
Create a class that extends javax.mail.Authentication. I've called it Gmail Sender because I'll be sending Email from one of my Gmail account. Now add the following code in the class:

 private String mailhost = "smtp.gmail.com";
    private String user;
    private String password;
    private Session session;

    static {
        Security.addProvider(new JSSEProvider());
    }

    public GMailSender(String user, String password) {
        this.user = user;
        this.password = password;

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", mailhost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");

        session = Session.getDefaultInstance(props, this);
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }

    public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
        try{
            MimeMessage message = new MimeMessage(session);
            DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
            message.setSender(new InternetAddress(sender));
            message.setSubject(subject);
            message.setDataHandler(handler);
            if (recipients.indexOf(',') > 0)
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
            else
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
            Transport.send(message);
        }catch(Exception e){
            Log.d("mylog", "Error in sending: " + e.toString());
        }
    }

    public class ByteArrayDataSource implements DataSource {
        private byte[] data;
        private String type;

        public ByteArrayDataSource(byte[] data, String type) {
            super();
            this.data = data;
            this.type = type;
        }

        public ByteArrayDataSource(byte[] data) {
            super();
            this.data = data;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getContentType() {
            if (type == null)
                return "application/octet-stream";
            else
                return type;
        }

        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(data);
        }

        public String getName() {
            return "ByteArrayDataSource";
        }

        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Not Supported");
        }
    } 

Now we have all the required this are we are ready to send Email from our app. We will just create one method in our Activity and call it whenever we need to send the Email to the User. This method will contain your Email Address, your password so you can be authenticated and the email address of your recipient. Let's call this methods sendMessage():

private void sendMessage() {
        final ProgressDialog dialog = new ProgressDialog(ActivityMain.this);
        dialog.setTitle("Sending Email");
        dialog.setMessage("Please wait");
        dialog.show();
        Thread sender = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    GMailSender sender = new GMailSender("youremail", "yourpassword");
                    sender.sendMail("EmailSender App",
                            "This is the message body",
                            "youremail",
                            "your recipient's email");
                    dialog.dismiss();
                } catch (Exception e) {
                    Log.e("mylog", "Error: " + e.getMessage());
                }
            }
        });
        sender.start();
    } 

Finally we have our app ready and we can call this method whenever we need to send the Email directly from the app without any intents. You can find the full source code below, Cheers!

NOTEGmail has disabled logging in to accounts by third party apps. You need to disable this feature of Gmail and allow logging in from any app otherwise you won't be able to login and Emails won't be sent from your account.

Full source code for Email Sender App:

OkHttp Android Initially Android had only two HTTP clients:  HttpURLConnection  and  Apache HTTP Client ; for sending and receiving data fro...

OkHttp Android

Initially Android had only two HTTP clients: HttpURLConnection and Apache HTTP Client; for sending and receiving data from the web. Each of these clients required a lot of boilerplate code to be written inside the AsyncTask or the background thread methods. Moreover, these clients have their own sets of limitations when it came to cancelling an HTTP request or connection-pooling.
okhttp android example tutorial
OkHttp android provides an implementation of HttpURLConnection and Apache Client interfaces by working directly on a top of java Socket without using any extra dependencies.

OkHttp Android Advantages

Some advantages that OkHttp brings to us are:
  1. Connection pooling
  2. Gziping
  3. Caching
  4. Recovering from network problems
  5. Redirects
  6. Retries
  7. Support for synchronous and asynchronous calls

Synchronous vs Asynchronous calls

  • Synchronous calls require an AsyncTask wrapper around it. That means it doesn’t support cancelling a request. Also, AsyncTasks generally leak the Activity’s context, which is not preferred.
  • Asynchronous Calling is the recommneded way since it supports native cancelling, tagging multiple requests and canceling them all with a single method call (by invoking the cancel on the Acitivty instance inside the onPause or onDestroy method).
Before we look into the implementation of OkHttp android, add the following dependency

compile 'com.squareup.okhttp3:okhttp:3.4.1'
Add the permission for internet inside the AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET"/>

OkHttp Android Example Code

The MainActivity.java for Synchronous Calls is given below.

package com.neo-istone.okhttp;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

OkHttpClient client = new OkHttpClient();

TextView txtString;

public String url= "https://reqres.in/api/users/2";


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

txtString= (TextView)findViewById(R.id.txtString);

OkHttpHandler okHttpHandler= new OkHttpHandler();
okHttpHandler.execute(url);
}

public class OkHttpHandler extends AsyncTask {

OkHttpClient client = new OkHttpClient();

@Override
protected String doInBackground(String...params) {

Request.Builder builder = new Request.Builder();
builder.url(params[0]);
Request request = builder.build();

try {
Response response = client.newCall(request).execute();
return response.body().string();
}catch (Exception e){
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
txtString.setText(s);
}
}

}
For Asynchronous Calls the MainActivity.java should be defined as:

package com.neo-istone.okhttp;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

TextView txtString;
public String url= "https://reqres.in/api/users/2";

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

txtString= (TextView)findViewById(R.id.txtString);

try {
run();
} catch (IOException e) {
e.printStackTrace();
}
}

void run() throws IOException {

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
.url(url)
.build();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
}

@Override
public void onResponse(Call call, Response response) throws IOException {

final String myResponse = response.body().string();

MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
txtString.setText(myResponse);
}
});

}
});
}

}
We’ve used a test API from here.
The response string returned is of the JSON format that gets printed on the screen.
You can try out other open source API’s like Github API, Stackoverflow etc.

OkHttp Query Parameters Example

If there are any query parameters we can easily pass them using an HttpUrl.Builder class.

HttpUrl.Builder urlBuilder = HttpUrl.parse("https://httpbin.org/get).newBuilder();
urlBuilder.addQueryParameter("
website", "www.journaldev.com");
urlBuilder.addQueryParameter("
tutorials", "android");
String url = urlBuilder.build().toString();

Request request = new Request.Builder()
.url(url)
.build();
The above url was obtained from https://resttesttest.com/.

OkHttp Android Headers Example

If there are any authenticated query parameters, they can be added in the form of headers as shown below:

Request request = new Request.Builder()
.header("Authorization", "replace this text with your token")
.url("
your api url")
.build();

Processing the JSON Response

We can parse the JSON data to get the relevant params and display them in a TextView as below code.

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
}

@Override
public void onResponse(Call call, Response response) throws IOException {

final String myResponse = response.body().string();

MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
try {

JSONObject json = new JSONObject(myResponse);
txtString.setText(json.getJSONObject("data").getString("first_name")+ " "+json.getJSONObject("data").getString("last_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});

}
});

OkHttp Android POST Example

Up until now, we’ve looked at getting a response by calling a few API’s. To post a data to the server we need to build our request in the following way.

public class MainActivity extends AppCompatActivity {

public String postUrl= "https://reqres.in/api/users/";
public String postBody="{\n" +
" \"name\": \"morpheus\",\n" +
" \"job\": \"leader\"\n" +
"}";

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

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

try {
postRequest(postUrl,postBody);
} catch (IOException e) {
e.printStackTrace();
}
}

void postRequest(String postUrl,String postBody) throws IOException {

OkHttpClient client = new OkHttpClient();

RequestBody body = RequestBody.create(JSON, postBody);

Request request = new Request.Builder()
.url(postUrl)
.post(body)
.build();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
}

@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("TAG",response.body().string());
}
});
}
}
In the above code, we’ve used the MediaType class that’s a part of OkHttp to define the type of data being passed. We’ve used the test API URL from https://reqres.in/.
The post(RequestBody body) method is called on the RequestBuilder with the relevant value.
The Log displays the following response.
{"name":"morpheus","job":"leader","id":"731","createdAt":"2017-01-03T17:26:05.158Z"}.
OkHttp is the recommend HttpClient that’s used inside the Retrofit Networking Library. We’ll look into this in the next tutorial.
We’ve added three buttons in the layout to invoke each of the methods, postRequest(), run() and the AsyncTask wrapper class.
You can download the final Android OkHttp Project from the link below.

In this tutorial, we will learn how to implement Draggable (drag and drop) layout using  RearrangeableLayout  library in Android Application...





In this tutorial, we will learn how to implement Draggable (drag and drop) layout using RearrangeableLayout library in Android Application through simple example.

Draggable Layout is special type of user interface whose elements can be dragged with in the layout. We can rearrange the position of elements of layout by dragging them manually. To drag an element, just press over the element and move it from one position to another without dropping the element.
In this tutorial, we will implement Draggable layout using RearrangeableLayout library through a simple example in Android Application.

Step 2

Create New Project

Create a new Project in Android Studio, goto File ⇒ New ⇒ New Projects.

Step 3

Download Library

To implement Draggable layout, we need to add RearrangeableLayout library in the project. So, download the RearrangeableLayout library

Step 4

Add RearrangeableLayout library

Unzip the downloaded file into project directory. Open build.gradle file and add RearrangeableLayout as a dependency. Use the following code to add library:
1
2
3
4
5
dependencies {
  ....
    compile project(':library')
  ....
}

Step 5

Create Layout

To implement draggable layout, we need to add com.rajasharan.layout.RearrangeableLayout in our layout file. Also, add few widget such as Button and TextView widget within the scope of the RearrangeableLayout to test draggable functionality. So, open your activity_main.xml file and the following code snippet in there to create a draggable user interface.
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
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;
    android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;
    android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;
    android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;
    tools:context=&quot;app.rearrangeablelayout.MainActivity&quot;&gt;
    &lt;com.rajasharan.layout.RearrangeableLayout
        xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
        xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
        android:id=&quot;@+id/rearrangeable_layout&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        android:clipToPadding=&quot;false&quot;
        app:outlineWidth=&quot;2dp&quot;
        app:outlineColor=&quot;#00FFFF&quot;
        app:selectionAlpha=&quot;0.5&quot;
        app:selectionZoom=&quot;1.2&quot;&gt;
        &lt;!-- add child views with `android:id` attr to
         save position during orientation change --&gt;
        &lt;TextView
            android:id=&quot;@+id/texview&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;Sample Demo&quot;
            android:textSize=&quot;30sp&quot;
            android:background=&quot;@android:color/darker_gray&quot;
            android:layout_margin=&quot;15dp&quot; /&gt;
        &lt;TextView
            android:id=&quot;@+id/textview2&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;Sample Demo with very large text that will overflow in width&quot;
            android:textSize=&quot;30sp&quot;
            android:background=&quot;@android:color/holo_green_light&quot;/&gt;
        &lt;Button
            android:id=&quot;@+id/button&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;Button&quot;
            android:textSize=&quot;30sp&quot;
            android:layout_margin=&quot;15dp&quot;/&gt;
        &lt;TextView
            android:id=&quot;@+id/textview3&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;Sample&quot;
            android:textSize=&quot;15sp&quot;
            android:background=&quot;@android:color/holo_orange_light&quot;
            android:layout_margin=&quot;15dp&quot;/&gt;
    &lt;/com.rajasharan.layout.RearrangeableLayout&gt;
&lt;/RelativeLayout&gt;

draggable layout

Step 6

Initialize the RearrangeableLayout object

We need to initialize RearrangeLayout object and use its instance to get updated child view while its dragged.
1
2
3
4
5
6
7
8
9
10
11
12
13
public class MainActivity extends AppCompatActivity {
    private static final String TAG = &quot;MainActivity&quot;;
    private RearrangeableLayout root;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // initialize the RearrangeableLayout object
        root = (RearrangeableLayout) findViewById(R.id.rearrangeable_layout);
    }
}

Step 7

Add Child View Position Listener

Next, we need to receive updated position of a child view after child view is dragged. To do so, we will implement position listeners to listen on the child view position changes. RearrangeLayout library has methods to track element’s movement. So, create a method, named childPosiitonListener() and set position listener on layout instance using setChildPositionListener() method and pass ChildPositionListener object to it. ChildPositionListener has a method named onChildMehtod()which provides new and old position of the element. Override onChildMethod to use the position coordinates of dragged element.
Here is the code snippet for the same :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
 *  Added a ChildPositionListener to the root layout to receive
 *  position of child view whenever any child view is dragged
 */
public void childPosiitonListener(){
    root.setChildPositionListener(new RearrangeableLayout.ChildPositionListener() {
        @Override
        public void onChildMoved(View childView, Rect oldPosition, Rect newPosition) {
            Log.e(TAG, childView.toString());
            Log.e(TAG, oldPosition.toString() + &quot; -&gt; &quot; + newPosition.toString());
        }
   });
}

Step 8

Add PreDraw Listener

We can also get the position of child view while  it is being dragged from one position to the other. To receive updated position of child view while it is being dragged, we need to add addOnPreDrawListener to the root layout. So, create a method, named preDrawListener() and call addOnPreDrawListener() method to listen on the drag event on the child view while its dragged from one position to another. Here is the code snippet for the same :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 *  Added a PreviewListener to the root layout to receive update during
 *  child view is dragging
 */
public void preDrawListener(){
    root.getViewTreeObserver()
           .addOnPreDrawListener(new
             ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            Log.e(TAG, &quot;onPrepreview&quot;);
            Log.e(TAG, root.toString());
            return true;
        }
    });
}

Step 9

Final code

Here is the final code of the MainActivity.java file
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
public class MainActivity extends AppCompatActivity {
    private static final String TAG = &quot;MainActivity&quot;;
    private RearrangeableLayout root;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // initialize the RearrangeableLayout object
        root = (RearrangeableLayout) findViewById(R.id.rearrangeable_layout);
        // callback method to call childPositionListener() method
        childPosiitonListener();
        // callback method to call preDrawListener() method
        preDrawListener();
    }
    /**
     *  Added a ChildPositionListener to the root layout to receive
     *  position of child view whenever any child view is dragged
     */
    public void childPosiitonListener(){
        root.setChildPositionListener(new RearrangeableLayout.ChildPositionListener() {
            @Override
            public void onChildMoved(View childView, Rect oldPosition, Rect newPosition) {
                Log.e(TAG, childView.toString());
                Log.e(TAG, oldPosition.toString() + &quot; -&gt; &quot; + newPosition.toString());
            }
        });
    }
    /**
     *  Added a PreviewListener to the root layout to receive update during
     *  child view is dragging
     */
    public void preDrawListener(){
        root.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                Log.e(TAG, &quot;onPrepreview&quot;);
                Log.e(TAG, root.toString());
                return true;
            }
        });
    }
}