I just started working with Java and the Android SDK and got an app working using sockets. But it seems pretty ugly and I was wondering if there was a better or more elegant way to go about it.
public class HelloAndroidActivity extends Activity {
private TextView textOut, textIn;
private EditText editOut;
private Handler mMainHandler, mChildHandler;
private Socket socket;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textIn = (TextView)findViewById(R.id.textin);
textOut = (TextView)findViewById(R.id.textout);
editOut = (EditText)findViewById(R.id.editout);
mMainHandler = new Handler() {
public void handleMessage(Message msg) {
textIn.append(msg.obj+"\n");
}
};
new ComOutThread().start();
new ComInThread().start();
Button buttonSend = (Button)findViewById(R.id.send);
buttonSend.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
//get a recycled message object, send it to comThread
Message msg = mChildHandler.obtainMessage();
msg.obj = editOut.getText().toString();
Log.d("SocketTest", "msg: "+msg.obj);
mChildHandler.sendMessage(msg);
//update outgoing text
textOut.append(editOut.getText().toString()+"\n");
}
});
}
public void onDestroy() {
mChildHandler.getLooper().quit();
super.onDestroy();
}
class ComOutThread extends Thread {
PrintWriter out;
public void run() {
Looper.prepare();
try {
socket = new Socket("192.168.1.160", 4444);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mChildHandler = new Handler() {
public void handleMessage(Message msg) {
Log.d("SocketTest", "sending msg: "+msg.obj+"\n");
out.println(msg.obj);
out.flush();
}
};
Looper.loop();
}
}
class ComInThread extends Thread {
public void run() {
String inputLine;
BufferedReader in = null;
try {
while(socket == null) {
Thread.sleep(200);
}
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("SocketTest", "Input thread started\n");
try {
while((inputLine = in.readLine()) != null) {
Log.d("SocketTest", "getting msg: "+inputLine+"\n");
Message msg = mMainHandler.obtainMessage();
msg.obj = inputLine;
mMainHandler.sendMessage(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
One thing that I thought might help would be to implement my own handler and message queue so the socket communication wouldn't need to be split into two threads, but idk if that would make it any cleaner.