繁体   English   中英

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

[英]How to send current latitude and longitude data on localhost server in Json format in android using loopj concept?

在这段代码中,我解释了如何将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;
    }

这个问题分为三个部分。 第1部分:从设备获取位置。 第2部分:向服务器发送数据第3部分:在服务器中接收数据。 部分1 如何在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");

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

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

public class Your_Activity extends AppCompatActivity {


    private static final String TAG = "YOUR_ACTIVITY";


    public static final int LOCATION_UPDATE_MIN_DISTANCE = 10;
    public static final int LOCATION_UPDATE_MIN_TIME = 5000;
    private LocationManager mLocationManager;
    public static Double latitude = 0.0;
    public static Double longitude = 0.0;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_activity);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
                getCurrentLocation();

            }
        });

    }
    private LocationListener mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            if (location != null & wayPoints!=null && wayPoints.size()!=0) {
                Calendar calendar = Calendar.getInstance();
                String currentDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
                latitude = location.getLatitude();
                longitude = location.getLongitude();

                Log.e("LOCATION UP",String.format("%f, %f", location.getLatitude(), location.getLongitude()));

                Intent intent = new Intent(Your_Activity .this,LiveLocationUploadReceiver.class);
                sendBroadcast(intent);

            } else {
                Log.e("LOCATION","Location is null");
            }
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    };

    @SuppressLint("MissingPermission")
    private void getCurrentLocation() {
        boolean isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        Location location = null;
        if (!(isGPSEnabled || isNetworkEnabled)){

        } else {
            if (isNetworkEnabled) {
                mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                        LOCATION_UPDATE_MIN_TIME, LOCATION_UPDATE_MIN_DISTANCE, mLocationListener);
                location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            }

            if (isGPSEnabled) {
                mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                        LOCATION_UPDATE_MIN_TIME, LOCATION_UPDATE_MIN_DISTANCE, mLocationListener);
                location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            }
        }
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            Log.e("LOCATIONS",String.format("getCurrentLocation(%f, %f)", location.getLatitude(),
                    location.getLongitude()));
        }
    }


}


public class LiveLocationUploadReceiver extends BroadcastReceiver {



    @Override
    public void onReceive(Context context, Intent intent) {


            LiveLocationreq liveLocationreq = new LiveLocationreq();
            liveLocationreq.setLatitude(DemoRouteApi.latitude+"");
            liveLocationreq.setLongitude(DemoRouteApi.longitude+"");
            uploadLiveLocation(liveLocationreq);


    }

    private void uploadLiveLocation(LiveLocationreq liveLocationreq){
        Apis apis = RetroFitClient.getservices(YOUR_URL);
        Call<LiveLocationResp> liveUpload = apis.liveLocation(liveLocationreq);
        liveUpload.enqueue(new Callback<LiveLocationResp>() {
            @Override
            public void onResponse(Call<LiveLocationResp> call, Response<LiveLocationResp> response) {

                String str = new Gson().toJson(response.body());
                Log.e(TAG,str);

            }

            @Override
            public void onFailure(Call<LiveLocationResp> call, Throwable t) {

                return ;
            }
        });

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM