开发者

How to separate my code to many method?

I am a new in android developing, I've code to connect to server and send commands, How to separate connection code in method and sending code in another method. my code as following:

public void onClick(View arg0) {
 // TODO Auto-generated method stub
 Socket socket = null;
 DataOutputStream dataOutputStream = null;
 DataInputStream dataInputStre开发者_StackOverflow社区am = null;

 try {  
// connect code         
  socket = new Socket("172.16.149.64", 8888);

// sending code
  dataInputStream = new DataInputStream(socket.getInputStream());
  dataOutputStream = new DataOutputStream(socket.getOutputStream());
  dataOutputStream.writeUTF(textOut.getText().toString());
  textIn.setText(dataInputStream.readUTF());
 } catch (UnknownHostException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 finally{

  if (dataOutputStream != null){
   try {
    dataOutputStream.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }

  if (dataInputStream != null){
   try {
    dataInputStream.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }

  if (socket != null){
       try {
        socket.close();
       } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
      }

 }
}


Write a class of your own and make the Socket one of its member variables. You can then write connect() and sendData() methods to your class using the same socket in both methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜