簡體   English   中英

無法更新緯度和經度

[英]Can't update latitude and longitude

這是我班

package com.example.seadog.gps;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 5000; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {

            } else {
                this.canGetLocation = true;

                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }

                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}

這是我的asyncTask:

class MyAsyncTask extends AsyncTask<JSONObject, Void, JSONObject> {

    @Override
    protected void onPreExecute() {

    }

    protected JSONObject doInBackground(JSONObject... params) {

        int ID=0;
        int random=0;
        int Code=0;

        String string = null;

        double latitude;
        double longitude;

        try {
            JSONObject json = params[0];
            ID = Integer.parseInt(json.getString("ID"));
            random = Integer.parseInt(json.getString("random"));
            Code = Integer.parseInt(json.getString("Code"));
        } catch (Exception e){
            e.printStackTrace();
        }

        int i=0;

        while(i<1){

            latitude = gps.getLatitude();
            longitude = gps.getLongitude();

            try {
                JSONObject json = new JSONObject();
                json.put("ID", ID);
                json.put("random", random);
                json.put("latitude", latitude);
                json.put("longitude", longitude);
                json.put("Code", Code);

                string = "json="+json;

            } catch (Exception e){
                e.printStackTrace();
            }

            try {

                URL url = new URL("http://10.0.2.2/gps.php");

                HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
                httpCon.setDoOutput(true);
                httpCon.setDoInput(true);
                httpCon.setUseCaches(false);
                httpCon.setConnectTimeout(15000);
                httpCon.setRequestProperty("Content-Length", Integer.toString(string.length()));
                httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                httpCon.setRequestMethod("POST");

                DataOutputStream wr = new DataOutputStream(httpCon.getOutputStream());
                wr.writeBytes(string);
                wr.flush();
                wr.close();

                int responseCode = httpCon.getResponseCode();

                if(Code==0){

                    if (responseCode==-1) { httpCon.connect(); }

                    InputStream is = httpCon.getInputStream();
                    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
                    String line;
                    StringBuffer response = new StringBuffer();
                    while((line = rd.readLine()) != null) {
                        response.append(line);
                        response.append('\r');
                    }
                    rd.close();

                    String result = response.toString();

                    JSONObject json = new JSONObject(result);

                    try {

                        OutputStream file = openFileOutput("configND", Context.MODE_PRIVATE);
                        DataOutputStream wrf = new DataOutputStream(file);
                        wrf.writeBytes(result);
                        wrf.close();

                        random = Integer.parseInt(json.getString("random"));
                        Code=1;

                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }

                if (responseCode == 200) {
                    Thread.sleep(3000);
                }else{
                    httpCon.disconnect();
                }

            } catch (Exception e1) {
                e1.printStackTrace();
            }

        }

        return null;

    }

    protected void onPostExecute(Boolean result) {

    }

}

在asyncTask中,我通過gps.getLatitude和gps.getLongitude將緯度和經度稱為兩個Double變量。 首次運行的應用返回GPS位置,但不再進行迭代(我的意思是在asyncTask中睡眠3秒)。

如何在一段時間內更新緯度和經度?

要將定期更新發送到服務器,我建議您使用Android AsyncHttp Client,它是一個不錯的庫,它將使您節省一些時間。

至於你的問題:

您的API調用應位於第一個類的OnLocationChanged中。 例如:

@Override
public void onLocationChanged(Location location) {
 sendLocationToServer(location, new MyAsyncHttpResponseHandler());
}

您可以將您的位置作為Json tring發送,但隨后您需要對其進行Jsonize。 您也可以將“緯度和經度”作為“字符串”放入參數中。

 private void sendLocationToServer(Location location, AsyncHttpResponseHandler handler){
    RequestParams params = new RequestParams();
    params.put(MY_LOCATION_PARAMETER_KEY,locationAsJson);
    getClient().post("mydomain.com/update/device/location",params, handler);
}

然后管理您的處理程序:

private class MyAsyncHttpResponseHandler extends AsyncHttpResponseHandler{

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
    //Check the server response
    } else{
    //Notify user of error type
    }

}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody,     Throwable error) {
 //Notify user of connection error
}
}  

從我的閱讀中,我只能看到冰山一角。 但這應該為您指明正確的方向。 祝好運。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM