如何在doInBackground中的AsyncTask中显示吐司

问题描述 投票:13回答:9

在我的一项活动中,我正在使用AsyncTask。在doInBackground()中,我正在调用各种方法。在这些方法之一中,我遇到了异常,因此在catch块中,我想在Toast中显示错误。我知道我可以使用Log,但我仍然更喜欢Toast。因此,如何在doInBackground()的AsyncTask中使用Toast?

android android-asynctask
9个回答
11
投票

您可以将Toast包装在runOnUIThread()中,但这不是最佳解决方案。发生错误时,应在catch块中设置一个布尔标志,然后在runOnUIThread()onProgressUpdate()或任何其他具有UI访问权限的方法中,只要该标志为onPostExecute(),就显示适当的Toast。


17
投票

从doInBackground返回为

true

6
投票

protected String doInBackground(String... params){ //some code try{ //some code }catch(Exception e){ return "Exception Caught"; } return someValidResult; } protected void onPostExecute(String result){ if(result.equalsIgnoreCase("Exception Caught")){ //Display Toast }else{ // // whatever you wana do with valid result } } 方法中,在必须显示吐司的地方编写以下代码

doInBackground()
  • BTW:如果您正在使用runOnUiThread(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), "Example for Toast", Toast.LENGTH_SHORT).show(); } }); ,则需要通过活动呼叫Fragments

runOnUiThread(...)


3
投票

您可以在可以访问UI线程的方法中显示它,例如getActivity().runOnUiThread(...)onPreExecute()onProgressUpdate()


3
投票

创建处理程序对象并使用该对象执行所有Toast消息。

onPostExecute()

1
投票
@Override
protected Void doInBackground(Void... params) {

    Handler handler=new handler();
    handler=  new Handler(context.getMainLooper());
    handler.post( new Runnable(){
        public void run(){
            Toast.makeText(context, "Created a server socket",Toast.LENGTH_LONG).show(); 
        }
    });
  }

可以很好地在doInBackground()方法中显示烤面包


0
投票
runOnUiThread(new Runnable() {

public void run() {

  Toast.makeText(getApplicationContext(), "Example for Toast", Toast.LENGTH_SHORT).show();

   }
}); 

0
投票

尝试此代码

activity.runOnUiThread(new Runnable() {
 public void run() 
 {
    Toast.makeText(activity, "Toast teaxt", Toast.LENGTH_SHORT).show();
 }
});

0
投票

如果必须声明与Thread相关的任何东西,那么它必须在runOnUiThread()方法之外,然后才将要执行,

void showError(final String err) {
    runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(downloadprogress.this, err + "error in download", Toast.LENGTH_LONG)
                    .show();
        }
    });
  }
© www.soinside.com 2019 - 2024. All rights reserved.