Android 客户端错误 - java.lang.IllegalStateException:无法执行 activity 的方法

Android Client Error - java.lang.IllegalStateException: Could not execute method of the activity

我正在构建一个简单的客户端-服务器系统。我已经构建了一个 Java 服务器和一个 android 客户端,它们在我的设备上运行(都连接到同一个 LAN)。

当我试图建立连接(通过单击按钮)时,客户端失败并显示错误

-"java.lang.IllegalStateException: Could not execute method of the activity"

关闭问题的其他答案中说它可能连接到 AsyncTask,但我不确定。

服务器代码:

    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;

    public class Server { 
        public static void startConnection(int portNum)
        {   
            ServerSocket serverSocket=null;
            Socket clinetSocket=null;
            ObjectOutputStream serverOut=null;
            ObjectInputStream serverIn=null;
            String message=null;

            //create a socket
            try{
                serverSocket=new ServerSocket(portNum);
            } 
            catch (IOException e) {
                e.printStackTrace();
            } 
            System.out.println("Waiting for connection...");
            try{
                clinetSocket = serverSocket.accept();
            }
            catch (IOException e){
                e.printStackTrace();
            }

            System.out.println("connected to "+ clinetSocket.getInetAddress().getHostName());

        }

Android 客户端代码:

    Main.java :

    package com.example.user_pc.myapplication;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    import java.net.Socket;
    import java.io.IOException;
    import java.net.UnknownHostException;
    import java.net.SocketException;
    import android.util.Log;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;

    public class Main extends ActionBarActivity {

        TextView text;

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

            text= (TextView) findViewById(R.id.textView1);
            text.setText("");
        }

        public void pushTheButton(View v)
        {
            Button button = (Button) findViewById(R.id.button);
            createSocket();
        }
        public void createSocket()
        {
            Socket sock = null;
            String dstIP = "192.168.2.103";//server ip
            int dstPort = 9632;


             try
            {
                sock = new Socket(dstIP, dstPort);
            }

            catch(SocketException ie)
            {
                Log.wtf("SocketException",ie);
            }

            catch(UnknownHostException ie)
            {
                Log.wtf("UnknownHostException",ie);
            }
            catch(IOException ie)
            {
                Log.wtf("IOException",ie);
            }

    }

        public static void main(String[] args) 
        {
            int portNum=9632;
            startConnection(portNum);
        }

    ``}

manifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.user_pc.myapplication" >

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Main"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Main"
    android:onClick="pushTheButton">

    <Button
        android:layout_width="300dp"
        android:layout_height="100dp"
        android:text="Click to connect"
        android:id="@+id/button"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="96dp"
        android:onClick="pushTheButton"
        />
</RelativeLayout>

正如我所说。你得到了 NetworkOnMainThreadException。您需要在后台线程中执行网络 I/O。您的 createSocket() 方法必须启动一个新的后台线程来完成这项工作。或者使用 AsyncTask.