1
我正在嘗試創建一個具有編輯文本視圖和按鈕的應用程序。此按鈕將通過TCP連接將編輯文本中的任何內容發送到服務器。如何在Java中的循環中放置TCP發送按鈕?
我已經完成了編輯文本的發送,但是當我單擊按鈕一次後,應用程序崩潰。我怎樣才能把它放到一個循環中,以便我可以發送多條消息?這是我的源
public class MainActivity extends Activity {
//Handler h;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText eText = (EditText) findViewById(R.id.address);
final TextView tView = (TextView) findViewById(R.id.pagetext);
final Button button = (Button) findViewById(R.id.ButtonGo);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
Socket s = new Socket("192.168.0.117", 4447);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//send output msg
String outMsg = ((EditText)findViewById(R.id.address)).getText().toString().trim();
out.write(outMsg);
out.flush();
Log.i("TcpClient", "sent: " + outMsg);
} catch (UnknownHostException e) {
tView.setText(e.toString());
Log.v("Tcp",e.toString());
} catch (IOException e) {
tView.setText(e.toString());
Log.v("Tcp",e.toString());
}catch (Exception e) {
tView.setText(e.toString());
}
}
});
}
}
你是否收到一個'NetworkOnMainThreadException'(或一些相似的名字)?發佈您的LogCat堆棧跟蹤。如果是這樣,請使用Thread/Runnable/AsyncTask作爲您的網絡資源,應用程序不會崩潰並且效率更高。 –
因爲你在UI線程中這樣做。在asyntask或separte線程中執行此任務。 –
你能向我解釋如何做到這一點?或者將我指向正確的方向?對不起,我對Java編程比較陌生,我非常感謝你的幫助。 – Man