STM32 developing GPS locator for GPRS transmission android studio developing client APP displaying track

The previous article introduces how to develop the positioner hardware, SCM software, server software, upper computer client software. The following describes how to use android studio to develop the client APP display track.

What you can do by yourself never asks people. In front of you, you used C ා to realize the display and location data trace on the PC side. The process of developing the trace on the APP on the client side with android studio is the same. It's just the different development languages. Android applications are developed in Java, but C # and Java are very similar.

 

Using android studio to develop the client APP to display the trace can be divided into several steps: 1. Writing xml file; 2. Communication with TCP server; 3. Calling Baidu map API to draw the trace.

1. Add the XML layout file to Baidu map mapview and two text boxes. The code and UI interface are as follows

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context="com.example.myapplication.MainActivity">

    <com.baidu.mapapi.map.MapView
        android:id="@+id/bmapview"
        android:layout_width="match_parent"
        android:layout_height="400dp"
        android:clickable="true" />
    <TextView
    android:id="@+id/Text2view"
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:text="---"
    android:layout_below="@id/bmapview"/>
    <TextView
        android:id="@+id/Textview"
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:text="---"
        android:layout_below="@id/Text2view"/>
</RelativeLayout>

2. Write the communication program between TCP and server

This part mainly consists of three threads, one for connecting to the server, one for sending data to the server, and one for receiving data from the server.

To connect to the server thread, you need to check whether the connection between the Android client and the server is effective in real time, do disconnection and reconnection, and start the sending data thread and receiving data thread. The program is as follows

private class connectToServer extends Thread{
        @Override
        public void run() {
            while(true)
            {
                try
                {
                    //Client sends connection request to server
                    //c_Socket = new Socket("---.---.---.---",8888);
                    if (c_Socket==null)
                    {
                        c_Socket = new Socket("---.---.---.---",8888);
                        if (c_Socket.isConnected())
                        {
                            TCP_R_Count=0;
                            int port = c_Socket.getLocalPort();
                            Message msg = new Message();
                            msg.what = 5;
                            msg.obj = String.valueOf(port);
                            mHandler.sendMessage(msg);
                            c_readflag = true;
                            new c_ReadThread().start();
                            new SenfToServer().start();
                            connect=true;
                        }

                    }
                    if(connect==false)
                    {
                        if(c_Socket!=null){
                            c_Socket.close();
                            c_Socket=null;
                        }

                    }

                    //c_Socket = new Socket("192.168.5.32",8888);
                    //c_Socket.connect(IPAddress.Parse(c_ip.getText().toString()), Int32.Parse(c_port.Text));
                }catch(Exception ee)
                {
                    ee.printStackTrace();
                }
            }
            //super.run();
        }

    }

At present, this part of the sending thread is relatively simple, and will gradually enrich with the increase of functions.

    //Client sends data to server
    private class SenfToServer extends Thread{
        @Override
        public void run() {
            while(true)
            {
                if(c_Socket!=null){
                    if (c_Socket.isConnected())
                    {
                        try{
                            out = c_Socket.getOutputStream();
                            out.write("----------------".getBytes());
                            out.flush();
                            SenfToServer.sleep(60000);
                        }
                        catch(Exception e){
//                        connect=false;
                        }
                    }
                }
            }
            //super.run();
        }
    }

Receiving thread

The receiving thread receives the GPS positioning data from the server, and passes the message to the main thread through the Handler. Check the validity of the TCP connection here, and reconnect the server if you are disconnected.

    //Client receives information from server
    private class c_ReadThread extends Thread
    {
        @Override
        public void run() {
            // Method stubs generated automatically by TODO
            try {
                InputStream input = c_Socket.getInputStream();
                while (c_readflag)
                {
                    byte[] buff = new byte[100];

                    int size = input.read(buff);
                    if((size>12)){
                        if((buff[0]=='$')&&(buff[1]=='3')&&(buff[12]!=0)){
                            Message msg = new Message();
                            msg.what =4;
                            msg.obj = new String(buff,0,size);
                            latitude_o=latitude_n;
                            longitude_o=longitude_n;
                            latitude_n=new String(buff,20,7);
                            longitude_n=new String(buff,12,8);

                            Log.i("n","Latitude:"+latitude_n+" | Longitude:"+longitude_n);

                            if((latitude_n!="00.0000")&&(longitude_n!="000.0000")){
                                mHandler.sendMessage(msg);
                            }else{
                                latitude_n=null;
                                longitude_n=null;
                            }
                        }
                    }
                    if(size>0)
                    {
                        TCP_R_Count=TCP_R_Count+size;
                        Message msg = new Message();
                        msg.what =5;
                        mHandler.sendMessage(msg);
                    }
                }
            } catch (IOException e) {
                // The catch block automatically generated by TODO
                e.printStackTrace();
                connect=false;
            }
            super.run();
        }
    }

3. Call Baidu map API to realize trace drawing

First, get the map component added in xml, mMapView = (MapView) findViewById(R.id.bmapview);    
mBaiduMap = mMapView.getMap(); set map zoom level mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(21).build())); after that, use overlay mpolyline = mbaidumap. Addoverlay (muveryoptions); add two-point connection section by section to finally form the track in the above figure. Update the coordinate position to make the last position coordinate as the center of the map mBaiduMap.animateMapStatus(u); note that there is a deviation between the longitude and latitude received from the GPS satellite and the longitude and latitude of Baidu map, and use the following methods to correct the deviation. CoordinateConverter converter1  = new CoordinateConverter().from(CoordinateConverter.CoordType.GPS).coord(p1); LatLng desLatLng1 = converter1.convert();

The key codes are as follows

mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what ==4){
                    if((latitude_n!=null) &&(longitude_n!=null)&&(latitude_o!=null) &&(longitude_o!=null)){

                        List<LatLng> points = new ArrayList<LatLng>();
                        LatLng p1,p2 ;
                        p1=new LatLng( Double.parseDouble(latitude_n),Double.parseDouble(longitude_n));
                        // sourceLatLng coordinates to be converted

                        CoordinateConverter converter1  = new CoordinateConverter()
                                .from(CoordinateConverter.CoordType.GPS)
                                .coord(p1);
                        LatLng desLatLng1 = converter1.convert();
                        points.add(desLatLng1);

                        Log.i("P1","Latitude:"+desLatLng1.latitude+" | Longitude:"+desLatLng1.longitude);

                        p2=new LatLng( Double.parseDouble(latitude_o),Double.parseDouble(longitude_o));
                        // sourceLatLng coordinates to be converted

                        CoordinateConverter converter2  = new CoordinateConverter()
                                .from(CoordinateConverter.CoordType.GPS)
                                .coord(p2);
                        LatLng desLatLng2 = converter2.convert();
                        points.add(desLatLng2);

                        Log.i("P2","Latitude:"+desLatLng2.latitude+" | Longitude:"+desLatLng2.longitude);

                        //Set properties for polylines
                        OverlayOptions mOverlayOptions = new PolylineOptions()
                                .width(10)
                                .color(0xAAFF0000)
                                .points(points);
                        Overlay mPolyline = mBaiduMap.addOverlay(mOverlayOptions);
                        //if(((latitude_n.equals(latitude_o))&&(longitude_n.equals(longitude_o))))
                        {

                            //Define Maker coordinate points
                            LatLng p3;
                            p3=new LatLng( Double.parseDouble(latitude_n),Double.parseDouble(longitude_n));

                            // sourceLatLng coordinates to be converted

                            CoordinateConverter converter3  = new CoordinateConverter()
                                    .from(CoordinateConverter.CoordType.GPS)
                                    .coord(p3);
                            LatLng desLatLng3 = converter3.convert();
                            /*
                            //Build Marker Icon
                            BitmapDescriptor bitmap = BitmapDescriptorFactory
                                    .fromResource(R.drawable.icon_w);
                            //Build MarkerOption to add a Marker to a map
                            OverlayOptions option = new MarkerOptions()
                                    .position(desLatLng3)
                                    .icon(bitmap);
                            //Add Marker to the map and display
                            mBaiduMap.addOverlay(option);
                            */
                            // Construct location data
                            MyLocationData locData = new MyLocationData.Builder()
                                    .accuracy(0)    //Setting accuracy
                                    .direction(0)		 // Set the direction information obtained by the developer here, clockwise 0-360
                                    .latitude(desLatLng3.latitude)  	 	// Set latitude coordinates
                                    .longitude(desLatLng3.longitude)    //Set longitude coordinates
                                    .build();
                            // Set location data
                            mBaiduMap.setMyLocationData(locData);
                            //Set custom positioning icon
                            BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                                    .fromResource(R.drawable.icon_w);
                            mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;  //Set positioning mode
                            //Location construction method, which will locate the mode and define the icon to add
                            MyLocationConfiguration config = new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker);
                            mBaiduMap.setMyLocationConfigeration(config);  //Map display location Icon

                            MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(desLatLng3);  //Update coordinate position
                            mBaiduMap.animateMapStatus(u);                            //Set map location
                        }



                        //Get TextView component showing LocationProvider name
                        TextView textView = (TextView) findViewById(R.id.Textview);
                       // StringBuilder stringBuilder = new StringBuilder(); / / use StringBuilder to save data
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
                        Date date = new Date(System.currentTimeMillis());
                        String str=simpleDateFormat.format(date);

                        textView.setText("");
                        textView.append(str + "\n");
                        textView.append(("N Latitude:"+desLatLng1.latitude).toString() + "\n");
                        textView.append(("N Latitude:"+desLatLng2.latitude).toString() + "\n");
                        textView.append(("O Longitude:"+desLatLng1.longitude).toString() + "\n");
                        textView.append(("O Longitude:"+desLatLng2.longitude).toString() + "\n");
                    }
                }
                if(msg.what ==5){
                    TextView textView = (TextView) findViewById(R.id.Text2view);
                    textView.setText("receive is  "+Integer.toString(TCP_R_Count));
                }
                super.handleMessage(msg);
            }

        };

 

Published 44 original articles, won praise 19, visited 10000+
Private letter follow

Tags: Android xml socket Java

Posted on Sat, 11 Jan 2020 05:58:44 -0800 by robinas