How to display a Toast inside a Handler/thread?

笑着哭i 提交于 2019-12-21 04:46:08

问题


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

Whether I need to create a separate thread to display 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;
        }
    }
}

}


回答1:


put

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

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

after this line

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



回答2:


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



回答3:


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 man between 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 :

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



回答4:


Declare a global Handler first,

Handler handler=null;

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

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.");"

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.



来源:https://stackoverflow.com/questions/10610962/how-to-display-a-toast-inside-a-handler-thread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!