1.做了一個項目,需要在activity中實時採集屏幕滑動的坐標,並將坐標發送給服務端,由於socket不能在activity中直接使用,採用如下辦法,將socket作爲內部類:
public class SocketMotion { byte[] motiondata; Socket socket = null; String ip; int port; public SocketMotion(){ Log.i("soc","啓動socket motion "); } public void setIPandPort(String ip,int port){ this.ip = ip; this.port = port; } public void sendMotion(byte[] motiondata){ this.motiondata = motiondata; SocketConn socketConn = new SocketConn(); new Thread(socketConn).start(); } class SocketConn extends Thread{ public void run(){ try { socket = new Socket(ip,port);//"192.168.31.31",12000 Log.i("soc","socket client 已連接"); BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream()); BufferedInputStream is = new BufferedInputStream(socket.getInputStream()); os.write(motiondata); os.flush(); // os.close(); // socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } 2.在activity中只需要如下語句即可
socket = new SocketMotion(); socket.setIPandPort("192.168.31.31",12000); 使用socket.sendMotion()發送數據