android.os.NetworkOnMainThreadException sending an email from Android
本问题已经有最佳答案,请猛点这里访问。
我编写了一个从Android设备发送电子邮件的应用程序,但是当我尝试发送电子邮件时出现以下异常:
为什么会发生这种情况,我该如何解决?
哪个SDK版本? 如果14岁以上,请看这个链接。
解决方案是
只是为了调试
添加这些行
1 2 | StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); |
真实案例
将代码放在AsyncTask上
1 2 3 4 5 6 7 8 | private class Connection extends AsyncTask { @Override protected Object doInBackground(Object... arg0) { connect(); return null; } } |
然后打电话
1 | new Connection().execute(""); |
此异常意味着您尝试在主UI线程上执行与网络相关的操作。 您需要在单独的线程或AsyncTask中执行。
文件说:
1 2 3 4 5 | 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更多。 要获得更多帮助,您可能需要显示更多代码。
就像是:
1 2 3 4 5 6 7 8 9 10 11 12 | 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 } } |
这是执行任务的方法:
1 | new RetreiveFeedTask().execute(urlToRssFeed); |