package com.liu.activity;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ImageButton;
public class LoginActivity extends Activity {
private TextView text = null;//显示文本
private Socket socket = null;//目标为服务器的socket
private BufferedReader in = null;//输入流
private BufferedWriter out = null;//输出流
private String str = "";//接收的消息
private Button btn_login;//登陆按钮
private ImageButton btnQuit;//叉叉退出按钮
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//去除标题
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
//获得实例对象
btn_login = (Button) findViewById(R.id.btn_login);
btnQuit = (ImageButton)findViewById(R.id.img_btn);
text = (TextView) findViewById(R.id.TextView);//显示信息
new socketThread().start();//启动socket线程,耗时的工作放到子线程去做
btn_login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(str.indexOf("ok")>=0){
try {
out.write("da05c0d8471bc2116ce2b965c7b01aec\r\n");
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
btnQuit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
//子线程
public class socketThread extends Thread {
@Override
public void run() {
//将用户跳转到登陆成功的界面,如果输入错误,告知用户重新输入!
try {
socket = new Socket("115.28.79.163", 32906);//socket连接地址
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));//构造socket输入流
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));//构造socket输出流
//开机,如果客户端连接服务器上服务器,则跳出循环,如果没有连上,则每过四秒向服务器发送连接请求信息
while(true) {//如果连接上服务器就发送msg
try {
out.write("1\r\n");//并且使用flush刷新输出流
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
str=in.readLine();
if(str.indexOf("content ok")>=0){//如果收到的content数据为1
mHandler.sendMessage(mHandler.obtainMessage());//将接受到的数据发送到显示屏幕
break;//跳出循环
}
}
//将收到的数据发送到屏幕
while (true) {
str = in.readLine();
mHandler.sendMessage(mHandler.obtainMessage());//将接受到的数据发送到显示屏幕
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//将接收的消息打印到屏幕
public Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);//调用自身构造函数
text.setText("");//清空文本框内容
text.setText(text.getText().toString() + str);//打印文本框内容到屏幕
}
};
}
------解决思路----------------------
试试asynctask,或者volley(网络请求框架).
asynctask:
http://www.cnblogs.com/devinzhang/archive/2012/02/13/2350070.html
volley:
http://www.kwstu.com/ArticleView/kwstu_20144118313429