Android 后台记录GPS轨迹并转为80参数service

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bit_kaki/article/details/60867116

          我们知道Android里都是用LocationManager来管理定位相关的操作, LocationListener来进行位置变化时候的监听,获取结果有三种条件下的经纬度坐标。

          于是在写后台service时候主要是将每次监听到的经纬度记录下来,最后在转变为80的坐标。

           核心代码为:

service为:

public class PatrolService extends Service implements
      ICoordinaters<Coordinates> {
   private PatrolStartGPS gps = null;
   private final static String TAG = PatrolService.class.getSimpleName();

   @Override
   public void onCreate() {
      super.onCreate();

      gps = new PatrolStartGPS(this, this);

   }

   @Override
   public void onDestroy() {
      if (gps != null) {
         gps.closeLocation();
         gps.close();
         gps = null;
      }
      super.onDestroy();
   }

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

   @Override
   public void coordinaterUpdate(ArrayList<Coordinates> list) {
      // TODO Auto-generated method stub
      // 发送广播
      Intent intent = new Intent();
      intent.putExtra("saveFlag", "netWork");
      intent.putExtra("saveGps", list);
      intent.setAction("com.diit.patrolservicedemo.PatrolService");
      sendBroadcast(intent);
   }

   @Override
   public void coordinaterLocalStorage(ArrayList<Coordinates> list) {
      // TODO Auto-generated method stub
      // 发送广播
      Intent intent = new Intent();
      intent.putExtra("saveFlag", "local");
      intent.putExtra("saveGps", list);
      intent.setAction("com.diit.patrolservicedemo.PatrolService");
      sendBroadcast(intent);
   }

监听GPS变化轨迹为:

public class PatrolStartGPS {
   private String TAG = PatrolStartGPS.class.getName();

   public ArrayList<Coordinates> coordinatesList;

   public ICoordinaters<Coordinates> mICoordinaters;

   public PatrolStartGPS mPatrolThread = null;

   public LocationManager locationManager;

   public SaveSdcardGps mSaveSdcardGps;

   private Context context;

   public PatrolStartGPS(Context context,
         ICoordinaters<Coordinates> mICoordinaters) {
      this.context = context;
      mSaveSdcardGps = SaveSdcardGps.getSaveSdcardGps();
      this.mICoordinaters = mICoordinaters;
      coordinatesList = new ArrayList<Coordinates>();
      try {
         getLocation();
      } catch (Exception e) {
         // TODO Auto-generated catch block
         mSaveSdcardGps.write(e.getMessage());
      }
   }

   // 获取gps 信息
   public void getLocation() throws Exception {
      locationManager = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);

      String bestProvider = locationManager.getBestProvider(getCriteria(),
            true);
      // 获取位置信息
      // 如果不设置查询要求,getLastKnownLocation方法传人的参数为LocationManager.GPS_PROVIDER
      Location location = locationManager.getLastKnownLocation(bestProvider);
      addCoordinates(location);
      // 设置每2秒获取一次GPS的定位信息
      locationManager.addGpsStatusListener(listener);
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            8000, 8, locationListener);
   }

   private LocationListener locationListener = new LocationListener() {

      /**
       * 位置信息变化时触发
       */
      public void onLocationChanged(Location location) {
         addCoordinates(location);
      }

      /**
       * GPS状态变化时触发
       */
      public void onStatusChanged(String provider, int status, Bundle extras) {
         switch (status) {
         // GPS状态为可见时
         case LocationProvider.AVAILABLE:
            Log.i(TAG, "当前GPS状态为可见状态");
            break;
         // GPS状态为服务区外时
         case LocationProvider.OUT_OF_SERVICE:
            Log.i(TAG, "当前GPS状态为服务区外状态");
            break;
         // GPS状态为暂停服务时
         case LocationProvider.TEMPORARILY_UNAVAILABLE:
            Log.i(TAG, "当前GPS状态为暂停服务状态");
            break;
         }
      }

      /**
       * GPS开启时触发
       */
      public void onProviderEnabled(String provider) {
         Location location = locationManager.getLastKnownLocation(provider);
         addCoordinates(location);
      }

      /**
       * GPS禁用时触发
       */
      public void onProviderDisabled(String provider) {
         addCoordinates(null);
      }

   };
   // 状态监听
   GpsStatus.Listener listener = new GpsStatus.Listener() {
      public void onGpsStatusChanged(int event) {
         switch (event) {
         // 第一次定位
         case GpsStatus.GPS_EVENT_FIRST_FIX:
            Log.i(TAG, "第一次定位");
            break;
         // 卫星状态改变
         case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
            Log.i(TAG, "卫星状态改变");
            break;
         // 定位启动
         case GpsStatus.GPS_EVENT_STARTED:
            Log.i(TAG, "定位启动");
            break;
         // 定位结束
         case GpsStatus.GPS_EVENT_STOPPED:
            Log.i(TAG, "定位结束");
            break;
         }
      };
   };

   /**
    * 返回查询条件
    * 
    * @return
    */
   private Criteria getCriteria() {
      Criteria criteria = new Criteria();
      // 设置定位精确度 Criteria.ACCURACY_COARSE比较粗略,Criteria.ACCURACY_FINE则比较精细
      criteria.setAccuracy(Criteria.ACCURACY_FINE);
      // 设置是否要求速度
      criteria.setSpeedRequired(false);
      // 设置是否允许运营商收费
      criteria.setCostAllowed(false);
      // 设置是否需要方位信息
      criteria.setBearingRequired(false);
      // 设置是否需要海拔信息
      criteria.setAltitudeRequired(false);
      // 设置对电源的需求
      criteria.setPowerRequirement(Criteria.POWER_LOW);
      return criteria;
   }

   // 讲GPS数据放入集合中
   public void addCoordinates(Location mLocation) {
      if (null != mLocation) {
         mSaveSdcardGps.write("Longitude:" + mLocation.getLongitude()
               + " , Latitude: " + mLocation.getLatitude() + ";");
         coordinatesList.add(new Coordinates(mLocation.getLongitude(),
               mLocation.getLatitude()));
         run();
      } else {
      }
   }

   public void run() {
      // TODO Auto-generated method stub
      // 当前有网络的进行数据传输
      if (NetWorkUtils.isNetworkAvailable(context)) {
         mICoordinaters.coordinaterUpdate(coordinatesList);
      } else {
         // 当前没有网络进行本地保存
         mICoordinaters.coordinaterLocalStorage(coordinatesList);
      }
   }

   /**
    * 关闭GPS保存操作
    */
   public void close() {
      mSaveSdcardGps.close();
   }

   /**
    * 清楚GPS
    */
   public void closeLocation() {
      if (locationManager != null) {
         if (locationListener != null) {
            locationManager.removeUpdates(locationListener);
            locationListener = null;
         }
         locationManager = null;
      }
   }

保存坐标点(这里用的是保存到个txt里)

public class SaveSdcardGps {
   public static SaveSdcardGps mSaveSdcardGps = null;
   private FileOutputStream stream = null;

   public static SaveSdcardGps getSaveSdcardGps() {
      if (null == mSaveSdcardGps) {
         mSaveSdcardGps = new SaveSdcardGps();
      }
      return mSaveSdcardGps;
   }

   private SaveSdcardGps() {
      writeFileToSD("开始写入GPS坐标文件!");
   }

   public void writeFileToSD(String gpsStr) {
      String sdStatus = Environment.getExternalStorageState();
      if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
         Log.d("TestFile", "SD card is not avaiable/writeable right now.");
         return;
      }
      try {
         String pathName = Environment.getExternalStorageDirectory()+"/ydzfjc/";
         String fileName = "file.txt";
         File path = new File(pathName);
         File file = new File(pathName + fileName);
         if (!path.exists()) {
            path.mkdir();
         }
         if (!file.exists()) {
            file.createNewFile();
         }
         stream = new FileOutputStream(file);
         byte[] buf = gpsStr.getBytes();
         stream.write(buf);
         stream.write("\n".getBytes());
         stream.flush();

      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public void write(String writes) {

      try {
         if (stream != null) {
            byte[] buf = writes.getBytes();
            stream.write(buf);
            stream.flush();
         }
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }

   public void close() {
      try {
         stream.close();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
}
启动服务和广播的方法:

new Thread(new Runnable() {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        Looper.prepare();
        // PatrolThread mPatrolThread = new PatrolThread(
        // WebServicePlugin.this);
        try {
            ContextUtil.getContext()
                    .startService(new Intent(ContextUtil.getContext(), PatrolService.class));
        }catch (Exception e){
            e.printStackTrace();
        }
        // 注册广播
        MyReceiver receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.diit.patrolservicedemo.PatrolService");
        ContextUtil.getContext().registerReceiver(receiver, filter);

    }
}).start();
// 获取广播数据
private class MyReceiver extends BroadcastReceiver {

    @SuppressWarnings("unchecked")
    @Override
    public void onReceive(Context context, Intent intent) {

        Bundle bundle = intent.getExtras();
        ArrayList<Coordinates> list = (ArrayList<Coordinates>) bundle.getSerializable("saveGps");
        String saveFlag = intent.getStringExtra("saveFlag");
        if (saveFlag.equals("netWork")) {
            coordinaterUpdate(list);
        } else if (saveFlag.equals("local")) {
            coordinaterLocalStorage(list);
        }

    }
}

最后附上demo代码地址:

http://download.csdn.net/detail/bit_kaki/9774055

没有更多推荐了,返回首页