如何使用loopj概念在Android中以Json格式在本地服务器上发送当前的纬度和经度数据?

时间:2019-02-14 11:19:06

标签: java android json loopj network-connection

在这段代码中,我解释了如何将json格式的数据发送到服务器。它使用“ RequestParams”将数据发送到服务器,并以“ JSONObject response”的json格式从服务器获取响应。

////////首先获取位置///////////

Location location;

 private Location getLocation() {
        if (isNetworkAvailable( this )) {
            LocationManager locationManager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
            if (locationManager != null) {
                boolean gps_enabled = locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER );
                boolean network_enabled = locationManager.isProviderEnabled( LocationManager.NETWORK_PROVIDER );
                if (ContextCompat.checkSelfPermission( NearMeActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText( NearMeActivity.this, "Turn on location permission", Toast.LENGTH_SHORT ).show();
                } else {
                    if (network_enabled) {
                        locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 5000, 10, this );
                        location = locationManager.getLastKnownLocation( LocationManager.NETWORK_PROVIDER );
                        return location;
                    } else if (gps_enabled) {
                        locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 10, this );
                        location = locationManager.getLastKnownLocation( LocationManager.GPS_PROVIDER );
                        return location;
                    }
                }
            }
        } else {
            Toast.makeText( NearMeActivity.this, R.string.isOnline, Toast.LENGTH_SHORT ).show();
        }
        return null;
    }

//////////将JSON格式的LATLNG发送到服务器///////////////

    public void submitBtn(View view) {
    if (isNetworkAvailable( this )) {
                if (location != null) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    AsyncHttpClient client = new AsyncHttpClient();
                    RequestParams params = new RequestParams();

                    params.put( "latitude", latitude );
                    params.put( "longitude", longitude );
                    String uploadURL = "192.168.1.106";

                    client.post( uploadURL, params, new JsonHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                            try {
                                String status = response.getString( "status" );
                                String msg = response.getString( "msg" );
                                //Toast.makeText( getApplicationContext(), status, Toast.LENGTH_SHORT ).show();
                                if (status.equals( "success" )) {
                                    Toast.makeText( getApplicationContext(), msg, Toast.LENGTH_SHORT ).show();
                                } else if (status.equals( "failed" )) {
                                    Toast.makeText( getApplicationContext(), msg, Toast.LENGTH_SHORT ).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                            //Toast.makeText( getApplicationContext(), R.string.onFailure, Toast.LENGTH_SHORT ).show();
                        }
@Override
                    public void onStart() {
                        progressBar.setVisibility( View.VISIBLE );
                        System.out.println( "onStart" );
                    }

                    @Override
                    public void onFinish() {
                        progressBar.setVisibility( View.INVISIBLE );
                        System.out.println( "onFinish" );
                    }
                } );
            } else {
                Toast.makeText( this, "Getting your current location...", Toast.LENGTH_SHORT ).show();
            }
        } else {
            Toast.makeText( this, R.string.isOnline, Toast.LENGTH_SHORT ).show();
        }
    }

////////检查网络连接///////////////////

private static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService( Context.CONNECTIVITY_SERVICE );
        if (connectivity == null) {
            Log.d( "NetworkCheck", "isNetworkAvailable: No" );
            return false;
        }
        // get network info for all of the data interfaces (e.g. WiFi, 3G, LTE, etc.)
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        // make sure that there is at least one interface to test against
        if (info != null) {
            // iterate through the interfaces
            for (NetworkInfo anInfo : info) {
                // check this interface for a connected state
                if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                    Log.d( "NetworkCheck", "isNetworkAvailable: Yes" );
                    return true;
                }
            }
        }
        return false;
    }

2 个答案:

答案 0 :(得分:0)

根据活动和接收者使用此代码 在这里,“ LiveLocationResp”是我的api响应,“ LiveLocationreq”是我的api请求 调用您的api而不是 “ Apis apis = RetroFitClient.getservices(YOUR_URL);  致电liveUpload = apis.liveLocation(liveLocationreq);“

查询结果并获取数据,这是我的工作代码 在这里,每次发生位置更改事件时,您都会将当前的lat lang上传到服务器上

STATS = as.numeric(df[1,])

答案 1 :(得分:0)

此问题分为三个部分。 第1部分:从设备获取位置。 第2部分:将数据发送到服务器 第3部分:在服务器中接收该数据。 对于第1部分How to get Latitude and Longitude of the mobile device in android?,请点击此链接 第2部分:

AsyncHttpClient client=new AsyncHttpClient();
    RequestParams requestParams=new RequestParams();
    String lati=latitude.getText().toString();
    String longi=longitude.getText().toString();
    requestParams.put("Latitude",lati);
    requestParams.put("Logitude",longi);
    client.post("http://192.168.1.109/LocationApp.json",new JsonHttpResponseHandler(){
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
           //receive the response from server here
        }
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }
    });

第3部分: 在服务器端使用这样的代码(请注意,此代码适用于jsp)

String latitude=request.getParameter("Latitude");
String longitude=request.getParameter("longitude");