NetworkOnMainThreadException错误

时间:2014-05-09 16:42:38

标签: java android sockets networkonmainthread

运行时 echoSocket = new Socket(serverHostname, 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) {

        }
    }
}

XML:

<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>

这个剂量是什么:一键按下它运行send();使连接到服务器。当再次按下它时,它会将edittext中的测试发送到服务器,如果它是DC,它会从服务器断开连接,如果它是VIEW-LOG,则服务器会发送5个字符串

2 个答案:

答案 0 :(得分:0)

当你在android不允许的主线程上执行某些网络操作时会引发此异常。将您的send方法调用移至非UI线程或更好地将代码移至AsyncTask

答案 1 :(得分:-1)

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

使用Handler http://developer.android.com/reference/android/os/Handler.html

OR

AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html