首先,我是Android和Java的新手......我正在研究機器人,需要發送無線命令。在嘗試了幾種方法來做到這一點,並獲得大量錯誤和時間調試(不理解示例代碼中發生的一半事件)後,我發現最簡單的通信方式就是使用套接字。我遵循教程http://android-er.blogspot.com/2011/01/simple-communication-using.html,它很好用!它確實如此,沒有錯誤,這是一個可喜的解決方案,但不是我想要的。它從Android開始,發送消息到PC,然後等待PC的響應,然後結束,直到再次單擊該按鈕。我想讓它朝相反的方向前進。我試着只是切換代碼,但一直在關閉。我終於搞定了,所以當你從android發送消息後,PC響應,然後android自動發送另一條消息,以便它始終等待PC。它不能很好地工作,有時因按鈕而崩潰。此外,它不再顯示來自PC的消息!我試圖把代碼的重要部分放入一個線程,所以android永遠不需要被觸及,並保持循環...我不知道爲什麼這不起作用,我得到以下錯誤:將PC循環到Android Socket通信?
11-24 13:21:11.492: E/AndroidRuntime(2656): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
我的整個程序是一個類:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//textOut = (EditText)findViewById(R.id.textout);
//Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
//buttonSend.setOnClickListener(buttonSendOnClickListener);
// start a loop
new Thread(new Runnable()
{
public void run()
{
while (true)
{
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.0.9", 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF("Received!");
dataInputStream = new DataInputStream(socket.getInputStream());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}).start();
}}
任何幫助或更好的方法的建議,這樣做將是巨大的!謝謝!