onLocationChanged() - 无法发送帖子请求

时间:2013-04-01 00:35:12

标签: java android

我正在创建简单的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会随着位置的变化而更新。这可能有什么不对?

1 个答案:

答案 0 :(得分:0)

将您的Http帖子放在一个单独的帖子中。

每当您尝试将您的位置发布到远程服务器时,它需要一些时间,最终可能会阻止onLocationChanged(Location loc)执行,下次由LocationListener调用它。

每次收到位置更新时都可以尝试启动一个新线程,解决方案的问题可能是,根据您的位置更新接收频率,您可能会得到这么多线程。但如果您每小时要求更新位置,这可能不是一个坏主意。

或者您可以将所有网络发布请求放入队列并逐个处理。您甚至可以使用IntentService,也可以按照您的要求使用其他设计模式套件。

关键是处理网络操作异步,因为这样的操作需要时间,在此期间它不会阻止其他键操作执行。

相关问题