Socket.isConnected() 让我的 android 应用强制关闭

Socket.isConnected() make my android app force close

当我使用方法

时,我不知道 Android 中有关 Socket 的源代码发生了什么

.isConnected()

我的应用总是强制关闭。这是我的源代码

public class MyActivity extends Activity {
    private String IP;
    private int PORT;
    private Socket socket;
    private PrintWriter printWriter;
    private TextView text;

    private EditText fieldIp;
    private EditText fieldPort;


    private Button connect;
    private FrameLayout frameIP;

    private String message;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        frameIP = (FrameLayout)findViewById(R.id.frameIP);
        connect = (Button)findViewById(R.id.connect);
        fieldIp = (EditText)findViewById(R.id.ip);
        fieldPort = (EditText)findViewById(R.id.port);
        text = (TextView)findViewById(R.id.keterangan);
        connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IP = fieldIp.getText().toString();
                PORT = Integer.parseInt(fieldPort.getText().toString());
                SocketConnect socketConnect = new SocketConnect(IP,PORT);
                socketConnect.execute();
            }
        });
    }


    private class SocketConnect extends AsyncTask<Void, Void, Boolean> {

        String ip;
        int port;

        public SocketConnect(String a, int b){
            this.ip = a;
            this.port = b;
        }


        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                socket = new Socket();
                socket.connect(new InetSocketAddress(ip,port));
                if(socket.isConnected())
                {
                    text.setText("Connected!");
                }
                else
                {
                    text.setText("Failed to connect!");
                }
            } catch (IOException e) {
                Log.e("MyActivity",e.getMessage());
            }
            finally {
                startActivity(new Intent(getApplicationContext(),ListViewText.class));
            }
            return null;
        }
    }
}

我在 AndroidManifest.xml

中使用它
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

希望大家能帮帮我:(

改变doInBackground方法如下...

@Override
protected Boolean doInBackground(Void... params) {

    boolean success = true;

    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(ip, port));
    } catch (Exception e) {
        success = false;
        Log.e("MyActivity", e.getMessage());
    }
    return success;
}

然后添加一个onPostExecute方法...

@Override
protected void onPostExecute(boolean result) {
    if(result) {
        text.setText("Connected!");
        startActivity(new Intent(MyActivity.this, ListViewText.class));
    }
    else {
        text.setText("Failed to connect!");
    }
}

首先你在 UI 线程之外调用 UI 操作(这就是创建 AsyncTask 的原因,只在 doInBackground 中处理后台作业)所以关于显示文本的问题TextView解决了...

但更重要的是:

切勿在 AsyncTask 中打开 Socket。在 Android developer site 您可以找到以下内容:

If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.)

而这正是您想要做的。因此,请改用 Service, Thread 或上面提到的那些。