Search code examples
androidmultithreadingbackground-process

Using another thread for "networking" , in Android


I am developing an Android application and when it launches :

1) I make an HTTP Request to my server to send a small JSON file.

2) Open a webView to show a URL.

When the server is running properly there is absolutely no problem and everything goes smoothly.

HOWEVER , if for any reason the server is down , the HTTP request literally hangs and i need to wait till there is an HTTP timeOut which is around 30seconds till i actually see the webView with the URL loading.

I read that i shouldn't make any networking inside the UI thread and i should use another thread for that.

In BlackBerry , that i have already developed the application for , this is as simple as that :

new Thread(){
  public void run(){
    HttpConnection hc = 
            (HttpConnection)Connector.open("http://www.stackoverflow.com");
  }
}.start();

I just start a new thread and inside i make the requests and all the necessary networking. That way , even when my server is not reachable the webView is loaded immediately without making the user wait and sense that the app is actually hanging.

How could i do exactly the same in Android , easiest way possible ?


Solution

  • Why not to use the same method as you use it for BlackBerry?

    new Thread() {
      public void run() {
        new URL("http://www.stackoverflow.com").getContent();
      }
    }.start();