当我尝试连接到 wifi 路由时,这是我的代码,但我显示错误
Button.OnClickListener buttonConnectOnClickListener = new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
wifiInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiInfo.isConnected()) {
if(!connected){
try {
// socket = new Socket("192.168.1.1", 2001);
// Log.v("test4","test4");
/*Toast msg = Toast.makeText(Main.this,
"Connected Successfully", Toast.LENGTH_LONG);
msg.show();*/
//Log.v("test5","test5");
socket = new Socket("192.168.1.1",2001);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
changeConnectionStatus(true);}
catch (UnknownHostException e) {changeConnectionStatus(false);}
catch (IOException e) {changeConnectionStatus(false);}}
else{
try {socket.close();
Toast msg = Toast.makeText(Main.this,
"Disconnected Successfully", Toast.LENGTH_LONG);
msg.show();
changeConnectionStatus(false);}
catch (UnknownHostException e) {changeConnectionStatus(false);}
catch (IOException e) {changeConnectionStatus(false);}}}
else {Toast msg = Toast.makeText(Main.this,
"Wifi is not connected !", Toast.LENGTH_LONG);
msg.show();}
}};
logcat 中的错误是
06-26 18:37:48.190: W/dalvikvm(11911): threadid=1: 线程退出未捕获异常 (group=0x40a571f8) 06-26 18:37:48.205: E/AndroidRuntime(11911): 致命异常: main 06-26 18:37:48.205: E/AndroidRuntime(11911): android.os.NetworkOnMainThreadException 06-26 18:37:48.205: E/AndroidRuntime(11911): 在 android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode. java:1099) 06-26 18:37:48.205: E/AndroidRuntime(11911): 在 libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)