アプリをソケット経由で接続するスレッドを作成しました。しかし、このスレッドでソケットとの間でデータを読み書きする必要があります。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();
}
}
};
}