[android]代码库import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
@SuppressLint("HandlerLeak")
public class SocketDemo extends Activity {
/** Called when the activity is first created. */
private Button btn_receive;
private TextView txt;
private String line;
private static final String HOST = "192.168.1.101";
private static final int PORT = 9999;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initControl();
}
private void initControl() {
btn_receive = (Button) findViewById(R.id.btn_receive);
txt = (TextView) findViewById(R.id.txt);
btn_receive.setOnClickListener(new ReceiverListener());
}
@SuppressLint("HandlerLeak")
class ReceiverListener implements OnClickListener {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread() {
@Override
public void run() {
// 执行完毕后给handler发送一个空消息
try {
// 实例化Socket
Socket socket = new Socket(HOST, PORT);
// 获得输入流
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
line = br.readLine();
br.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}
} .start();
}
}
// 定义Handler对象
private Handler handler = new Handler() {
@Override
// 当有消息发送出来的时候就执行Handler的这个方法
public void handleMessage(Message msg) {
super.handleMessage(msg);
// 处理UI
txt.setText(line);
Log.i("PDA", "----->" + line);
}
};
}