3

Preface

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

system structure

16202923779379.jpg

For a GPSRecordSystem (GPS track recording system), it is mainly divided into three parts: start recording, record GPS positioning, end recording and store, as shown on the right side of the figure above. In practical applications, take the navigation system as an example: (1) When starting the navigation (start navi), perform the relevant configuration of the recording work; (2) Receive the onLocationChanged callback of the Android system to record the GPSLocation; (3) End When navigating (stop navi), stop recording and save to file.

Related code display

Related variables used

    private LocationManager mLocationManager;   // 系统locationManager
    private LocationListener mLocationListener; // 系统locationListener
    
    private boolean mIsRecording = false;       // 是否正在录制 

    private List<String> mGpsList;              // 记录gps的list
    private String mRecordFileName;             // gps文件名称
  • Start recording

Start recording is usually at the beginning of the whole system work, for example, in the navigation scene, when "start navigation", you can start the configuration of "startRecordLocation"

    public void startRecordLocation(Context context, String fileName) {
        // 已经在录制中不进行录制
        if (mIsRecording) {
            return;
        }
        Toast.makeText(context, "start record location...", Toast.LENGTH_SHORT).show();
        
        // 初始化locationManager和locationListener
        mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        mLocationListener = new MyLocationListener();
        try {
            // 添加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();
        }

// 记录文件名称,笔者这里使用“realLocationRecord + routeID”形式进行记录
        mRecordFileName = fileName;
        if (!mRecordFileName.endsWith(".gps")) {
            mRecordFileName += ".gps";
        }

        mIsRecording = true;
    }
  • Record track during recording

Record location is generally called "recordGPSLocation" when getting the Android system onLocationChanged callback

    public void recordGPSLocation(Location location) {
        if (mIsRecording && location != null) {
        // 记录location to list
            mGpsList.add(locationToString(location));
        }
    }

locationToString tool method

The GPS track points that drive the navigation work generally include the following elements, longitude, latitude, accuracy, angle, speed, time, altitude, so record 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((double) time / 1000.0));
        // sb.append(df.format(System.currentTimeMillis()/1000.0));
        // sb.append(df.format(location.getTime()/1000.0));
        sb.append(",");
        sb.append(location.getAltitude());
        sb.append("\n");
        return sb.toString();
    }
  • End recording and save the gps file

The end of recording is generally used at the end of the entire system, for example, in a navigation scene, when "end navigation", stop recording and call "stopRecordLocation"

    public void stopRecordLocation(Context context) {
        Toast.makeText(context, "stop record location, save to file...", Toast.LENGTH_SHORT).show();
        
        // 移除listener
        mLocationManager.removeUpdates(mLocationListener);
        String storagePath = StorageUtil.getStoragePath(context); // 存储的路径
        String filePath = storagePath + mRecordFileName;

        saveGPS(filePath);
        mIsRecording = false;
    }

GPS track 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

// 存储在跟路径下/TencentMapSDK/navigation
    private static final String NAVIGATION_PATH = "/tencentmapsdk/navigation";

// getStoragePath工具方法
    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()) { // 目录不存在,创建目录
                if (!file.mkdirs()) {
                    strFolder = context.getFilesDir().getPath() + NAVIGATION_PATH;
                    file = new File(strFolder);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                }
            } else { // 目录存在,创建文件测试是否有权限
                try {
                    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;
    }

Result display

Finally stored in the navigation directory under the mobile phone directory

16202872001222.jpg

Follow-up

Later, you can explain the recorded gps file to share the track playback in the navigation scene


腾讯位置服务
1.7k 声望133 粉丝

立足生态,连接未来


引用和评论

0 条评论