Android InputStream Internet Disconnect

Question!

In my Android program, I have some code that downloads a file. This works fine, but since on a cell phone, you can be disconnected at any time, I need to change it do it reconnects and resumes the download when you are halfway through and somebody calls/you lose cell reception/etc. I cannot figure out how to detect the InputStream has stopped working. See the code below:

InputStream in = c.getInputStream();

    byte[] buffer = new byte[8024];
    int len1 = 0;

    while ( (len1 = in.read(buffer)) > 0 ) {
        Log("-"+len1+"- Downloaded.");
        f.write(buffer,0, len1);
        Thread.sleep(50);
    }

When I lose internet connection, My log shows:

Log: -8024- Downloaded.
Log: -8024- Downloaded.
Log: -8024- Downloaded.
Log: -8024- Downloaded.
Log: -6024- Downloaded. (some lower number)

And then my program just hangs on the while( (len1 = etc. I need to make it so when the internet gets disconnected I wait for the internet to be connected again and then resume the download.



Answers

Take a look here: http://developer.android.com/reference/java/nio/channels/SocketChannel.html

EDIT (based on comment): http://www.jguru.com/faq/view.jsp?EID=72378

So thoughts based on the above.... you might put the reading in a thread and periodically check to see if the thread has stopped reading data (update a shared variable probably). If it has kill the connection and the thread and deal with it however you need to.

Another alternative is to not use the HTTPURLConnection and deal with the bits you need your self.

By : TofuBeer


Just an observation - it looks like this is not an issue anymore with Silverlight 4. Adding 100K elements to a data-templated list box is instantaneous and it renders just fine as well.



+1 for using the Silverlight DataGrid in this scenario, make sure you have the latest version installed as the default Silverlight SDK version has a few bugs.

Another option is to use the free Silverlight DataGrid Control available here. One of it's features is also a Virtual StackPanel Row Container which means the grid can handle an unlimited number of rows.

Compare the performance of each and see which works best in your situation.

By : Peter McG


This video can help you solving your question :)
By: admin