简体   繁体   中英

onLocationChange() - cant send post request

I am creating simple GPS tracker. Application gets gps latitude/longitude and sends it to php on remote server.

@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:

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. What can be wrong here?

Put your Http post in a separate thread.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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