如何使用LOOPJ概念在Android中以JSON格式发送Localhost服务器上的当前纬度和经度数据



在此代码中,我解释了如何以JSON格式将数据发送到服务器。它使用" requestParams"将数据发送到服务器,并以" JSONOBJECT响应"中的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;
    }
    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);"

并将您的结果加油并获取数据,这是我的工作代码在这里,每个位置更改事件您都会将当前的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 ;
            }
        });
    }
}

相关内容

  • 没有找到相关文章

最新更新