在try-catch块中显示吐司

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

我是Android编程的新手,并尝试开发一个简单的应用程序,我试图通过使用try catch块发送电子邮件,如下所示:

new Thread(new Runnable() {
public void run() {
    try {       
        GMailSender sender = new GMailSender("[email protected]","password");
            sender.sendMail("Test mail","This mail has been sent from android app along with attachment","[email protected]","[email protected]");
            } 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("[email protected]","password");
                sender.sendMail("Test mail","This mail has been sent from android app along with attachment","[email protected]","[email protected]");
            Toast.makeText(getApplicationContext(), "Success",Toast.LENGTH_LONG).show();
                } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Error",Toast.LENGTH_LONG).show();
            }
        }
    }).start();

任何人都可以指导正确的方法来实现我的目标。

android try-catch toast
2个回答
9
投票

使用下面的代码显示toast将ui相关内容放在UI线程中

runOnUiThread(new Runnable(){
public void run() {
   Toast.makeText(getApplicationContext(), "Error",Toast.LENGTH_LONG).show();
}
});

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();
}
});

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