繁体   English   中英

在线程内调用MessageBox

[英]Call MessageBox inside thread

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

使用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 
     }
   });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM