在我的应用程序中,正在绘制从Web服务到Google地图的一组经度和纬度,但是当Web服务中的经度和纬度发生变化时,标记不会移动。当我关闭并打开应用程序时,它会更新更改,但是我需要移动标记而无需关闭并重新启动应用程序。我的更新代码如下。

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_layout_one, container, false);


        MapsInitializer.initialize(getActivity());

        mMapView = (MapView)rootView.findViewById(R.id.mapView);
        mMapView.onCreate(mBundle);


        MapsInitializer.initialize(getActivity());

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        /* new DownloadJSON().execute();
        setUpMapIfNeeded(rootView); */
        /*
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                 new DownloadJSON().execute();
                    setUpMapIfNeeded(rootView);

                 Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
                 Log.d("Data in Log", "");
            }
        }, 10*1000);*/

        new DownloadJSON().execute();
        setUpMapIfNeeded(rootView);

        LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
        //locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
        locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 000, 10, this);



        return rootView;
    }

    private void setUpMapIfNeeded(View inflatedView) {
        if (mMap == null) {
            mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
            mMap.setMyLocationEnabled(true);

            Location myLocation = mMap.getMyLocation();
            if (mMap != null) {
                // setUpMap();
                mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

                    @Override
                    public void onMyLocationChange(Location arg0) {

                        // TODO Auto-generated method stub

                        final LatLngBounds.Builder builder = new LatLngBounds.Builder();
                        for (int i = 0; i < arraylist1.size(); i++) {
                            final LatLng position = new LatLng(Double
                                    .parseDouble(arraylist1.get(i).get("Latitude")),
                                    Double.parseDouble(arraylist1.get(i).get(
                                            "Longitude")));
                            String ime1 = arraylist1.get(i).get("IME");
                            final MarkerOptions options = new MarkerOptions()
                            .position(position);

                            mMap.addMarker(options);
                            mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
                            //options.title(ime1);
                            builder.include(position);
                        }
                        LatLng latLng = new LatLng(arg0.getLatitude(), arg0
                                .getLongitude());

                        mMap.setMyLocationEnabled(true);

                        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                        // mMap.setOnMapClickListener(null);
                        mMap.setOnMarkerClickListener(null);

                        mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
                    }
                });

            }
        }
    }

    /*  protected void retrieveAndAddCities() throws IOException {
        HttpURLConnection conn = null;
        final StringBuilder json = new StringBuilder();
        try {

            URL url = new URL(SERVICE_URL);
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                json.append(buff, 0, read);
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error connecting to service", e);
            throw new IOException("Error connecting to service", e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        new DownloadJSON().execute();

    } */

    private class DownloadJSON extends AsyncTask<Void, Void, Void> {
        String result="";
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                arraylist1 = new ArrayList<HashMap<String, String>>();

                JSONParser jParser = new JSONParser();
                String result = "";

                json = jParser.getJSONFromUrl(SERVICE_URL);

                try {
                    arraylist1.clear();

                    jsonarray = json.getJSONArray("SingleIMEs");
                    Log.d("Haaaaaaaaaaaa", "" + json);

                    for (int i = 0; i < jsonarray.length(); i++) {
                        Log.d("H11111111111111111111111111",
                                "" + jsonarray.length());
                        map = new HashMap<String, String>();
                        json = jsonarray.getJSONObject(i);

                        // pubname = json.getString("PubName");
                        latitude = json.getDouble("Latitude");
                        longitude = json.getDouble("Longitude");
                        ime = json.getString("IME");
                        //  map.put("PubName", json.getString("PubName"));
                        //map.put("PubID", json.getString("PubID"));
                        map.put("Latitude", json.getString("Latitude"));
                        map.put("Longitude", json.getString("Longitude"));
                        map.put("IME", json.getString("IME"));
                        arraylist1.add(map);
                    }

                } catch (JSONException e) {
                    Log.e("log_tag", "Error parsing data " + e.toString());
                    result="Error";
                    e.printStackTrace();
                }
            }catch(Exception e){
                result="Error";
            }

            return null;
        }

        protected void onPostExecute(Void args) {

            // mProgressDialog.dismiss();

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        mMapView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

        Toast.makeText(getActivity(), "onLocationUpdated!!!", Toast.LENGTH_SHORT).show();
        Log.d("onLocationUpdated!!!","");
        new DownloadJSON().execute();
        setUpMapIfNeeded(rootView);

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String provider) {

        // TODO Auto-generated method stub

    }

}

最佳答案

您可以使用处理程序来更新位置。在run()内部只需调用该Web服务,然后将标记放在当前位置即可。

// Call current location API after 3 Min
    handler.postDelayed(run, 3000 * 60);

    Runnable run = new Runnable() {
            @Override
            public void run() {
                if (isConnected(context)) {
                    new CurrentPosTask().execute();
                } else {
                    Toast.makeText(context, "No internet connection",
                            Toast.LENGTH_LONG).show();
                }

            }
        };


不要忘记将下面的方法调用到onDestroy()方法中

 // Stop the handler
        handler.removeCallbacks(run);


希望对您有帮助。完成后让我知道。

10-07 19:41
查看更多