2014-04-26 56 views
-1

我想獲取我的當前位置並獲取到某個目的地的駕車路線。 我能得到我的位置,當我執行代碼的行車路線我在下面一行android.os.NetworkOnMainThreadException。如何解決它?

 HttpResponse response = httpClient.execute(httpPost, localContext); 

響應爲NULL得到android.os.NetworkOnMainThreadException。我該怎麼辦 ?

public Document getDocument(LatLng start, LatLng end, String mode) { 
    String url = "http://maps.googleapis.com/maps/api/directions/xml?" 
      + "origin=" + start.latitude + "," + start.longitude 
      + "&destination=" + end.latitude + "," + end.longitude 
      + "&sensor=false&units=metric&mode="+mode; 

    try { 
     new DownloadWebpageTask().execute(url); 


     HttpClient httpClient = new DefaultHttpClient(); 
     HttpContext localContext = new BasicHttpContext(); 
     HttpPost httpPost = new HttpPost(url); 
     HttpResponse response = httpClient.execute(httpPost, localContext); 
     InputStream in = response.getEntity().getContent(); 
     DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
     Document doc = builder.parse(in); 
     return doc; 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 
+0

的[android.os.NetworkOnMainThreadException(http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – Simon

回答

0

您無法在主UI線程上執行網絡操作。你將不得不做的是創建一個新的線程,並在那裏做網絡的東西。如果需要,您可以使用Handler將更新發布回主UI線程。如果你需要一個代碼示例,我可以發佈一個最小的應該工作。

這樣做很重要,當你這樣做不是爲了維護一個強大的引用回到活動,或者你可以泄漏設備旋轉或其他onDestroy()事件的整個活動。因爲你將上下文傳遞給了另一個線程,所以你需要測試它以確保你沒有泄漏。我寫了一篇博客文章這對我的Tumblr:

http://tmblr.co/ZSJA4p13azutu


編輯1

下面是一些代碼,應該幫助:

static final class ProgressMessages extends Handler 
{ 
    private WeakReference<MyAndroidClass> weakAndroidClassRef; 

    public ProgressMessages (MyAndroidClass myContext) 
    { 
     weakWritingPadRef = new WeakReference<MyAndroidClass>(myContext); 

    } 

    public void handleMessage(Message msg) 
    { 
     String s = "Uploading page " + msg.arg1 + "."; 
     Toast t = Toast.makeText(weakAndroidClassRef.get(), s, Toast.LENGTH_LONG); 
     t.show(); 

    } 


}; 

ProgressMessages pm; 



public void doNetworkStuff() 
{ 

    t = new Thread() 
    { 
     public void run() 
     { 

      Looper.prepare(); 
      try 
      { 
        pm.sendMessage(Message.obtain(pm, 0, i + 1, 0)); 


      } 
      catch(IOException ioe) 
      { 
       ioe.printStackTrace(); 

      } 
      pm.post(update); 
     } 


    }; 
    t.start(); 

} 
0

這是因爲當你試圖在主線上做網絡連接..它應該在後臺線程上完成..

解決方案: 的AsyncTask

點擊這裏瞭解AsyncTask

1

由於NetworkOnMainThreadException狀態,網絡請求應該只在後臺線程中執行。你不能在主線程中執行。

創建一個AsycTask並在doInBackground()方法上執行您的代碼。一旦後臺操作完成後,您可以在onPostExecute

new AsyncTask<Void, Integer, Document>(){ 
     @Override 
     protected Document doInBackground(Void... params) { 
      try { 

       // call you method here 
       return getDocument(); 

      } catch (Exception ex) { 
       // handle the exception here 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Document result){ 
      // update the UI with your data 
     } 
    }.execute(); 
+0

可能重複更新UI根據您的網絡任務,AsyncTask可能不是正確的:「AsyncTask被設計成圍繞Thread和Handler的助手類,並且不構成通用線程框架。理想情況下AsyncTasks適用於短操作(最多幾秒鐘。 )如果需要讓線程長時間運行,強烈建議您使用java.util.concurrent pacakge提供的各種API,例如Executor,ThreadPoolExecutor和FutureTask。「 – mttdbrd

+0

謝謝你,工作。 –

+0

@mttdbrd。不,我不認爲他在這裏做任何網絡數據庫合併,以線程運行。 AsyncTask應該沒問題。 – Libin

相關問題