1

我正在尝试找到一种从线程内部调用 MessageBox 的方法。但是我发现的每一段代码/示例都不起作用。有人可以用尽可能少的代码行以最简单和最简单的方式详细说明解决方案/示例吗?

到目前为止,这是我的代码:

public class MainActivity extends Activity {

    void MessageBox(String msg){
        AlertDialog deleteAlert = new AlertDialog.Builder(this).create();
        deleteAlert.setTitle("This is the title");
        deleteAlert.setMessage(msg);
        deleteAlert.show();
    }

    Button b1;
    TextView tv1;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        b1 = (Button) findViewById(R.id.button1);
        tv1 = (TextView) findViewById(R.id.editText1);

        b1.setOnClickListener(new OnClickListener(){
            public void onClick(View arg0) {
                MyRunnable myRunnable = new MyRunnable();
                Thread myThread = new Thread(myRunnable);
                myThread.setDaemon(true);
                myThread.start();
            }   
        });

        MainActivity.this.runOnUiThread(new Runnable() {
            public void run() {
                MessageBox("This is a message");
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

class MyRunnable implements Runnable{

    Socket Client;
    public void run() {
        try {
            Client = new Socket("192.168.1.20", 3333);
            //MessageBox
        } catch (UnknownHostException e) {
            //MessageBox
        } catch (IOException e) {
            //MessageBox
        }
    }
}
4

1 回答 1

1

使用runOnUiThread在线程内调用 MessageBox。作为 :

//your code here....
Socket Client;
public void run() {
 try {
     Client = new Socket("192.168.1.20", 3333);
     showMessage("Yout MessageBox message here");
    } catch (UnknownHostException e) {
      showMessage("Yout MessageBox message here");
   } catch (IOException e) {
     showMessage("Yout MessageBox message here");
 }

public void showMessage(String message){
  MainActivity.this.runOnUiThread(new Runnable() {
   public void run() {
       // show MessageBox here 
     }
   });
}
于 2013-01-09T16:34:38.540 回答