Как я могу получить обновления местоположения для отслеживания, когда другое устройство во время путешествия? - PullRequest
0 голосов
/ 05 марта 2020

Мой проект для отслеживания драйвера с клиентского устройства, как Uber. Что я сделал, так это то, что я выбираю данные о местоположении, отправленные драйвером на сервер с помощью библиотеки залпов, и публикую их на картах Google на стороне пользователя.

Я периодически реализовывал обработчик для получить обновления местоположения, отправленные драйвером. Но мое приложение зависало, выдав неожиданный код ответа 507 и неожиданный код ответа 508 . Мне просто нужна некоторая помощь, поскольку, как я могу получить это, или какая-то справка была бы полезна.

Ниже мой код.

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{

    private final Handler handler = new Handler();
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private GoogleMap mMap;
    String newLatitude = "";
    String newLongitude = "";
    Marker marker;
    Runnable runnable;
    String schoolid, studentid;
    String LocationUrl = Constant.BASE_URL+"selectlocation/";

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

        Bundle bundle = getIntent().getExtras();
        schoolid = bundle.getString("ap_school_fkid");
        studentid = bundle.getString("student_fkid");

        SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.maps);
        if (mapFragment != null) {
            mapFragment.getMapAsync(this);
        }

    }
@Override
    public void onMapReady(final GoogleMap googleMap) {
        Log.d("MapsActivity", "Inside onMapReady");

        mMap = googleMap;
        StringRequest request = new StringRequest(Request.Method.GET, LocationUrl+schoolid+"/"+studentid+"/", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d("MapsActivity", response);
                try {
                    JSONObject object = new JSONObject(response);
                    JSONArray array = object.getJSONArray("resp");
                    for (int i = 0; i < array.length(); i++) {
                        //JSONObject jsonObject = array.getJSONObject(i);
                        if (array.getJSONObject(i).getString("loc_latitude") != null && array.getJSONObject(i).getString("loc_longitude") != null) {
                            newLatitude = array.getJSONObject(i).getString("loc_latitude").trim();
                            newLongitude = array.getJSONObject(i).getString("loc_longitude").trim();
                            Toast.makeText(MapsActivity.this, newLatitude + ", " + newLongitude, Toast.LENGTH_SHORT).show();
                            addmarkerToMap(newLatitude, newLongitude);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        queue.add(request);
        if (!newLatitude.isEmpty() && !newLongitude.isEmpty()) {
            Double lat = Double.parseDouble(newLatitude);
            Double lng = Double.parseDouble(newLongitude);
            LatLng latLng = new LatLng(lat, lng);
            mMap.addMarker(new MarkerOptions().position(latLng).title("I'm Here"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            CameraUpdate location = CameraUpdateFactory.newLatLngZoom(latLng, 17);
            mMap.animateCamera(location);
        }
    }

    private void addmarkerToMap(String newLat, String newLng) {
        double lat = Double.parseDouble(newLat);
        double lng = Double.parseDouble(newLng);
        LatLng latLng = new LatLng(lat, lng);
        MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(lat, lng)).title("I'm Here");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
        mMap.addMarker(markerOptions);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        CameraUpdate location = CameraUpdateFactory.newLatLngZoom(latLng, 17);
        mMap.animateCamera(location);
        new Handler().postDelayed(() -> {
            getLocation();
        }, 3000);

    }

    private void getLocation(){
        Log.d("getLocation", "Refreshed");
        mMap.clear();
        if (mMap!= null){
            if (marker == null){
                StringRequest request = new StringRequest(Request.Method.GET, LocationUrl+schoolid+"/"+studentid+"/", new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject object = new JSONObject(response);
                            JSONArray array = object.getJSONArray("resp");
                            for (int i = 0; i < array.length(); i++) {
                                //JSONObject jsonObject = array.getJSONObject(i);
                                if (array.getJSONObject(i).getString("loc_latitude") != null && array.getJSONObject(i).getString("loc_longitude") != null) {
                                    newLatitude = array.getJSONObject(i).getString("loc_latitude").trim();
                                    newLongitude = array.getJSONObject(i).getString("loc_longitude").trim();
                                    Toast.makeText(MapsActivity.this, "location is refreshed, new Latitude : "+newLatitude+", new Longitude : "+newLongitude, Toast.LENGTH_SHORT).show();
                                    addmarkerToMap(newLatitude, newLongitude);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });


                RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
                queue.add(request);
                if (!newLatitude.isEmpty() && !newLongitude.isEmpty()) {
                    Double lat = Double.parseDouble(newLatitude);
                    Double lng = Double.parseDouble(newLongitude);
                    LatLng latLng = new LatLng(lat, lng);
                    mMap.addMarker(new MarkerOptions().position(latLng).title("I'm Here"));
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                    CameraUpdate location = CameraUpdateFactory.newLatLngZoom(latLng, 17);
                    mMap.animateCamera(location);
                }
            }

        }

    }
}
...