我创建了通过套接字连接我的应用程序的线程。但是我需要在这个线程中从/向套接字读取和写入数据。我不能这样做,因为 Looper.loop 不允许这样做。如何从主 UI 读取此线程的消息并检查是否有新数据进入套接字?
public class MainActivity extends Activity {
EditText textOut;
TextView textIn;
//Socket soc;
int port=1000;
EditText text ;
public Handler h;
public Handler mHandler;
String str;
Message msg1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (EditText)findViewById(R.id.editText1);
h = new Handler() {
public void handleMessage(android.os.Message msg) {
Bundle bundle = msg.getData();
str=bundle.getString("TCP");
text.setText(str);
};
};
thread.start();
//thread.start();
}
public void send(View view){
Log.d("TCP", "C: READ123");
mHandler.sendEmptyMessage(1);
}
@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;
}
Thread thread = new Thread()
{
Message msg;
BufferedWriter out;
@Override
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// обрабатываем входящие сообщения
Log.d("MY", "RECEIVE");
}
};
//LOOP
//Looper.loop();
char[] mData = new char[4096];
String s="";
Bundle bundle = new Bundle();
try {
try {
InetAddress serverAddr = InetAddress.getByName("192.168.2.75");
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, 1000);
String message = "komand1";
try {
out = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream()));
// out.println(message);
Toast.makeText (getApplicationContext(), message, Toast.LENGTH_SHORT).show();
Log.d("TCP", "C: Sent.");
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
}
//Read Data from socket
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int read = 0;
Log.d("TCP", "Receive");
while ((read = reader.read(mData)) >= 0)
{
if(read > 0){
Log.d("TCP", "DATA!!");
msg = h.obtainMessage();
s="";
for(int i=0; i<read;i++){
s=s+Character.toString(mData[i]);
}
bundle.putString("TCP", s);
msg.setData(bundle);
h.sendMessage(msg);
}
}
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
};
}