首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将GPS位置发送到Web Service

将GPS位置发送到Web Service
EN

Stack Overflow用户
提问于 2017-05-30 16:00:59
回答 1查看 54关注 0票数 0

我试图将我的位置坐标发送到web服务,我有一个名为"LocationService“的类可以这样做,但是在执行应用程序的时候没有发生任何事情.

LocationService

代码语言:javascript
运行
复制
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) {

}}

我从活动中打电话给我的服务:

代码语言:javascript
运行
复制
    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_map);

    startService(new Intent(UserMapActivity.this, LocationService.class));}
EN

回答 1

Stack Overflow用户

发布于 2017-05-30 17:30:52

首先,将权限检查移到onStartCommand,只需检查一次。请让用户给你许可,这很简单:

代码语言:javascript
运行
复制
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中替换如下:

代码语言:javascript
运行
复制
new SendToServer().execute(Double.toString(getLocation().getLongitude()), Double.toString(getLocation().getLatitude()),usuarioId);

有了这个

代码语言:javascript
运行
复制
new SendToServer().execute(Double.toString(location.getLongitude()), Double.toString(location.getLatitude()),usuarioId);

您已经从提供程序获得了最后一个位置,您不必再从getLastKnownLocation获得它

在服务器连接中,您应该添加此选项,以检查所有操作是否正常:

代码语言:javascript
运行
复制
os.flush();
os.close();
int serverResponse = urlConnection.getResponseCode();
String serverMsg = urlConnection.getResponseMessage();
urlConnection.disconnect();
Log.d(TAG, "Code: " + serverResponse + " - Menssage: " + serverMsg);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44266938

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档