简体   繁体   中英

Correct way to read input stream android

I have a piece of code below that is to receive an input stream from a socket on Android. It works fine, but when the phone goes to sleep, my logger goes crazy printing out that it received "" .

From my debugging it means that my if statement in the whole loop is not sufficient?

//Global variable declaration
private OnMessageReceived mMessageListener = null;
byte[] buffer = new byte[100];   

 while (mRun) {
            int len = in.read(buffer);
            input = "";

            if (buffer != null && mMessageListener != null) {
                for (int i = 0; i < len; i++) {
                    input += (char) buffer[i];
                }
                // call the method messageReceived from MyActivity class
                mMessageListener.messageReceived(input);
                System.out.println("Recieved: " + input);
            }
            input = "";
        }

That is my code that runs in the while . Now, I am sure I am not testing a correct condition in my : if (buffer != null && mMessageListener != null) code.

What else could I test / what could I be testing that is incorrect?

Obviously after the while has run once, the buffer is not == null and then I am assuming that when the phone goes to sleep (screen goes black) mMessageListener becomes non null ?

Thanks

1) You shouldn't use + operator to join multiple Strings, it's very slow, use StringBuilder instead.

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < len; i++) {
       sb.append((char)buffer[i]);
    }

    String input = sb.toString();

Or, this may be even faster if you joining by single characters:

    char[] inputChars = new char[len];

    for (int i = 0; i < len; i++) {
       inputChars[i] = (char)buffer[i];
    }

    String input = new String(inputChars);

There's shorter way to achieve this effect..

    String input = new String(buffer);

2) I'm not sure, but buffer will never become null in this case, so != null statement is pointless. Length can be 0 if there's no data readed, so check if len != 0.

EDIT Well, there's a number of mean looking statements there. Is that all the code? How do you expect things to become null or spawn to life on their own?

If you want to consume an InputStream, the easiest way is to use a Scanner :

String text = new Scanner(in).useDelimiter("\\A").next();

This says "scan the input stream in until the end is found". You may use another delimiter to split it into several parts.

你应该检查len变量是否大于0,read方法将在到达流末尾时返回-1,这样:

if (len>0 && buffer != null && mMessageListener != null)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM