Android Open Source - LocationUpdate Location Send Task






From Project

Back to project page LocationUpdate.

License

The source code is released under:

Copyright (c) 2011 Stefan A. van der Meer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to dea...

If you think the Android project LocationUpdate listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.meernet.LocationUpdate;
// www  .  j  a v  a  2  s .com
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.location.Location;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;
import android.util.Pair;

public class LocationSendTask extends AsyncTask<Location, Void, Pair<Boolean, String>> {
    static final String TAG = "LocationSendTask";

    private final URL destination;
    private final SendService parent;
    private Location submittedLocation;

    public LocationSendTask(SendService parent, URL destination) {
        this.destination = destination;
        this.parent = parent;

    }

    @Override
    protected Pair<Boolean, String> doInBackground(Location... locs) {
        submittedLocation = locs[0];
        return sendCoordinates(submittedLocation);
    }

    /**
     * Construct a list of keyvals containing the information on the location
     * that we want to send.
     *
     * Currently, this is only the latitude and longitude.
     *
     * @param coordinate    The location.
     * @return              Keyval params to be encoded in the HTTP request.
     */
    private List<NameValuePair> buildRequestParameters(Location coordinate) {
        List<NameValuePair> params = new ArrayList<NameValuePair>(2);

        params.add(new BasicNameValuePair("lat", Double.toString(coordinate.getLatitude())));
        params.add(new BasicNameValuePair("lon", Double.toString(coordinate.getLongitude())));

        return params;
    }

    /**
     * Construct a HttpPost request that, when executed, will send the given
     * parameters to the destination server.
     *
     * @param params    Keyval pairs that will be sent to the server
     * @return          The HttpPost request
     */
    private HttpPost buildRequest(List<NameValuePair> params)
        throws URISyntaxException, IOException {

        // Construct a request that will send the coordinate
        HttpPost req = new HttpPost(destination.toURI());
        req.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        return req;
    }

    /**
     * Execute an HTTP request.
     *
     * @param req               The HTTP POST request.
     * @return                  True if request succeeded.
     * @throws ParseException
     * @throws IOException
     */
    private boolean executeRequest(HttpPost req) throws ParseException, IOException {
        AndroidHttpClient client = null;
        try {
            client = AndroidHttpClient.newInstance("Android");
            HttpResponse response = client.execute(req);

            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == HttpStatus.SC_OK) {
                Log.d(TAG, EntityUtils.toString(response.getEntity()));
                return true;
            } else {
                // Shouldn't the http client throw this itself?
                throw new HttpResponseException(statusCode, String.format("Server response %d != 200", statusCode));
            }
        } finally {
            if (client != null) {
                Log.d(TAG, "Closing http client");
                // android's http client requires closing, will leak otherwise
                client.close();
            }
        }
    }

    /**
     * Send GPS coordinate to the server
     *
     * @param coordinate    The location to send.
     * @return              Pair of a boolean indicating success or failure,
     *                      plus a string containing an error message to report
     *                      to the user in case of failure.
     */
    private Pair<Boolean, String> sendCoordinates(Location coordinate) {

        // This function is 99% exception handling and communicating those
        // errors to the user. The real meat is in the other functions.

        Pair<Boolean, String> result = null;

        // Build the HTTP request
        HttpPost req = null;
        try {
            req = buildRequest(buildRequestParameters(coordinate));

        } catch (URISyntaxException e) {
            result = Pair.create(false, "Invalid destination URL: " + destination);
            Log.e(TAG, result.second, e);
        } catch (IOException e) {
            // shouldn't happen, as we should never have un-encodable bad values
            result = Pair.create(false, "Bad values when building request");
            Log.wtf(TAG, result.second, e);
        }

        if (req == null) {
            Log.e(TAG, "No request could be built, send task fails.");
            return result;
        }

        // Execute the HTTP request
        try {
            boolean req_result = executeRequest(req);
            result = Pair.create(req_result, null);

        } catch (ClientProtocolException e) {
            result = Pair.create(false, "HTTP error: " + e.getMessage());
            Log.e(TAG, result.second, e);
        } catch (IOException e) {
            result = Pair.create(false, "Connection problem: " + e.getMessage());
            Log.e(TAG, result.second, e);
        } catch (ParseException e) {
            result = Pair.create(false, "Failed to parse server response");
            Log.e(TAG, result.second, e);
        } catch (RuntimeException e) {
            result = Pair.create(false, "Failed to send data to server: " + e.getMessage());
            Log.e(TAG, result.second, e);
        }

        return result;
    }

    /**
     * After completing the task, display the result.
     */
    protected void onPostExecute(Pair<Boolean, String> result) {
        parent.onSendTaskComplete(result.first, result.second, submittedLocation);
    }
}




Java Source Code List

com.meernet.LocationUpdate.BootReceiver.java
com.meernet.LocationUpdate.LocationSendTask.java
com.meernet.LocationUpdate.LocationUpdatePrefs.java
com.meernet.LocationUpdate.LocationUpdate.java
com.meernet.LocationUpdate.SendService.java