android.os.NetworkOnMainThreadException从Android发送电子邮件

这个问题在这里已经有了答案:

  • 我该如何解决android.os.NetworkOnMainThreadException? 48个答案

  • 哪个SDK版本? 如果14+看到这个链接。

    解决方案是

    只是为了调试

    添加这些行

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

    真实案例将代码放在AsyncTask上

    private class Connection extends AsyncTask {
        @Override
        protected Object doInBackground(Object... arg0) {
    
            connect();
            return null;
        }
    }
    

    然后打电话

    new Connection().execute("");
    

    此异常意味着您正尝试在主UI线程上执行网络相关操作。 您需要在单独的线程中或在AsyncTask中执行。

    该文件说:

    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
    

    请参阅如何解决android.os.NetworkOnMainThreadException? 和Android - android.os.NetworkOnMainThreadException更多。 为获得更多帮助,您可能需要展示更多代码。

    就像是:

    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
        }
    }
    

    这是如何执行任务:

    new RetreiveFeedTask().execute(urlToRssFeed);
    
    链接地址: http://www.djcxy.com/p/5021.html

    上一篇: android.os.NetworkOnMainThreadException sending an email from Android

    下一篇: Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley