gpt4 book ai didi

java - 在线程内调用 MessageBox

转载 作者:行者123 更新时间:2023-11-30 03:50:27 29 4
gpt4 key购买 nike

我正在尝试找到一种从线程内部调用 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
}
});
}

关于java - 在线程内调用 MessageBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14241789/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com