2011-07-26 45 views
1

我有一個應用程序,其中包含Google地圖,Google地圖上的位置疊加層和每隔30秒將設備當前位置發送到服務器的單獨線程。問題是當線程將位置發送到服務器時,設備的屏幕停止,直到服務器響應。這是下面的代碼,Android中的通信(客戶端/服務器)屏幕暫停

全局對象

private Handler handlerTimer = new Handler(); 

在onCreate方法

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

這裏是taskUpdateStuffOnDialog

private Runnable 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); 
     } 

    }; 

請告訴我什麼是錯我的代碼。

+0

這聽起來好像你沒有真正產生一個單獨的線程來發送位置到服務器。很可能你以某種方式阻止了主UI線程。我無法真正瞭解您發佈的代碼中發生了什麼。 – dbryson

+0

@Dbryson,我編輯了我的問題,請現在檢查它。 – Siddiqui

+0

看到我的帖子在下面。希望有所幫助 – dbryson

回答

1

問題是,雖然你產生了一個新的線程,但你不會產生新的進程。你所做的一切仍然在用戶界面過程中,這就是阻塞。您可以在主題on developer.android.com中找到更多信息。

解決此問題的最快最簡單的方法是使用IntentService類。它只允許一次執行一個HTTP請求,但會爲您解決所有問題。