功能需求:在后台新建一个线程来向指定的服务器发送手机当前的位置信息,同时读取服务器发送回来的信息,客户端和服务器的信息格式就是普通字符串,各位牛人帮忙看看客户端这么写是否正确,万分感谢。
MessageControl mc=null;//MessageControl是继承自Handler的普通类,重写了handMessage方法
单击某个按钮后onclick的方法体如下:try {
socket = new Socket(HOST, PORT);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
     } catch (Exception e) {
e.printStackTrace();
}
HandlerThread thread = new HandlerThread("MyThread");
thread.start();
mc = new MessageControl(thread.getLooper());
mc.post(rSend);
mc.post(rRec);Runnable rSend=new Runnable(){ @Override
public void run() {
Location location = locationManager.getLastKnownLocation(provider);
if (socket.isConnected()) {
if (!socket.isOutputShutdown()) {
out.println(Double.toString(location.getLatitude()).substring(0,8)+Double.toString(location.getLongitude()).substring(0,8));
}
}
mc.postDelayed(rSend, 30000);//过30秒后继续读取当前的位置
}

};

Runnable rRec=new Runnable(){ @Override
public void run() {
String content=null;
try {
while (true) {
if(socket.isConnected()){
if(!socket.isInputShutdown()){
if ((content = in.readLine()) != null) {
content += "\n";
}
}
}

}
} catch (Exception ex) {
ex.printStackTrace();
}
Message msg = mc.obtainMessage();
msg.obj=content;
msg.sendToTarget();
mc.postDelayed(rRec, 30000);//过30秒后读取服务器发送来的消息
}

};