I am trying to find a way to call a MessageBox from inside a thread. But every piece of code/example I’ve found didn’t work. Can someone elaborate a solution/example with the easiest and most simple way with the fewest lines of code as possible?
This is my code so far:
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
}
}
}
Use runOnUiThread for Calling MessageBox inside a thread. as :