安卓求解~
============问题描述============
public class MainActivity extends Activity {
private static final String LOG_TAG = "IP Test";
private EditText chattxt;
private TextView chattxt2;
private Button chatok;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findviews();
setonclick();
chattxt2.setText(getLocalIpAddressV4());
}
public void findviews() {
// chattxt = (EditText) this.findViewById(R.id.chattxt);
chattxt2 = (TextView) this.findViewById(R.id.chattxt2);
chatok = (Button) this.findViewById(R.id.chatOk);
}
private void setonclick() {
chatok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
connecttoserver("I‘m a client!");
// connecttoserver(chattxt.getText().toString());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void connecttoserver(String socketData) throws UnknownHostException,
IOException {
Socket socket = RequestSocket("10.13.33.136", 5000);// 程序一打开执行到这里就停止运行了,不知道为什么?手机连的是wifi,地址是10.24.28.139,网关10.24.16.1,电脑ip是10.13.33.136,网关是10.13.33.1,所以这里感觉应该是是不在一个导致的,但是为啥手机能打开我本机的网站,地址为:http://10.13.33.136:8080/phnt ps:网络学的不好~T_T
// Socket socket = new Socket("10.13.33.136", 5000);
// SendMsg(socket, socketData);
// String txt = ReceiveMsg(socket);
// this.chattxt2.setText(txt);
}
private Socket RequestSocket(String host, int port)
throws UnknownHostException, IOException {
Socket socket = new Socket(host, port);
return socket;
}
private void SendMsg(Socket socket, String msg) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
writer.write(msg.replace("\n", " ") + "\n");
writer.flush();
}
private String ReceiveMsg(Socket socket) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String txt = reader.readLine();
return txt;
}
============解决方案1============
网络请求写线程里
============解决方案2============
android4.0以后的版本,不允许在UI线程中进行网络操作,网络操作应放子线程里,或AsyncTask中执行。
============解决方案3============
顶~
============解决方案4============
log里有提示不让在主线程访问网络!
============解决方案5============
new Thread(new Runnable(){
public void run() {
connecttoserver("I‘m a client!");
}
}).start();
将这段代码放到你的onclick方法里面~
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。