简体   繁体   中英

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

In this code, I explain how to send data in json format to server. It uses "RequestParams" to send data to server and get response from server in json format in "JSONObject response".

///////Getting location first///////////

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;
    }

/////////Sending LATLNG in json format to server///////////////

    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();
        }
    }

///////Check network connectivity///////////////////

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;
    }

There is three parts in this question. Part 1: fetching location from device. Part 2: sending data to server Part 3: receiving that data in server. for part 1 How to get Latitude and Longitude of the mobile device in android? follow this link part 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);
        }
    });

part 3: in server side use code like this(Note this code is for jsp)

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

Use this code as per the activity and reciever Here, "LiveLocationResp" is my api response and "LiveLocationreq" is my api request call your api instead of " Apis apis = RetroFitClient.getservices(YOUR_URL); Call liveUpload = apis.liveLocation(liveLocationreq);"

and enque your result and get data this is my working code Here, every on location change event you will upload your current lat lang to the server

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 ;
            }
        });

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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