在线程内部调用MessageBox

时间:2013-01-09 16:29:59

标签: java android

我试图找到一种从线程内部调用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
        }
    }
}

1 个答案:

答案 0 :(得分:1)

使用runOnUiThread在线程内调用MessageBox。 as:

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