简体   繁体   English

onLocationChange()-无法发送发布请求

[英]onLocationChange() - cant send post request

I am creating simple GPS tracker. 我正在创建简单的GPS跟踪器。 Application gets gps latitude/longitude and sends it to php on remote server. 应用程序获取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
}

And here is uploadLoc: 这是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) {
       //
    }
}

But i am constantly getting "application has stopped". 但是我一直在“应用程序已停止”。 When i remove line that is calling uploadLoc method, everything works and Toast is updated as location changes. 当我删除调用uploadLoc方法的行时,一切正常,并且Toast随着位置的变化而更新。 What can be wrong here? 这里有什么问题?

Put your Http post in a separate thread. 将您的Http帖子放在单独的线程中。

Every time you are trying to post your location to remote server its take some time which could eventually block your onLocationChanged(Location loc) execution, next time it is called by LocationListener. 每次尝试将位置发布到远程服务器时,都会花费一些时间,这最终可能会阻止onLocationChanged(Location loc)执行,下次由LocationListener调用它。

You can try starting a new thread each time you receive location update and problem with solution would be, based on your location update receiving frequency you might end up with so many thread. 您可以在每次收到位置更新时尝试启动一个新线程,而解决方案的问题将会是,根据您的位置更新接收频率,您最终可能会遇到很多线程。 But if you are requesting location update in every hour this may not be a bad idea. 但是,如果您要求每小时更新一次位置,这可能不是一个坏主意。

Alternatively You can put all your network posting request in a queue and process one by one. 或者,您可以将所有网络发布请求放入队列中,并一一处理。 You can even use IntentService or can also follow other design pattern suites your requirements. 您甚至可以使用IntentService ,也可以遵循您的要求的其他设计模式套件。

Key is to process network operation Asynchronously as such operation take time and during this time it is not blocking other key operation to perform. 关键是异步处理网络操作,因为这种操作需要时间,并且在此期间它不会阻止其他关键操作的执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM