我编写了一个从Android设备发送电子邮件的应用程序但是当我尝试发送电子邮件时出现以下异常:
android.os.NetworkOnMainThreadException
为什么会发生这种情况?如何解决?
答案 0 :(得分:7)
哪个SDK版本?如果14岁以上,请参阅this link。
解决方案是
JUST FOR DEBUG
添加这些行
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("");
答案 1 :(得分:1)
此异常表示您尝试在主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
有关详情,请参阅How to fix 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);