簡體   English   中英

onLocationChange()-無法發送發布請求

[英]onLocationChange() - cant send post request

我正在創建簡單的GPS跟蹤器。 應用程序獲取gps緯度/經度,並將其發送到遠程服務器上的php。

@Override

public void onLocationChanged(Location loc)
{
   String infLat = Double.toString(loc.getLatitude());
   String infLon = Double.toString(loc.getLongitude());

   String Text = "My current location is: " +
     "Latitud = " + infLat +
     "Longitud = " + infLon;

   Toast.makeText( getApplicationContext(),
                   Text,
                   Toast.LENGTH_SHORT).show();

   uploadLoc(infLat, infLon); // calling method which sends location info
}

這是uploadLoc:

public void uploadLoc(String a, String b) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://link to script");

    try {

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("latitude", a));
        nameValuePairs.add(new BasicNameValuePair("longitude", b));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        //
    } catch (IOException e) {
       //
    }
}

但是我一直在“應用程序已停止”。 當我刪除調用uploadLoc方法的行時,一切正常,並且Toast隨着位置的變化而更新。 這里有什么問題?

將您的Http帖子放在單獨的線程中。

每次嘗試將位置發布到遠程服務器時,都會花費一些時間,這最終可能會阻止onLocationChanged(Location loc)執行,下次由LocationListener調用它。

您可以在每次收到位置更新時嘗試啟動一個新線程,而解決方案的問題將會是,根據您的位置更新接收頻率,您最終可能會遇到很多線程。 但是,如果您要求每小時更新一次位置,這可能不是一個壞主意。

或者,您可以將所有網絡發布請求放入隊列中,並一一處理。 您甚至可以使用IntentService ,也可以遵循您的要求的其他設計模式套件。

關鍵是異步處理網絡操作,因為這種操作需要時間,並且在此期間它不會阻止其他關鍵操作的執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM