Search code examples
androidandroid-activityxamarin.androidstreamwriter

Mono for Android - Activity crash upon service call


My application has a UI (implemented with an Activity) and a service (implemented with the IntentService). The service is used to send data (synchronous, using NetworkStream.Write) to a remote server as well as to update the transmission status to the UI (implemented using Broadcast Receiver method).

Here is my problem:

  • The application works properly if the size of the buffer used for the NetworkStream.Write is 11 KB or less.

  • However, if the size of the buffer is larger than 11 KB, say 20 KB (this size needed in order to send jpg images), then the sevice keeps working properly (verified with log file), nonetheless the UI its gone (similar as if device's back button is pushed) and I can't find the way to bring it back. Its important to point out that in this case the Activity its not going into OnStop() nor OnDestroy() states.

  • At first I thought this would be some ApplicationNotResponding related issue due to a server delay, yet the UI crashes after about 5 sec.

  • Moreover, this only happens with the Hardware version. The emulator version works fine.

    // SEND STREAM:
    
    Byte[] outStream = new Byte[20000];
    // -- Set up TCP connection: --
    TcpClient ClientSock = new TcpClient();
    ClientSock.Connect("myserver.com", 5555);
    NetworkStream serverStream = ClientSock.GetStream();
    serverStream.Write(outStream, 0, outStream.Length);
    serverStream.Flush();
    // . . .
    
    // RECEIVE STREAM:            
    inStream.Initialize();           // Clears any previous value.
    int nBytesRead = 0;
    nBytesRead = serverStream.Read(inStream, 0, 1024);
    
    // -- Closing communications socket: --
    ClientSock.Close(); 
    

Solution

  • One thing first: I would have been commented the question to clarify one thing before I give an answer, but unfortunately I don't have enough reputation yet.

    The thing I would have asked for is: Why do you need to have a buffer greater than 11k to send an JPG image?

    I nearly do the same in one (async) task with an image of 260k, but with a buffer of 10240 Bytes. Works without difficulties.

    byte[] buffer = new byte[10240];
    for (int length = 0; (length = in.read(buffer)) > 0;) {
      outputStream.write(buffer, 0, length);
      outputStream.flush();
      bytesWritten += length;
      progress = (int) ((double) bytesWritten * 100 / totalBytes);
      publishProgress();
    }
    outputStream.flush(); 
    

    I use this part to read an JPG image from resources or SD and post to my server.