preface

In the use of maps, especially in the navigation scene, GPS track recording is very necessary and useful. This paper will share the track recording part under the Android system.

System architecture

A GPSRecordSystem is divided into three parts: start recording, record GPS positioning, and end recording and storage, as shown on the right of the figure above. In practical application, the navigation system is taken as an example :(1) at the start of navigation, the relevant configuration of recording work is carried out; (2) Receiving the callback of Android OnLocationChanged to record GPSLocation; (3) When stop navi, stop recording and save to file.

Related code display

I’m going to use related variables

private LocationManager mLocationManager; // System LocationManager private LocationListener mLocationListener; // System LocationListener private Boolean mIsRecording = false; Private List<String> mGpsList; // List private String mRecordFileName; // GPS file name
  • Start recording

Recording starts at the beginning of the whole system. For example, in a navigation scenario, “Start Navigation” can start the configuration of “StartRecordLocation”

Public void startRecordLocation(Context Context, String fileName) {// already recorded if (misRecording) {return; } Toast.makeText(context, "start record location..." , Toast.LENGTH_SHORT).show(); MLocationManager = (LocationManager) mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); mLocationListener = new MyLocationListener(); Try {/ / add the listener mLocationManager. RequestLocationUpdates (LocationManager GPS_PROVIDER, 0, 0, mLocationListener); } catch (SecurityException e) { Toast.makeText(context, "start record location error!!!" , Toast.LENGTH_SHORT).show(); Log.e(TAG, "startRecordLocation Exception", e); e.printStackTrace(); } // RecordFileName = fileName;} // RecordFileName = fileName; if (! mRecordFileName.endsWith(".gps")) { mRecordFileName += ".gps"; } mIsRecording = true; }
  • RecordGPSLocation is usually called when you get the Android OnLocationChanged callback.
public void recordGPSLocation(Location location) { if (mIsRecording && location ! = null) {// Record location to list mGpsList. Add (LocationToString (Location)); }}

The locationToString utility method

The GPS track points that drive navigation generally contain the following elements, longitude, latitude, accuracy, Angle, speed, time and altitude. Therefore, they are recorded here to prepare for later track playback.

private String locationToString(Location location) { StringBuilder sb = new StringBuilder(); long time = System.currentTimeMillis(); String timeStr = gpsDataFormatter.format(new Date(time)); sb.append(location.getLatitude()); sb.append(","); sb.append(location.getLongitude()); sb.append(","); sb.append(location.getAccuracy()); sb.append(","); sb.append(location.getBearing()); sb.append(","); sb.append(location.getSpeed()); sb.append(","); sb.append(timeStr); sb.append(","); Sb. Append (df) format (1000.0) (double) time /); / / sb. Append (df) format (System. CurrentTimeMillis () / 1000.0)); / / sb. Append (df) format (the location. The getTime () / 1000.0)); sb.append(","); sb.append(location.getAltitude()); sb.append("\n"); return sb.toString(); }
  • End recording and save the GPS file

End recording is generally used at the end of the whole system. For example, in a navigation scene, stop recording when “End navigation” calls “stopRecordLocation”.

public void stopRecordLocation(Context context) { Toast.makeText(context, "stop record location, save to file..." , Toast.LENGTH_SHORT).show(); / / remove the listener mLocationManager. RemoveUpdates (mLocationListener); String storagePath = StorageUtil.getStoragePath(context); // String filePath = StoragePath + mRecordFileName; saveGPS(filePath); mIsRecording = false; }

GPS trajectory storage tool method

    private void saveGPS(String path) {
        OutputStreamWriter writer = null;
        try {
            File outFile = new File(path);
            File parent = outFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            OutputStream out = new FileOutputStream(outFile);
            writer = new OutputStreamWriter(out);
            for (String line : mGpsList) {
                writer.write(line);
            }
        } catch (Exception e) {
            Log.e(TAG, "saveGPS Exception", e);
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG, "Failed to flush output stream", e);
                }
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG, "Failed to close output stream", e);
                }
            }
        }
    }
    

StorageUtil’s getStoragePath tool method

/ / stored in the follow path/TencentMapSDK/navigation under private static final String NAVIGATION_PATH = "/ TencentMapSDK/navigation"; Public static String getStoragePath(Context Context) {if (Context == null) {return null; } String strFolder; boolean hasSdcard; try { hasSdcard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); } catch (Exception e) { Log.e(TAG, "getStoragePath Exception", e); e.printStackTrace(); hasSdcard = false; } if (! hasSdcard) { strFolder = context.getFilesDir().getPath() + NAVIGATION_PATH; File file = new File(strFolder); if (! file.exists()) { file.mkdirs(); } } else { strFolder = Environment.getExternalStorageDirectory().getPath() + NAVIGATION_PATH; File file = new File(strFolder); if (! File.exists ()) {// directory does not exist, create directory if (! file.mkdirs()) { strFolder = context.getFilesDir().getPath() + NAVIGATION_PATH; file = new File(strFolder); if (! file.exists()) { file.mkdirs(); }} else {try {String newFile = StrFolder + "/.test";} else {String newFile = StrFolder + "/.test"; File tmpFile = new File(newFile); if (tmpFile.createNewFile()) { tmpFile.delete(); } } catch (IOException e) { e.printStackTrace(); Log.e(TAG, "getStoragePath Exception", e); strFolder = context.getFilesDir().getPath() + NAVIGATION_PATH; file = new File(strFolder); if (! file.exists()) { file.mkdirs(); } } } } return strFolder; }

The results show

It is eventually stored in the Navigation directory of the phone directory

The follow-up work

Later, we can explain the recorded GPS file and share the track playback under the navigation scene