Java NetworkOnMainThreadException错误

Java NetworkOnMainThreadException错误,java,android,sockets,networkonmainthread,Java,Android,Sockets,Networkonmainthread,运行线路时 echoSocket=新套接字(服务器主机名,10008)我的应用程序因错误而崩溃,NetworkOnMainThreadException错误 据我所见,这与尝试在UI线程上运行套接字有关。那么,我如何更改我的代码(如下)使其工作 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import

运行线路时
echoSocket=新套接字(服务器主机名,10008)我的应用程序因错误而崩溃,NetworkOnMainThreadException错误

据我所见,这与尝试在UI线程上运行套接字有关。那么,我如何更改我的代码(如下)使其工作

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Build;

public class MainActivity extends ActionBarActivity  {

    Button Bgo;
    private static TextView TV1;
    EditText Text;
    String userInput;
    Socket echoSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    String Responce = null;
    String serverHostname;
    int section = 0;
    Boolean keepgoing = true;
    Boolean g1o = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bgo = (Button) findViewById(R.id.Go);
        TV1 = (TextView) findViewById(R.id.tv1);
        Text = (EditText) findViewById(R.id.Inputtext);
        onclick();
    }

    public void send() {

        // System.out.println("type the host name"); ->>updating
        // serverHostname = new String(stdIn.readLine());

        serverHostname = new String("192.168.1.105");
        System.out.println("Attemping to connect to host " + serverHostname
                + " on port 10008.");

        try {
            echoSocket = new Socket(serverHostname, 10008);
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(
                    echoSocket.getInputStream()));

        } catch (UnknownHostException e) {
            TV1.setText("Don't know about host: " + serverHostname);
        } catch (IOException e) {
            TV1.setText("Couldn't get I/O for " + "the connection to: "
                    + serverHostname);
        }

        TV1.setText("type VIEW-LOG for last 5 enteries (newset first) or DC to dissconect");
    }

    public void onclick() {
        Bgo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (g1o = true) {
                    TV1.setText("conecting");
                    g1o = false;
                    send();
                } else {
                    userInput = Text.getText().toString();
                    try {
                        if (userInput.equals("VIEW-LOG")) {
                            out.println(userInput);
                            int i = 0;
                            while (i < 5) {

                                Responce = in.readLine();

                                System.out.println(Responce);//this will be replace once this is working
                                i++;
                            }
                        } else if (userInput.equals("DC")) {
                            keepgoing = false;
                            System.out.println("dc");
                            out.println(userInput);
                        } else {
                            out.println(userInput);

                            System.out.println(in.readLine());

                        }
                    } catch (IOException e) {

                    }

                }
            }
        });
    }

    public void Close() {

        try {
            out.close();
            in.close();
            echoSocket.close();
        } catch (IOException e) {

        }
    }
}
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.io.PrintWriter;
导入java.net.Socket;
导入java.net.UnknownHostException;
导入android.support.v7.app.ActionBarActivity;
导入android.support.v7.app.ActionBar;
导入android.support.v4.app.Fragment;
导入android.os.Bundle;
导入android.view.LayoutInflater;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.TextView;
导入android.os.Build;
公共类MainActivity扩展了ActionBarActivity{
按钮Bgo;
私有静态文本视图TV1;
编辑文本;
字符串用户输入;
套接字echoSocket=null;
PrintWriter out=null;
BufferedReader in=null;
字符串response=null;
字符串服务器主机名;
int段=0;
布尔值keepgoing=true;
布尔g1o=真;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bgo=(按钮)findviewbyd(R.id.Go);
TV1=(TextView)findViewById(R.id.TV1);
Text=(EditText)findViewById(R.id.Inputtext);
onclick();
}
公共无效发送(){
//System.out.println(“键入主机名”);->>正在更新
//serverHostname=新字符串(stdIn.readLine());
serverHostname=新字符串(“192.168.1.105”);
System.out.println(“尝试连接到主机”+服务器主机名
+“在港口10008。”);
试一试{
echoSocket=新套接字(服务器主机名,10008);
out=新的PrintWriter(echoSocket.getOutputStream(),true);
in=新的BufferedReader(新的InputStreamReader(
echoSocket.getInputStream());
}捕获(未知后异常e){
setText(“不知道主机:+serverHostname”);
}捕获(IOE异常){
TV1.setText(“无法获取“+”到的连接的I/O:”
+服务器主机名);
}
TV1.setText(“为最后5个条目键入VIEW-LOG(首先键入新闻集)或DC以进行解析”);
}
公共void onclick(){
setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
如果(g1o=真){
TV1.setText(“连接”);
g1o=假;
send();
}否则{
userInput=Text.getText().toString();
试一试{
if(userInput.equals(“VIEW-LOG”)){
out.println(用户输入);
int i=0;
而(i<5){
response=in.readLine();
System.out.println(response);//这将在工作后被替换
i++;
}
}else if(userInput.equals(“DC”)){
keepgoing=false;
系统输出打印项次(“dc”);
out.println(用户输入);
}否则{
out.println(用户输入);
System.out.println(in.readLine());
}
}捕获(IOE异常){
}
}
}
});
}
公众假期结束(){
试一试{
out.close();
in.close();
echoSocket.close();
}捕获(IOE异常){
}
}
}
XML:



此剂量:按一个按钮即可运行send();连接到服务器的。当再次按下时,它会将edittext中的测试发送到服务器,如果是DC,它会断开与服务器的连接,如果是VIEW-LOG,服务器会发送5组字符串,当您在主线程上执行android不允许执行的某些网络操作时,会引发此异常。将
send
方法调用移动到非UI线程,或者最好将代码移动到
AsyncTask

中。您不应该在主线程上执行任何与网络相关的操作

使用
处理程序


一个
AsyncTask

中有多个答案,因此,使用AsyncTask执行网络请求。我建议在提问之前检查其他答案。谢谢,但我在解决如何修改代码以使用其中一个之前遇到了问题?
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="PlaceHolder"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/Inputtext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/Go"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go" />

</LinearLayout>