1

我已经编写了这段代码以在按下 imageview 时通过套接字发送数据
它工作正常但是在我离开 imageview 之后它仍然发送数据
我确信问题出在 android 部分。
这段代码有什么问题?

 package com.example.paradroid;


 import java.io.IOException;
 import java.net.InetAddress;
 import java.net.Socket;
 import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.EditText;

import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;

public class MainActivity extends Activity {

static final String RIGHT = "2";
static final String LEFT = "4";
static final String UP = "1";
static final String DOWN = "3";
static final String STOP = "5";

InetAddress serverAddress;
Socket socket;
// ---all the Views---
static TextView txtMessagesReceived;
EditText txtMessage;
// ---thread for communicating on the socket---
CommsThread commsThread;
// ---used for updating the UI on the main activity---
static Handler UIupdater = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        int numOfBytesReceived = msg.arg1;
        byte[] buffer = (byte[]) msg.obj;
        // ---convert the entire byte array to string---
        String strReceived = new String(buffer);
        // ---extract only the actual string received---
        strReceived = strReceived.substring(0, numOfBytesReceived);
        // ---display the text received on the TextView---
        // txtMessagesReceived.setText(txtMessagesReceived.getText()
        // .toString() + strReceived);
    }
};

private class CreateCommThreadTask extends
        AsyncTask<String[], Integer, Void> {
    @Override
    protected Void doInBackground(String[]... params) {
        try {
            // ---create a socket---
            serverAddress = InetAddress.getByName(params[0][0]);
            int port = Integer.parseInt(params[0][1]);
            // --remember to change the IP address above to match your own--
            socket = new Socket(serverAddress, port);
            commsThread = new CommsThread(socket);
            commsThread.start();

        } catch (UnknownHostException e) {
            Log.d("Sockets", e.getLocalizedMessage());
        } catch (IOException e) {
            Log.d("Sockets", e.getLocalizedMessage());
        }
        return null;
    }
}


private class WriteToServerTask extends AsyncTask<String, Void, Void> {
    protected Void doInBackground(String... data) {
        commsThread.write(data[0]);
        return null;
    }
}

private class CloseSocketTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        try {
            socket.close();
        } catch (IOException e) {
            Log.d("Sockets", e.getLocalizedMessage());
        }
        return null;
    }
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // ---get the views---
    final  ImageView im_up = (ImageView) findViewById(R.id.imageView2);
    final ImageView im_right = (ImageView) findViewById(R.id.imageView3);
    final ImageView im_down = (ImageView) findViewById(R.id.imageView1);
    final ImageView im_left = (ImageView) findViewById(R.id.imageView4);

    im_up.setOnTouchListener(new TheOnTouchListner(1));
    im_right.setOnTouchListener(new TheOnTouchListner(2));
    im_down.setOnTouchListener(new TheOnTouchListner(3));
    im_left.setOnTouchListener(new TheOnTouchListner(4));
}

private class TheOnTouchListner implements OnTouchListener {
    private Handler mHandler;
    private int tag;

    public TheOnTouchListner(int t) {
        this.tag = t;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (mHandler != null)
                return true;
            mHandler = new Handler();
            mHandler.postDelayed(mAction, 500);

        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            if (mHandler == null)
                return true;
            mHandler.removeCallbacks(mAction);
            mHandler = null;
            return false;
        }

        return false;
    }

    Runnable mAction = new Runnable() {
        @Override
        public void run() {

            onClickSend(tag);
            mHandler.postDelayed(this, 500);
        }

    };

}

public void onClickSend(int tag) {
    // ---send the message to the server---

    if (tag == 1) {
        sendToServer(UP);
    } else if (tag == 2) {
        sendToServer(RIGHT);
    } else if (tag == 3) {
        sendToServer(DOWN);

    } else if (tag == 4) {
        sendToServer(LEFT);

    }

}

public void onClickConnect(View view) {
    String[] params = new String[2];
    params[0] = ((EditText) findViewById(R.id.IPText)).getText().toString();
    params[1] = ((EditText) findViewById(R.id.PortText)).getText()
            .toString();

    new CreateCommThreadTask().execute(params);
    Toast.makeText(getBaseContext(), "connected!", Toast.LENGTH_SHORT)
            .show();
}

private void sendToServer(String message) {
    // byte[] byteArray = new byte[1];
    // byteArray[0] = message;
    new WriteToServerTask().execute(message);
}

@Override
public void onResume() {
    super.onResume();

}

@Override
public void onPause() {
    super.onPause();
    sendToServer("bye."); // defined in server that this string terminates
                            // connection
    new CloseSocketTask().execute();
}

CommsThread 类:

   package com.example.paradroid;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import android.util.Log;
import java.io.PrintWriter;

public class CommsThread extends Thread {
private final Socket socket;
private final InputStream inputStream;
private final OutputStream outputStream;
private final PrintWriter out;

public CommsThread(Socket sock) throws IOException {
    socket = sock;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;
    try {

        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();
    } catch (IOException e) {
        Log.d("SocketChat", e.getLocalizedMessage());
    }
    inputStream = tmpIn;
    outputStream = tmpOut;

    out = new PrintWriter(sock.getOutputStream(), true);

}

public void run() {

}


public void write(String bytes) {

    out.println(bytes);

}

public void cancel() {
    try {
        socket.close();
    } catch (IOException e) {
    }
}

}

4

0 回答 0