Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将GPS位置发送到Web服务_Java_Android_Google Maps - Fatal编程技术网

Java 将GPS位置发送到Web服务

Java 将GPS位置发送到Web服务,java,android,google-maps,Java,Android,Google Maps,我正在尝试将我的位置坐标发送到web服务,我有一个名为“LocationService”的类,该类可以执行此操作,但在执行应用程序时,什么都没有发生 定位服务 public class LocationService extends Service implements LocationListener{ public String LOG = "Log"; UserSessionManager session; private Context mContext = null; boole

我正在尝试将我的位置坐标发送到web服务,我有一个名为“LocationService”的类,该类可以执行此操作,但在执行应用程序时,什么都没有发生

定位服务

public class LocationService extends Service implements LocationListener{

public String LOG = "Log";
UserSessionManager session;

private Context mContext = null;

boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
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 = 0; // 0 meters

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

// Declaring a Location Manager
protected LocationManager locationManager;

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

public LocationService() {
    super();
    mContext = LocationService.this;
}

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
    Log.i(LOG, "Service started");
    Log.i("asd", "This is sparta");

    HashMap<String, String> user = session.obtenerRolyId();
    String usuarioId = user.get(UserSessionManager.KEY_ID);

    new SendToServer().execute(Double.toString(getLocation().getLongitude()), Double.toString(getLocation().getLatitude()),usuarioId);

    return START_STICKY;
}


@Override
public void onCreate() {
    super.onCreate();
    Log.i(LOG, "Service created");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.i(LOG, "Service destroyed");
}

class SendToServer extends AsyncTask<String, String, String> {


    @Override
    protected String doInBackground(String... la) {

        try {

            HttpURLConnection urlConnection = null;
            String posicionActual = "";
            BufferedReader reader = null;
            OutputStream os = null;
            InputStream inputStream = null;

            Log.i("string", la[0]);
            String longi = la[0];      // Recibo la longitud.
            String lati = la[1];       // Recibo la latitud.
            String idUsuario = la[2];  // Recibo Id del usuario.

            JSONObject coordenadas = new JSONObject();
            coordenadas.put("Latitud",lati);
            coordenadas.put("Longitud",longi);

            posicionActual = coordenadas.toString();

            URL url = new URL("http://localhost:8081/odata/Usuarios("+idUsuario+")/ActualizarPosicion");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);

            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");


            urlConnection.connect();

            os = new BufferedOutputStream(urlConnection.getOutputStream());
            os.write(posicionActual.getBytes());


        } catch (Exception e) {
            Log.i("error", e.toString());
        }

        return "call";
    }
}

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) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                //updates will be send according to these arguments
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                }
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    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;
}




@Override
public void onLocationChanged(Location location) {
    //Llamo al servidor cada segundo y le envío mi posición
    HashMap<String, String> user = session.obtenerRolyId();
    String usuarioId = user.get(UserSessionManager.KEY_ID);
    new SendToServer().execute(Double.toString(getLocation().getLongitude()),Double.toString(getLocation().getLatitude()), usuarioId);


}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}}

要开始,请将权限检查移动到onstart命令,只需检查一次。请让用户授予您权限,很简单:

ActivityCompat.requestPermissions(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION, SINGLE_PERMISSION_REQUEST_CODE);

public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
        d(TAG,"Permission " + permissions[0] +" granted");
    }
}
然后,在onLocationChange中替换以下内容:

new SendToServer().execute(Double.toString(getLocation().getLongitude()), Double.toString(getLocation().getLatitude()),usuarioId);
用这个

new SendToServer().execute(Double.toString(location.getLongitude()), Double.toString(location.getLatitude()),usuarioId);
您已经从提供程序获得了最后一个位置,不必再从getLastKnownLocation获取它

在服务器连接中,您应该添加以下内容以检查一切是否正常:

os.flush();
os.close();
int serverResponse = urlConnection.getResponseCode();
String serverMsg = urlConnection.getResponseMessage();
urlConnection.disconnect();
Log.d(TAG, "Code: " + serverResponse + " - Menssage: " + serverMsg);

添加logcat的输出以了解问题所在
os.flush();
os.close();
int serverResponse = urlConnection.getResponseCode();
String serverMsg = urlConnection.getResponseMessage();
urlConnection.disconnect();
Log.d(TAG, "Code: " + serverResponse + " - Menssage: " + serverMsg);