在 try-catch 块中显示吐司 [英] Show toast within try-catch block

查看:38
本文介绍了在 try-catch 块中显示吐司的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to android programming and trying to develop a simple app where I am trying to send email by using a try catch block as shown below:

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 显示了一个错误.但是现在我想知道如果邮件发送成功我需要显示toast

From the above code when the email sending is failed I get an error displayed using toast. But Now I would like to know If the mail is sent successfully I need to display the toast

这是我尝试过的,但应用程序崩溃了,无法显示任何吐司

This is what I have tried but the app is getting crashed and unable to display any 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();

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

can anyone guide to the right way of doing this to achieve my goal.

推荐答案

使用下面的代码展示toast把ui相关的内容放到UI线程中

Use the below code to show toast put the ui related contents within UI thread

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

这篇关于在 try-catch 块中显示吐司的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆