android.os.NetworkOnMainThreadException - 如何解决?[重复]

问题描述 投票:0回答:1

我试图从我的应用程序发送电子邮件。下面是一些代码。

        String text = editText.getText().toString();

        String to = "[email protected]";
        String from = "[email protected]";
        String host = "localhost";
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        Session session = Session.getDefaultInstance(properties);

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("Answer to your feedback");
            message.setText(text);
            Transport.send(message);
        } catch (MessagingException mex){
            mex.printStackTrace();
        }

但是我得到了一个异常:"Cause by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method)


Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater. java:397) at android.View.View.performClick(View.java:7189) at android.View.View.performClickInternal(View.java:7163) at android.View.View.access$3500(View.java:821) at android.View.View$PerformClick. ActivityThread.main(ActivityThread.java:8147) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513) at com.android.internal. os.ZygoteInit.main(ZygoteInit.java:1101) 原因是:在android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565) 在java.net.Inet6AddressImpl. 在java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115) at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103) at java.net.InetAddress.getLocalHost(InetAddress.java:1488) at javax.mail.internet. InternetAddress.getLocalAddress(InternetAddress.java:517) at javax.mail.internet.UniqueValue.getUniqueMessageIDValue(UniqueValue.java:99) at javax.mail.internet.MimeMessage.updateMessageID(MimeMessage. javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2076) at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2042) at javax.mail.Transport.send(Transport.java:117)


没有找到任何有用的东西。我怎样才能解决这个问题?

java android javamail
1个回答
0
投票

正如堆栈告诉你的那样,你在主线程上做了网络连接,这是不可接受的,因为它可能会阻止UI的更新。查看AsyncTask并在那里执行你的代码。

© www.soinside.com 2019 - 2024. All rights reserved.