android.os.NetworkOnMainThreadException sending an email from Android

giusy picture giusy · Aug 18, 2013 · Viewed 22.5k times · Source

I have written an application which sends email from an Android device but I get the following exception when I try to send an email:

android.os.NetworkOnMainThreadException

Why is this occurring and how can I fix it?

Answer

venergiac picture venergiac · Aug 18, 2013

Which SDK version? If 14+ see this link.

the solution is

JUST FOR DEBUG

add these rows

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Real Case Put the code on an AsyncTask

private class Connection extends AsyncTask {
    @Override
    protected Object doInBackground(Object... arg0) {

        connect();
        return null;
    }
}

then call

new Connection().execute("");