我是Android编程的新手,并尝试开发一个简单的应用程序,我尝试使用try catch块发送电子邮件,如下所示:
new Thread(new Runnable() {
public void run() {
try {
GMailSender sender = new GMailSender("username@gmail.com","password");
sender.sendMail("Test mail","This mail has been sent from android app along with attachment","username@gmail.com","Someuser1@gmail.com");
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error",Toast.LENGTH_LONG).show();
}
}
}).start();
从上面的代码中,当电子邮件发送失败时,我会使用toast显示错误。 但现在我想知道如果邮件发送成功,我需要显示吐司
这是我尝试过但应用程序崩溃而无法显示任何吐司
new Thread(new Runnable() {
public void run() {
try {
GMailSender sender = new GMailSender("username@gmail.com","password");
sender.sendMail("Test mail","This mail has been sent from android app along with attachment","username@gmail.com","Someuser1@gmail.com");
Toast.makeText(getApplicationContext(), "Success",Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error",Toast.LENGTH_LONG).show();
}
}
}).start();
任何人都可以指导正确的方法来实现我的目标。
答案 0 :(得分:9)
使用以下代码显示吐司将ui相关内容放在UI线程
中runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(), "Error",Toast.LENGTH_LONG).show();
}
});
答案 1 :(得分:0)
只是让 Viswanath Lekshmanan 对Android新手做出更清晰的回答
try{
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(), "Success Message",Toast.LENGTH_LONG).show();
}
});
}catch() {
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(), "Error Message",Toast.LENGTH_LONG).show();
}
});
}