开发者

Screen Halt while Communication(Client/Server) in Android

I have an application in which there is Google map, location overlays on Google map and a separate thread which send the current location of device to server after every 30 seconds. The problem is that when the thread sends the location to server the screen of device halted until the server respond. Here is the following code,

Global Object

private Handler handlerTimer = new Handler();

In onCreate Method

 handlerTimer.removeCallbacks(taskUpdateStuffOnDialog );
 handlerTimer.postDelayed(taskUpdateStuffOnDialog , 100);

And here is the taskUpdateStuffOnDialog

    private Runn开发者_StackOverflowable taskUpdateStuffOnDialog = new Runnable() 
    {        
        public void run() 
        { 
        try
        { 
        URL url3 = new URL("http://"+ appState.getURL()+"//iLocator/IDForClient.php?reg_no="+ Device_ID[0]);
        HttpURLConnection conn = (HttpURLConnection) url3.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String quote = reader.readLine();
        while (quote != null)
        {
            Device_ID = quote.split("\n");
            quote = reader.readLine();
            bCheckID = true;
        }//End While

        positionOverlay.setID(Device_ID[0]);
        addEvent(Device_ID[0]);

    }//End try
    catch (Exception e) 
    {
        e.printStackTrace();
        Toast.makeText(MainMapActivity.this, "Communication Issue",Toast.LENGTH_LONG).show();       
    }//End catch
handlerTimer.postDelayed(this, 9000);
        }

    };

Please tell me what is wrong with my code.


The problem is that, although you're spawning a new Thread, you aren't spawning a new process. Everything you're doing is still in the user interface process, and that's blocking. You can find more information on the topic on developer.android.com.

The quickest and easiest way to get around this is using the IntentService class. It will only allow one HTTP request to be executed at a time, but will take care of all the problems for you.


Try using the AsyncTask for connecting to the Server. See an example here: http://developer.android.com/reference/android/os/AsyncTask.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜