初学者求助:为GPS定位代码添加定时器及共享GPS.json文件
嘿,作为编程新手能把GPS获取逻辑跑通已经超棒啦!针对你提的两个问题,我给你整理了具体的实现思路和代码示例,一步步来:
1. 实现每10分钟获取GPS位置并写入GPS.json
首先,你已经有了能正常工作的MyLocationListener,接下来要做的是定时触发定位请求,并把获取到的位置数据写入JSON文件。这里推荐用ScheduledExecutorService来实现定时任务,它比普通的Timer更可靠,尤其是在处理后台任务时。
步骤拆解:
- 初始化定时任务调度器,设置每10分钟执行一次定位+保存任务
- 在任务中触发单次GPS定位(避免持续监听耗电)
- 获取到位置后,将数据追加到
GPS.json文件中(用JSON数组格式存储多条记录)
代码示例:
假设你已经有LocationManager实例和MyLocationListener,可以这样整合:
import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.json.JSONArray; import org.json.JSONObject; import android.location.Location; import android.location.LocationManager; // 初始化定时调度器 ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); // 立即执行第一次任务,之后每10分钟执行一次 scheduler.scheduleAtFixedRate(() -> { // 触发单次GPS定位(根据你的LocationManager实例调整) locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, new MyLocationListener() { @Override public void onLocationChanged(Location location) { super.onLocationChanged(location); // 获取到位置后,写入JSON文件 saveLocationToJson(location); // 移除监听,避免重复回调 locationManager.removeUpdates(this); } }, null); }, 0, 10, TimeUnit.MINUTES); // 保存位置到GPS.json的方法 private void saveLocationToJson(Location location) { try { // Android环境推荐用内部/外部私有存储路径,避免权限问题 File gpsFile = new File(getExternalFilesDir(null), "GPS.json"); JSONArray jsonArray; // 如果文件不存在,创建新的JSON数组;否则读取现有数组 if (!gpsFile.exists()) { jsonArray = new JSONArray(); } else { FileReader reader = new FileReader(gpsFile); StringBuilder sb = new StringBuilder(); int ch; while ((ch = reader.read()) != -1) { sb.append((char) ch); } reader.close(); jsonArray = new JSONArray(sb.toString()); } // 将位置信息封装为JSONObject JSONObject locationObj = new JSONObject(); locationObj.put("latitude", location.getLatitude()); locationObj.put("longitude", location.getLongitude()); locationObj.put("timestamp", location.getTime()); locationObj.put("accuracy", location.getAccuracy()); // 添加到数组并写入文件(格式化输出方便阅读) jsonArray.put(locationObj); FileWriter writer = new FileWriter(gpsFile); writer.write(jsonArray.toString(4)); writer.close(); } catch (Exception e) { e.printStackTrace(); } }
注意:如果是Android平台,你需要申请
ACCESS_FINE_LOCATION权限,后台定位还需要ACCESS_BACKGROUND_LOCATION;要在页面销毁或应用退出时调用scheduler.shutdown()关闭调度器,防止内存泄漏。
2. 在其他类中共享GPS.json文件
要让其他类方便访问这个文件,最简洁的方式是封装一个工具类,统一管理文件的路径和读写操作,避免每个类都重复写文件路径和IO逻辑。
实现思路:
- 创建一个
GPSFileUtil工具类,提供获取文件实例、读取JSON数据、写入数据的静态方法 - 其他类直接调用工具类的方法即可,无需关心文件的具体存储位置
代码示例:
import java.io.File; import java.io.FileReader; import java.io.FileWriter; import org.json.JSONArray; import org.json.JSONObject; import android.content.Context; import android.location.Location; public class GPSFileUtil { // 定义GPS.json的存储路径(通过Context获取私有存储目录) public static File getGPSFile(Context context) { return new File(context.getExternalFilesDir(null), "GPS.json"); } // 读取GPS.json中的所有位置数据 public static JSONArray readGPSData(Context context) { File gpsFile = getGPSFile(context); if (!gpsFile.exists()) { return new JSONArray(); } try { FileReader reader = new FileReader(gpsFile); StringBuilder sb = new StringBuilder(); int ch; while ((ch = reader.read()) != -1) { sb.append((char) ch); } reader.close(); return new JSONArray(sb.toString()); } catch (Exception e) { e.printStackTrace(); return new JSONArray(); } } // 追加位置数据到GPS.json(加synchronized保证线程安全) public static synchronized boolean appendLocation(Context context, Location location) { try { JSONArray jsonArray = readGPSData(context); JSONObject locationObj = new JSONObject(); locationObj.put("latitude", location.getLatitude()); locationObj.put("longitude", location.getLongitude()); locationObj.put("timestamp", location.getTime()); locationObj.put("accuracy", location.getAccuracy()); jsonArray.put(locationObj); FileWriter writer = new FileWriter(getGPSFile(context)); writer.write(jsonArray.toString(4)); writer.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } }
这样,其他类需要访问GPS数据时,直接调用:
// 读取所有位置数据 JSONArray gpsData = GPSFileUtil.readGPSData(getApplicationContext()); // 写入新的位置数据 GPSFileUtil.appendLocation(getApplicationContext(), newLocation);
小提示:如果多个类可能同时读写文件,
synchronized关键字能避免文件读写冲突,保证数据一致性。
内容的提问来源于stack exchange,提问作者pere plop




