Android 如何在处理程序/线程中显示 Toast?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10610962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:21:25  来源:igfitidea点击:

How to display a Toast inside a Handler/thread?

androidtoast

提问by Shan

I want to display a toast once the message is sent to a socket.After this "Log.d("ClientActivity", "C: Sent.");"

一旦消息发送到套接字,我想显示一个祝酒词。在此之后“Log.d(“ClientActivity”,“C: Sent.”);”

Whether I need to create a separate thread to display Toast?

我是否需要创建一个单独的线程来显示 Toast?

public class ClientActivity extends Activity {
private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.client);
    serverIp = (EditText) findViewById(R.id.EditText01);
    message =(EditText) findViewById(R.id.EditText02);
    connectPhones = (Button) findViewById(R.id.Button01);

}

    public void Click1(View v) {
        if (!connected) {
            serverIpAddress = serverIp.getText().toString();
            if (!serverIpAddress.equals("")) {
                Thread cThread = new Thread(new ClientThread());
                cThread.start();
            }
        }
    }


private class ClientThread implements Runnable {

    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            Log.d("ClientActivity", "C: Connecting...");
            Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
            connected = true;
            while (connected) {
                try {
                    if(i>5)
                    {


                    } 
                    else
                    {   
                        Log.d("ClientActivity", "C: Sending command.");
                        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                .getOutputStream())), true);
                        // where you issue the commands
                        message1= message.getText().toString();
                        out.println(message1);
                        i=i+1;
                        Log.d("ClientActivity", "C: Sent.");
                    }    
                } catch (Exception e) {
                    Log.e("ClientActivity", "S: Error", e);
                }
            }
            socket.close();
            Log.d("ClientActivity", "C: Closed.");
        } catch (Exception e) {
            Log.e("ClientActivity", "C: Error", e);
            connected = false;
        }
    }
}

}

}

回答by 5hssba

put

  runOnUiThread(new Runnable() {
                 public void run() {

                     Toast.makeText(ClientActivity.this,"asdf",Toast.LENGTH_LONG).show();
                }
            });

after this line

在这一行之后

  Log.d("ClientActivity", "C: Connecting...");

回答by itechDroid

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        System.out.println("I'm in handler");
        Toast.makeText(YourActivity.this, "This is a toast", Toast.LENGTH_SHORT).show(); 
    }
}, 1000);             

回答by Ashwin

You cannot create a toast from inside a thread. Because this new thread does not have access to the getApplicationContext()that you pass on to it. You somehow have to establesh a communication with the UI thread(i.e the main thread).
So whenever you want to toast something do it in the handler.Post(Runnable)method. Handler is the middle manbetween the UI thread and the separate thread that you are running. All UI Operations will have to be done in handler.Post(Runnable)'s run()method.

So in your activity to display a toast do this :

您不能从线程内部创建吐司。因为这个新线程无法访问getApplicationContext()您传递给它的 。您必须以某种方式与 UI 线程(即主线程)建立通信。
因此,无论何时您想敬酒,都可以在handler.Post(Runnable)方法中进行。处理程序middle man位于 UI 线程和您正在运行的单独线程之间。所有 UI 操作都必须在handler.Post(Runnable)'srun()方法中完成。

因此,在您的活动中显示祝酒词,请执行以下操作:

private class ClientThread implements Runnable {

    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
             .....
             .....
              message1= message.getText().toString();
                        out.println(message1);
                        i=i+1;
                        Log.d("ClientActivity", "C: Sent.");
                        handler.post(new Runnable(){
                          public void run()
                          {
                             Toast.make(....);
                           }
                         });

Don't forget to declare and initialize a handler object in your main activity(outside the thread)

不要忘记在主活动中(线程外)声明和初始化处理程序对象

handler=new Handler();

回答by Andro Selva

Declare a global Handler first,

先声明一个全局的Handler,

Handler handler=null;

Then Create a handler in your onCreate() like this,

然后像这样在你的 onCreate() 中创建一个处理程序,

Handler handler=new Handler()
{
  public void handleMessage(Message msg)
{
  if(msg.what==0)
{
   Toast.makeText(ClientActivity.this,"Your Toast Mesage Goes here",Toast.LENGTH_LONG).show();
}

}
};

And now in your Runnable class add this line after "Log.d("ClientActivity", "C: Sent.");"

现在在您的 Runnable 类中添加此行 "Log.d("ClientActivity", "C: Sent.");"

handler.sendEmptyMessage(0);

The problem you are facing is because you can't update UI from runnable. Handlers connect you to your main UI. So you have to pass a message to your handler from your Runnable.

您面临的问题是因为您无法从 runnable 更新 UI。处理程序将您连接到您的主 UI。因此,您必须将消息从 Runnable 传递给您的处理程序。