1
我試圖找到一種方法來調用線程內的MessageBox。但是我發現的每一段代碼/例子都不起作用。有人能用盡可能少的代碼行以最簡單和最簡單的方式闡述一個解決方案/例子嗎?調用線程內的MessageBox
這是我到目前爲止的代碼:用於調用線程中的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
}
}
}
你的意思是像我一樣的崗位(它的編輯) 但我怎麼會叫從線程,加上功能,我怎麼會叫不同MessagesBoxes從同樣的功能? – blacblu
@blacblu:查看我的編輯答案。 –
爲什麼我不能在MainActivity.this的作用域中訪問MainActivity類型的實例? – blacblu