每秒从服务访问数据到地图活动

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了每秒从服务访问数据到地图活动相关的知识,希望对你有一定的参考价值。

我创建了一个服务来从服务器接收车辆的位置并将其存储在LatLng的ArrayList中。它的工作正常。我想在地图活动中显示车辆的实时位置,并显示路径。我能够在地图活动本身上显示当前位置。地图工作正常。

但问题是如何从服务访问Arraylist位置并在地图活动中显示更新的位置?

我曾尝试使用广播接收器,但没有工作。

lo CS而V.Java :-

public class LocServ extends Service implements LocationListener {

    private static final Location TODO = null;
    //  private static String url_insert_location = "http://172.20.10.4/testing/insert.php";
    public static String LOG = "Log";
    public static ArrayList<latlong> arr_lac = new ArrayList<latlong>();

    static String journy_id;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
        Log.i(LOG, "Service started");
        Log.i("asd", "This is sparta");
        journy_id = intent.getStringExtra("jid");

        Log.i("journy_id",journy_id);
       new SendPostRequest().execute();

        Log.i("1234", "In onStartCommand");
        new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Intent broadcastIntent = new Intent();
                broadcastIntent.setAction(Track_Vehicle_loc.mBroadcastStringAction);
                broadcastIntent.putExtra("Data", "Broadcast Data");
                sendBroadcast(broadcastIntent);

                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                broadcastIntent.setAction(Track_Vehicle_loc.mBroadcastIntegerAction);
                broadcastIntent.putExtra("Data", 10);
                sendBroadcast(broadcastIntent);

                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                broadcastIntent
                        .setAction(Track_Vehicle_loc.mBroadcastArrayListAction);
                broadcastIntent.putExtra("Data", arr_lac);
                sendBroadcast(broadcastIntent);
            }
        }).start();

        return START_STICKY;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(LOG, "Service created");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(LOG, "Service destroyed");
    }


    public class SendPostRequest extends AsyncTask<String, Void, String> {

        protected void onPreExecute(){

        }

        protected String doInBackground(String... arg0) {


            try {

                URL url = new URL("http://test.in/Api/getLocation.php/?"); // here is your URL path


                JSONObject postDataParams = new JSONObject();
                postDataParams.put("tripid", journy_id);
                Log.e("params",postDataParams.toString());

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString(postDataParams));

                writer.flush();
                writer.close();
                os.close();

                int responseCode=conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {

                    BufferedReader in=new BufferedReader(new
                            InputStreamReader(
                            conn.getInputStream()));

                    StringBuffer sb = new StringBuffer("");
                    String line="";

                    while((line = in.readLine()) != null) {

                        sb.append(line);
                        break;
                    }

                    in.close();
                    return sb.toString();

                }
                else {
                    return new String("false : "+responseCode);
                }
            }
            catch(Exception e){
                return new String("Exception: " + e.getMessage());
            }

        }

        @Override
        protected void onPostExecute(String result) {

            try {
                Log.i("1234","result:" + result);
                if (result != null) {
                    final JSONObject jsobj = new JSONObject(result);
                    Log.i("jsobj",""+jsobj);
                    final String success_code = jsobj.getString("success");
                    final String success_message = jsobj.getString("message");

                    Log.i("success_code",""+success_code);
                    Log.i("success_message",""+success_message);


                            if (success_code.equals("1")) {
                                try {
                                    JSONArray j_details = jsobj.getJSONArray("data");
                                    Log.i("1234", "j_details:" + j_details);

                                    for (int i=0;i<j_details.length();i++) {
                                        JSONObject jobj = j_details.getJSONObject(i);

                                        latlong ld = new latlong();

                                        final Double lat = jobj.getDouble("lat");
                                        final Double longi = jobj.getDouble("longi");

                                        ld.setLat(lat);
                                        ld.setLongi(longi);
                                        arr_lac.add(ld);

                                    }


                                } catch (JSONException ex) {
                                    Log.i("Exception", ex.toString());
                                }
                            }
                            else
                            {
                            }


                    Log.e("pass 1", "connection success ");

                } else {
                }

            }catch (Exception e){
                Log.i("Exception",e.toString());
            }
        }
    }

    public String getPostDataString(JSONObject params) throws Exception {

        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator<String> itr = params.keys();

        while (itr.hasNext()) {

            String key = itr.next();
            Object value = params.get(key);

            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));

        }
        return result.toString();
    }


    @Override
    public void onLocationChanged(Location location) {
    new SendPostRequest().execute();

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

maps activity.Java :-

public class Track_Vehicle_loc extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    // check if GPS enabled
    GPSTracker gpsTracker;
    String tripid;
    static Double startlat, startlongi, current_lat, current_longi;
    Polyline line; //added
    BookingData dataobj = new BookingData();
    SharedPreferences sharedpreferences;
    String Url,mobile_number,otp;
    public static final String MyPREFERENCES = "MyPrefs" ;

    public static final String Latkey = "latkey";
    public static final String Longkey = "longkey";

    public static ArrayList<latlong> arr_lac = new ArrayList<latlong>();

    public static final String mBroadcastStringAction = "com.truiton.broadcast.string";
    public static final String mBroadcastIntegerAction = "com.truiton.broadcast.integer";
    public static final String mBroadcastArrayListAction = "com.truiton.broadcast.arraylist";
    private IntentFilter mIntentFilter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_track__vehicle_loc);

        gpsTracker = new GPSTracker(getApplicationContext());
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        Intent i = getIntent();
        dataobj = (BookingData) i.getSerializableExtra("bookdata");

        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(mBroadcastStringAction);
        mIntentFilter.addAction(mBroadcastIntegerAction);
        mIntentFilter.addAction(mBroadcastArrayListAction);

        Intent serviceIntent = new Intent(getApplicationContext(), LocServ.class);
        serviceIntent.putExtra("jid", dataobj.getJ_Id());
        startService(serviceIntent);
    }
    @Override
    public void onResume() {
        super.onResume();
        registerReceiver(mReceiver, mIntentFilter);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
           if (intent.getAction().equals(mBroadcastStringAction)) {
                Toast.makeText(context, "234"+intent.getStringExtra("Data"), Toast.LENGTH_SHORT).show();
           } else if (intent.getAction().equals(mBroadcastIntegerAction)) {
                Toast.makeText(context, "234"+intent.getIntExtra("Data",0), Toast.LENGTH_SHORT).show();
        } else if (intent.getAction().equals(mBroadcastArrayListAction)) {
                Toast.makeText(context, "234"+intent.getStringArrayListExtra("Data"), Toast.LENGTH_SHORT).show();
  }
        }
    };

    @Override
    protected void onPause() {
        unregisterReceiver(mReceiver);
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        stopService(new Intent(getApplicationContext(), LocServ.class));
        finish();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        Double latitude = gpsTracker.getLatitude();
        Double longitude = gpsTracker.getLongitude();
        mMap = googleMap;
        mMap.clear();
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
             return;
        }
        mMap.setMyLocationEnabled(true);

        LatLng sydny = new LatLng(latitude, longitude);

        final MarkerOptions marker = new MarkerOptions().position(sydny).title("Vehicle");

        int height = 100;
        int width = 100;
        BitmapDrawable bitmapdraw=(BitmapDrawable)getResources().getDrawable(R.drawable.caricon);
        Bitmap b=bitmapdraw.getBitmap();
        Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);

        marker.icon(BitmapDescriptorFactory.fromBitmap(smallMarker));

        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sydny, 16.0f));
        mMap.addMarker(marker);

        final Handler handler = new Handler();
        final int delay = 1000; //milliseconds

     //   Log.i("arr_lac",arr_lac+"156");
        handler.postDelayed(new Runnable(){
            public void run(){
               // arr_lac = LocServ.arr_lac;
                handler.postDelayed(this, delay);
            }
        }, delay);
/*
        if(arr_lac.size() > 2) {

            int index = arr_lac.size() - 1;

            latlong ll = arr_lac.get(index);

            current_lat = ll.getLat();
            current_longi = ll.getLongi();

            Log.i("current_lat",current_lat+"156");


         *//*   PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
            for (int i = 0; i < arr_lac.size(); i++) {
                LatLng point = new LatLng(arr_lac.get(i).getLat(),arr_lac.get(i).getLongi());
                options.add(point);
            }
            final Marker myMarker = mMap.addMarker(marker); //add Marker in current position
            line = googleMap.addPolyline(options); //add Polyline
            //  setmarker(ll.getLat(), ll.getLongi(), mMap);
            update_position(myMarker,ll.getLat(),ll.getLongi());

            startlat = current_lat;
            startlongi = current_longi;*//*

        }
*/

    }

    public String getPostDataString(JSONObject params) throws Exception {

        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator<String> itr = params.keys();

        while(itr.hasNext()){

            String key= itr.next();
            Object value = params.get(key);

            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));

        }
        return result.toString();
    }

    public void setmarker(Double stringLatitude,Double stringLongitude,GoogleMap googleMap){

        Log.i("latlong",stringLatitude+"");
        Log.i("latlong",stringLongitude+"");
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(stringLatitude, stringLongitude);
        // create marker
        MarkerOptions marker = new MarkerOptions().position(sydney).title("Vehicle");

        int height = 100;
        int width = 100;
        BitmapDrawable bitmapdraw=(BitmapDrawable)getResources().getDrawable(R.drawable.caricon);
        Bitmap b=bitmapdraw.getBitmap();
        Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);

        marker.icon(BitmapDescriptorFactory.fromBitmap(smallMarker));
        mMap.addMarker(marker);
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(stringLatitude,stringLongitude), 13));

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(stringLatitude,stringLongitude))      // Sets the center of the map to location user
                .zoom(17)                   // Sets the zoom
                .bearing(90)                // Sets the orientation of the camera to east
                .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                .build();                   // Creates a CameraPosition from the builder
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));


    }

    public void update_position(Marker marker,Double lat,Double lati){
        marker.setPosition(new LatLng(lat,lati));
    }
}
答案

你正在向arraylist发送一个你应该尝试这个link的活动

你必须添加arraylist作为你的MyCustomEvent()类的参数

另一答案

使用JSONArray作为帮助程序将位置数据序列化为字符串...

On the send side "serialize" using JSONArray

// assume 'myPos' is your ArrayList<LatLng> with your position data.

JSONArray ja = new JSONArray();
for (LatLng p : myPos) {
    JSONObject jo = new JSONObject();
    jo.put("lat", p.latitude);
    jo.put("lng", p.longitude);
    ja.put(jo);
}

Intent intent = new Intent();
intent.putExtra("data", ja.toString());

And on receiving end:

// 'rxPos' is your receiving array list...
ArrayList<LatLng> rxPos = new ArrayList<LatLng>();

String s = intent.getStringExtra("data");
JSONArray jaRx = new JSONArray(s);

for (int i = 0; i < jaRx.length(); i++) {
    JSONObject jo = jaRx.getJSONObject(i);
    rxPos.add(new LatLng(jo.getDouble("lat"), jo.getDouble("lng")));
}

可能值得一提的是捆绑有一个大小限制,但不确定确切的数字 - 512kb?

以上是关于每秒从服务访问数据到地图活动的主要内容,如果未能解决你的问题,请参考以下文章

如何将活动 UI 的点击传递到地图片段以将地图更改为 MAP_TYPE_HYBRID

使用绑定从片段访问父活动的 UI 元素

从片段访问父活动的数据

Android:使用 putExtra 从片段访问容器活动对象?

从片段访问数据库以在列表中显示

启动谷歌地图意图后返回活动