Вопрос

I have some weird problem on Android 2.2 phone.

I open the socket connection:

socket = new Socket(serverAddr, SERVERPORT);
messageWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), Charset.forName("UTF-8"))));
messageReader = new InputStreamReader(socket.getInputStream(), Charset.forName("UTF-8"));

Start reading in AsyncTask doInBackground():

    protected Boolean doInBackground(final Void... unused) {
    ...
        char[] chars = new char[256];
        int len;
        while((len = messageReader.read(chars))>=0) {
               builder.append(chars, 0, len);
               break;
        }
       result = true;
    ...
    }

After reading I close the connection:

                try {
                    socket.close();
                    socket = null;
                } catch (Exception e) {Log.e("socket", "ex");}
                try {
                    messageWriter.close();
                    messageWriter = null;
                } catch (Exception e) {Log.e("writer", "ex");}
                try {
                    messageReader.close();
                    messageReader = null;                   
                } catch (Exception e) {Log.e("reader", "ex");}  

Everything is working fine on Android 2.3 phone and Android 4.0 emulator, but for some reason it's not working on Android 2.2 phone. The socket is closed, the writer is closed, but the reader is stuck in a while loop even though it should brake loop when calling "socket.close();"... so my closing code is stuck on "messageReader.close();" and whole UI is blocked! ...and there is no way to kill AsyncTask... Why is this happening and what should I do?

Это было полезно?

Решение

First, you don't need those three closes. You only need to close the output stream/writer.

Second, closing isn't guaranteed to terminate a blocking operation in another thread. See the Javadoc. If you have such a thing you need to shutdown the socket for input before closing. Then the reading thread will get an EOS, on which it should exit.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top