android.os.NetworkOnMainThreadException sending an email from Android [duplicate]

心已入冬 提交于 2019-11-26 21:44:56

问题


This question already has an answer here:

  • How do I fix 'android.os.NetworkOnMainThreadException'? 55 answers

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?


回答1:


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("");



回答2:


This exception means that you are trying to do Network related operation on the main UI thread. You need to do either in a seperate thread or in AsyncTask.

The documentation says that:

The exception that is thrown when an application attempts to perform a 
networking operation on its main thread. This is only thrown for applications 
targeting the Honeycomb SDK or higher. Applications targeting earlier SDK 
versions are allowed to do networking on their main event loop threads, but it's 
heavily discouraged

See How to fix android.os.NetworkOnMainThreadException? and Android - android.os.NetworkOnMainThreadException for more. For getting more help you might need to show more code.

Something like:

class RetreiveFeedTask extends AsyncTask<String, Void, Void> {


    protected Void doInBackground(String... urls) {
        //Execurte the network related option here
    }

    protected void onPostExecute(Void param) {

        // TODO: do something with the feed
    }
}

This is how to execute the task:

new RetreiveFeedTask().execute(urlToRssFeed);


来源:https://stackoverflow.com/questions/18297485/android-os-networkonmainthreadexception-sending-an-email-from-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!