如何将gps位置值传递给android中的其他类?

时间:2016-09-22 16:03:51

标签: android gps

我使用类来获取lat和lon值,在检查后我确认数据是正确的,但是我面临的问题是如何将值传递给其他函数并将其发送到php脚本以便我可以存储值。这两个功能属于同一类。下面是我的获取位置类代码。

从这里我得到gps值。

public void get_location(){

    // Acquire a reference to the system Location Manager
    LocationManager locationManager = (LocationManager) LoginActivity.this.getSystemService(Context.LOCATION_SERVICE);
    // Define a listener that responds to location updates
    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Called when a new location is found by the network location provider.
            String lat = Double.toString(location.getLatitude());
            String lon = Double.toString(location.getLongitude());
        }
        public void onStatusChanged(String provider, int status, Bundle extras) {}
        public void onProviderEnabled(String provider) {}
        public void onProviderDisabled(String provider) {}
    };
    // Register the listener with the Location Manager to receive location updates
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

}

我需要将值传递给此函数,以便它可以发送到服务器。

public class SendPostRequest extends AsyncTask<String, Void, String> {

    protected void onPreExecute(){}

    protected String doInBackground(String... arg0) {

        try {
            URL url = new URL("http://localhost.com/save.php"); 

            JSONObject postDataParams = new JSONObject();
            postDataParams.put("lat", lat);
            postDataParams.put("lon", lon);
            Log.e("params",postDataParams.toString());

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();

            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                BufferedReader in=new BufferedReader(new
                        InputStreamReader(
                        conn.getInputStream()));

                StringBuffer sb = new StringBuffer("");
                String line="";

                while((line = in.readLine()) != null) {

                    sb.append(line);
                    break;
                }

                in.close();
                return sb.toString();

            }
            else {
                return new String("false : "+responseCode);
            }
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }

    }

    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getApplicationContext(), result,
                Toast.LENGTH_LONG).show();
    }
}

public String getPostDataString(JSONObject params) throws Exception {

    StringBuilder result = new StringBuilder();
    boolean first = true;

    Iterator<String> itr = params.keys();

    while(itr.hasNext()){

        String key= itr.next();
        Object value = params.get(key);

        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(key, "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(value.toString(), "UTF-8"));

    }
    return result.toString();
}

这是我执行asyn任务的功能

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new SendPostRequest().execute();

}

2 个答案:

答案 0 :(得分:0)

只需更改代码的这一部分:

public class SendPostRequest extends AsyncTask<Double, Void, String> {

protected void onPreExecute(){}

protected String doInBackground(Double... arg0) {

    try {
        URL url = new URL("http://localhost.com/save.php"); 

        JSONObject postDataParams = new JSONObject();
        postDataParams.put("lat", args[0]);
        postDataParams.put("lon", args[1]);

执行AsyncTask:

 new SendPostRequest().execute(lat,lon);

答案 1 :(得分:0)

创建一个全局Double数组(非常基本):

static Double[] arr;

onCreate

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new SendPostRequest().execute(arr); //changes made here
}

您的get_location方法:

public void get_location(){

    // Acquire a reference to the system Location Manager
    LocationManager locationManager = (LocationManager) LoginActivity.this.getSystemService(Context.LOCATION_SERVICE);
    // Define a listener that responds to location updates
    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Called when a new location is found by the network location provider.
            // getting location of user, don't parse to string latlng has to double
            double lat = location.getLatitude();
            double lon = location.getLongitude();
            arr[0] = lat; //changes made here
            arr[1] = lon; //changes made here

        }
        public void onStatusChanged(String provider, int status, Bundle extras) {}
        public void onProviderEnabled(String provider) {}
        public void onProviderDisabled(String provider) {}
    };
    // Register the listener with the Location Manager to receive location updates
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

}

将值传递给Asynctask

public class SendPostRequest extends AsyncTask<Double, Void, String> {

    protected void onPreExecute(){}

    protected String doInBackground(Double arr) {

        try {
            URL url = new URL("http://localhost.com/save.php"); 

            JSONObject postDataParams = new JSONObject();
            postDataParams.put("lat", arr[0]); //changes made here
            postDataParams.put("lon", arr[1]); //changes made here
            Log.e("params",postDataParams.toString());

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();

            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                BufferedReader in=new BufferedReader(new
                        InputStreamReader(
                        conn.getInputStream()));

                StringBuffer sb = new StringBuffer("");
                String line="";

                while((line = in.readLine()) != null) {

                    sb.append(line);
                    break;
                }

                in.close();
                return sb.toString();

            }
            else {
                return new String("false : "+responseCode);
            }
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }

    }

    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getApplicationContext(), result,
                Toast.LENGTH_LONG).show();
    }
}

public String getPostDataString(JSONObject params) throws Exception {

    StringBuilder result = new StringBuilder();
    boolean first = true;

    Iterator<String> itr = params.keys();

    while(itr.hasNext()){

        String key= itr.next();
        Object value = params.get(key);

        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(key, "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(value.toString(), "UTF-8"));

    }
    return result.toString();
}