package com.qiyou.mb.android.service;

import java.util.ArrayList;
import java.util.HashMap;
import android.app.IntentService;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.qiyou.mb.android.QiYouApplication;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.TrackStatus;
import com.qiyou.mb.android.utils.enums.TrackType;
import com.qiyou.mb.android.utils.enums.wpFlag;
import com.qiyou.mb.android.utils.log.QLog;

public class LocationService extends IntentService {
//public class LocationService extends  Service {

	public final static String TAG = "com.qiyou.LOCATION_SERVICE";
	public static final String dTAG = "com.qiyou";
	protected boolean isForceUpdate = false;

	

/*	@Override
	public void onStart(Intent intent, int startId) {
		QLog.getLogger().d(dTAG,TAG+"... service LOCATION_SERVICE onStart.....," );
		if(intent!=null)
			handleIntent(intent);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId){
		QLog.getLogger().d(dTAG,TAG+"... service LOCATION_SERVICE onStartCommand.....," );
		handleIntent(intent);
	    // We want this service to continue running until it is explicitly
	    // stopped, so return sticky.
		 return START_STICKY;		
	}
	*/
	
	public LocationService() {
		super(TAG);
	}

	public LocationService(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}

	protected QiYouApplication app;

	@Override
	public void onCreate() {
		super.onCreate();
		app = (QiYouApplication) this.getApplication();
//		app.reviewTrackStatus();
	    isPlayback =app.playBack && QiYouConstant.PLAYBACK_CAN_RECORD;
		trackType = app.getRecordingTrack().getTrackBean().getType();
		MAX_TIME_UPDATE_DB = Utils.get_updatedb_invterval(trackType);
//		QLog.getLogger().dLog(TAG," LocationService is created....................................................... ");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
////		@Override
//		protected void handleIntent(Intent intent) {
		// TODO Auto-generated method stub

		String key;
		Bundle extras = intent.getExtras();

	/*	key =QiYouConstant.STOP_LOCATION_SERVICE;
		if (intent.hasExtra(key)) {
			stopSelf();
		}
		*/
		
		key = QiYouConstant.EXTRA_KEY_BOOT;
		// QLog.getLogger().d(dTAG,TAG+"intent.hasExtra(key), Key, app.isLastTrackExist():"+intent.hasExtra(key)
		// +" , "+key+" , "+ app.isLastTrackExist());

		if (intent.hasExtra(key)) {
			if (app.isLastTrackExist()) {
				app.restoreLastTracking();
//				QLog.getLogger().dLog(dTAG,		TAG		+ " ----------$%@#$^%$$%^ Restore tracking on boot.............%$%^%%^&@#$#%%^---");
			}
		}
	/*	key = QiYouConstant.EXTRA_KEY_TICK_UPDATE; 
		if (intent.hasExtra(key)) {
			QLog.getLogger().d(dTAG,TAG+ " ----------$%@#$^%$$%^ EXTRA_KEY_TICK_UPDATE get notice to check gps..............%$%^%%^&@#$#%%^---");
			updateGPSstatus();
			return;
		}*/
		
		isForceUpdate =false;
		
		key = QiYouConstant.EXTRA_KEY_FORCE_UPDATE;
		if (intent.hasExtra(key)) {
//	    	 QLog.getLogger().dLog(TAG," LocationService got the alarm notice.  ");

	    	 try{
	    		 
	    	
			    	 
					if (!app.isOneRequestForceUpdate){
						
//						app.updateStatistics(); // changed to:1. each save new wapwpoints, 2. finish recording 
						
						if (app.getRecordingTrack().getTrackBean().getLastdbTime() == 0
								|| System.currentTimeMillis()
										- app.getRecordingTrack().getTrackBean()
												.getLastdbTime() < QiYouConstant.MAX_TIME_FORCE_UDATE)
					
							return;
					}
					
					
					if (app.isOneRequestForceUpdate)
						app.isOneRequestForceUpdate = false;
		
					isForceUpdate = extras.getBoolean(key);
					// Toast toast= Toast.makeText(this,
					// "begin force update... track status: "+app.getRecordingTrack().getTrackBean().getStatus()
					// +",last db update time since now(s): "
					// +(System.currentTimeMillis() -
					// app.getRecordingTrack().getTrackBean().getLastdbTime())/1000,
					// Toast.LENGTH_SHORT );
					// toast.show();
					//
					/*QLog.getLogger().dLog(TAG, 
									 " begin force update... track status:"
									+ app.getRecordingTrack().getTrackBean()
											.getStatus()
									+ ",since last db update time (s) :"
									+ (System.currentTimeMillis() - app
											.getRecordingTrack().getTrackBean()
											.getLastdbTime()) / 1000);*/
		
					processLocation(new Location(QiYouConstant.LOCATION_FORCE_UPDATE));
		
					if (app.isAppLong() && app.isLastTrackExist()
							&& (app.recordingTrack == null || app.isGPSstopped)) {
						app.restoreLastTracking();
//						QLog.getLogger().d(dTAG,					TAG						+ " ----------$%@#$^%$$%^ Restore tracking by ForceUpdate.............%$%^%%^&@#$#%%^---");
					} else if (app.isAppLong()
							&& app.getRecordingTrack().getTrackBean().getStatus() != TrackStatus.RECORDING) {
//						QLog.getLogger().d(dTAG, TAG + " Application start time since now(s): "		+ (System.currentTimeMillis() - app.startTime) / 1000);
						app.cancelForceDbAlarm();
						app.stopAndroidGPSRequest();
						return;
					}
			 }catch (Exception er){
				 Utils.logStackTrace(er, dTAG);
	    	 }
			return;
		}

		// 记录运动轨迹
		key = LocationManager.KEY_LOCATION_CHANGED; // get location from gps

		try{
		
		if (intent.hasExtra(key)) {
//			 QLog.getLogger().dLog(TAG," Location Service got new location. ");
			if ( app.getRecordingTrack().getTrackBean().getStatus() !=TrackStatus.RECORDING){
//				 QLog.getLogger().dLog(TAG,"  app.getRecordingTrack().getTrackBean().getStatus()" +app.getRecordingTrack().getTrackBean().getStatus());
//				 QLog.getLogger().dLog(TAG,"  Location got, No active tracking exits, stopping gps request...");
				app.stopAndroidGPSRequest();
				return;
			}
//			app.lastNaviLocation= (Location) extras.get(key);
//			 QLog.getLogger().d(dTAG,TAG+" "+ "gg Location got, and ready to process.");. 
			
//			Location loc =!isPlayback? app.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER):(Location) extras.get(key);
//			processLocation(loc);
			processLocation((Location) extras.get(key));
		 return;
		}
		}catch(Exception er){
			 Utils.logStackTrace(er, TAG);
		}
		
		
		
		key =	QiYouConstant.EXTRA_KEY_FINISH_RECORDING;
		
		if (intent.hasExtra(key)) {
			isCleanning=true;
			this.preUpdatedb(false);
//			QLog.getLogger().dLog(dTAG,"------------------------ cache  cleaned--------------------------"  );

		}
		

	}
	boolean isCleanning;
	// update ui, then update db
//	String KEY_PAUSETIME = "PAUSETIME";
	// String KEY_OFFTIME="OFFTIME";
	String KEY_AVBEAR = "AVBEAR";
	boolean isFirstwp ;
	TrackType trackType;
	long MAX_TIME_UPDATE_DB;// = Utils.get_updatedb_invterval(trackType);
	
	
	void processLocation(Location location) {
		
	/*	if(location!=null &&location.getSpeed()>0){
			QLog.getLogger().dLog(TAG," loacation accuracy:" +location.getAccuracy());
			QLog.getLogger().dLog(TAG," loacation speed:" +location.getSpeed());
		}*/
		
		
		boolean isGpsLocation =Utils.isLocOfGPS(location);
//		MAX_TIME_UPDATE_DB = Utils.get_updatedb_invterval(trackType);
		isFirstwp = (isPlayback ||isGpsLocation) && app.getRecordingTrack().getTrackBean().getTrackId() == 0;
		isFirstwp = isFirstwp && app.getRecordingTrack().getTrackBean().getStartTime()==0;
		isFirstwp = isFirstwp && !app.isRestoreLastTracking; 
		isFirstwp = isFirstwp && location.getSpeed()>0; 
		
		if(isFirstwp){
			 
			/*if(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL<2)
				app.speech("卫星定位成功，记录开始",0);*/
			app.SpDist = 0;
			
			
//			app.setCntKm((int)((app.getRecordingTrack().getTrackBean().getDistance()+500)/1000));  
			 
//			app.timeKm=System.currentTimeMillis();		
//			QLog.getLogger().dLog(TAG,"------------------------ isFirstwp: -----------------------------" +isFirstwp);
		}
		if(app.timeKm==0){
			app.timeKm=System.currentTimeMillis();
		}
		boolean isReturn =!isForceUpdate && location == null ||
							!isPlayback
							&& !isForceUpdate 
							&& (location.getTime() < app.getRecordingTrack().getTrackBean().getLastWp().getWb().getTime());
		
		
		
	 
		
//		 QLog.getLogger().dLog(TAG," Location is here 1 ");
		if (isReturn){
//			QLog.getLogger().dLog(TAG," !isForceUpdate && location == null,  " + (!isForceUpdate && location == null));
//			QLog.getLogger().dLog(TAG," !isPlayback	&& !isForceUpdate && location.getTime() < app.getRecordingTrack().getTrackBean().getLastWp().getWb().getTime()" 
//									+(!isPlayback && !isForceUpdate  && (location.getTime() < app.getRecordingTrack().getTrackBean().getLastWp().getWb().getTime())));
//			QLog.getLogger().dLog(TAG,"returned");
			return;
		}
	
	/*	
		if(!isFirstwp && !isPlayback && location.getSpeed() >0 ||QiYouConstant.DEVELOPER_MODE){
			//to filter out the suddenly high speed.

			String pearTag="PEARTAG";
			if(app.lastLocation!=null
 					&& app.lastLocation.getSpeed()>0 
					&& location.getTime() -app.lastLocation.getTime()<4* QiYouConstant.MAX_GPS_SPAN
					&& location.getSpeed()>2*app.lastLocation.getSpeed() 
					&& location.getSpeed()>2*app.getRecordingTrack().getTrackBean().getAvs()/3.6){
				
				QLog.getLogger().dLog(TAG,pearTag, "  Get one peak point!-------");
				QLog.getLogger().dLog(TAG,pearTag, "  location.getSpeed() "+location.getSpeed()*3.6);
				QLog.getLogger().dLog(TAG,pearTag, "  app.lastLocation.getSpeed() "+app.lastLocation.getSpeed()*3.6);
				QLog.getLogger().dLog(TAG,pearTag, "  2*app.getRecordingTrack().getTrackBean().getAvs()  "+ 2*app.getRecordingTrack().getTrackBean().getAvs() );
				return;
			
			}
			
			
		}*/
		
		/* if(!isFirstwp && !isPlayback && location.getSpeed() >0){
			//to filter out the suddenly high speed.

				String pearTag="PEARTAG";
				 
				QLog.getLogger().dLog(TAG,pearTag, "  location.getSpeed() "+location.getSpeed());
				QLog.getLogger().dLog(TAG,pearTag, " location.getTime() -app.lastLocation.getTime()<4* QiYouConstant.MAX_GPS_SPAN "+(location.getTime() -app.lastLocation.getTime()<4* QiYouConstant.MAX_GPS_SPAN));
				QLog.getLogger().dLog(TAG,pearTag, " location.getSpeed()>2*app.getRecordingTrack().getTrackBean().getAvs()/3.6 "+(location.getSpeed()>2*app.getRecordingTrack().getTrackBean().getAvs()/3.6));
								 
				
			if(app.lastLocation!=null
//					&& app.lastLocation.getSpeed()>0 
					&& location.getTime() -app.lastLocation.getTime()<4* QiYouConstant.MAX_GPS_SPAN
					&& location.getSpeed()>2*app.lastLocation.getSpeed() 
					&&location.getSpeed()>2*app.getRecordingTrack().getTrackBean().getAvs()/3.6){
				
				QLog.getLogger().dLog(TAG,pearTag, "  Get one peak point!-------");
//				QLog.getLogger().dLog(TAG,pearTag, "  location.getSpeed() "+location.getSpeed());
//				QLog.getLogger().dLog(TAG,pearTag, "  app.lastLocation.getSpeed() "+app.lastLocation.getSpeed());
//				QLog.getLogger().dLog(TAG,pearTag, "  2*app.getRecordingTrack().getTrackBean().getAvs()/3.6 "+ 2*app.getRecordingTrack().getTrackBean().getAvs()/3.6);
//				 
				
				
				if(app.toDecideLocations==null){
					app.toDecideLocations=new ArrayList<Location>();  
					app.toDecideLocations.add(location); 
					
					return;
				}else{
					
					QLog.getLogger().dLog(TAG,pearTag, " app.toDecideLocations.contains(location) "+app.toDecideLocations.contains(location));
					
					if(app.toDecideLocations.contains(location)){//the location is okay to save
						app.toDecideLocations.remove(location);		
						
					}else{//compare with exits ones to decide exists ones to be cleared or allowed
						
						
						QLog.getLogger().dLog(TAG,pearTag, " app.toDecideLocations.size() "+app.toDecideLocations.size());
						
						if(app.toDecideLocations.size()>2){
							app.toDecideLocations.add(location);
							
						 	for(Location loc:app.toDecideLocations){
								QLog.getLogger().dLog(dTAG, pearTag, "location to be allowed for suddenly big speed is:"+loc.getSpeed());
							}
							
							for(Location loc:app.toDecideLocations){
								processLocation(loc);
							}
							return;
						}
						Location lastLoc =app.toDecideLocations.get(app.toDecideLocations.size()-1);
						if(location.getSpeed()>lastLoc.getSpeed()){//new one speed is large than last
							app.toDecideLocations.add(location);
						}else{// new speed is not bigger than last in 
							
							 for(Location loc:app.toDecideLocations){
								QLog.getLogger().dLog(dTAG, pearTag, "location to be removed for suddenly big speed is:"+loc.getSpeed());
							}
							
							app.toDecideLocations.clear();
						}
					 
					}
					
				}
				
			}else if(app.toDecideLocations!=null){
				
				
				QLog.getLogger().dLog(dTAG, pearTag, " app.lastLocation.getSpeed() is:"+app.lastLocation.getSpeed());
				QLog.getLogger().dLog(dTAG, pearTag, " app.getRecordingTrack().getTrackBean().getAvs()/3.6 is:"+app.getRecordingTrack().getTrackBean().getAvs()/3.6);
				for(Location loc:app.toDecideLocations){
					QLog.getLogger().dLog(dTAG, pearTag, "location to be removed for suddenly big speed is:"+loc.getSpeed());
				}
				app.toDecideLocations.clear();//remove the large locations with high speed
			}
		} */
		
		
		
		
		
		
		
		 // // // //// QLog.getLogger().dLog(TAG," location.getTime():" +location.getTime());
		 // // // //// QLog.getLogger().dLog(TAG," app.getRecordingTrack().getTrackBean().getStartTime():" +app.getRecordingTrack().getTrackBean().getStartTime());
	/*	
		if (!isPlayback
				&& !isForceUpdate
				&& app.getRecordingTrack().getTrackBean().getLastWp()!=null
				&& location.getTime() < app.getRecordingTrack().getTrackBean().getLastWp().getWb().getTime()){
		
			QLog.getLogger().dLog(TAG," !isForceUpdate && location == null, returned. ");
		
			return;// this should not happen,but in case to get past playback
					// location sending which is stopped.
		}*/
//		  QLog.getLogger().dLog(TAG," Location is here 2 ");

		long pausingTime = 0;
		long offTime = 0;
//		if (app.canRecord()) {
		if (app.canRecord()) {
			if ( !isGpsLocation) { // force update, not from location  change 
										
				if (isForceUpdate && app.lastOfftime == 0)
//				if (isForceUpdate)
					app.lastOfftime = System.currentTimeMillis();
			}

			if (app.lastOfftime > 0) {
			/*	offTime = location.getTime() == 0 ? System.currentTimeMillis()
						- app.lastOfftime : location.getTime()
						- app.lastOfftime;*/
				
				offTime =  System.currentTimeMillis() - app.lastOfftime  ;   //系统时间只能能用于计算 相对时间，绝对时间以gps、network 为准
				offTime =offTime>app.getGPS_REQUEST_SPAN()?offTime:0;
				app.offtime = offTime;
				app.sumOfftimeWp += offTime;
				if (offTime>0 && isForceUpdate) {
//				if (location.getTime() == 0) { // only force update during the
												// lost gps signal period, to
												// count the off time.
				// offTime =location.getTime()==0?System.currentTimeMillis() -
				// app.lastOfftime :location.getTime() - app.lastOfftime;
					app.lastOfftime = System.currentTimeMillis();
					// app.sumOfftime +=offTime;
					// app.sumOfftimeWp +=offTime;
				} else
					app.lastOfftime = 0;

//				QLog.getLogger().d(dTAG, TAG + " app.lastOfftime " + app.lastOfftime);
//				QLog.getLogger().d(dTAG, TAG + " app.offtime " + app.offtime);
//				QLog.getLogger().d(dTAG, TAG + " app.sumOfftimeWp " + app.sumOfftimeWp);
//				QLog.getLogger().d(dTAG, TAG + " track total Offtime: "	+ app.getRecordingTrack().getTrackBean().getOffTime());
			}

			if ( isGpsLocation  ) {

				if(location.hasSpeed() && location.getSpeed()==0 && app.lastPaused == 0){ 
					app.lastPaused = location.getTime();
					// // // //// QLog.getLogger().dLog(TAG," system.current Time: "+Utils.getFormatedTime(System.currentTimeMillis()) +"  "+System.currentTimeMillis());
//					QLog.getLogger().dLog(TAG," location.getSpeed()==0 && app.lastPaused == 0");
//					QLog.getLogger().dLog(TAG," location.getTime(): "+Utils.getFormatedTime(location.getTime()) +"  "+location.getTime());

					// // // //// QLog.getLogger().dLog(TAG," ");					
					  
//					QLog.getLogger().dLog(TAG," ----------------------------------------------------------------------->isFirstwp "+isFirstwp );
//					QLog.getLogger().dLog(TAG," speed ==0 &&  app.lastPaused == 0" +(location.getSpeed()==0 && app.lastPaused == 0));					  
				}else if(location.hasSpeed() && location.getSpeed()>0 && app.lastPaused >0){
//					pausingTime = location.getTime() - app.lastPaused;
					pausingTime = location.getTime() - app.lastPaused-QiYouConstant.MAX_GPS_SPAN;
					pausingTime=pausingTime>0?pausingTime:0;
					app.lastPaused =0;
					app.sumPaused += pausingTime;
//					if(app.sumPaused<=0)app.sumPaused=0;
					
//					   // QLog.getLogger().dLog(TAG," location.getSpeed()>0 && app.lastPaused >0" +(location.getSpeed()>0 && app.lastPaused >0));
//					// // // //// QLog.getLogger().dLog(TAG," app.sumPaused  Time: "+Utils.getFormatedTime(System.currentTimeMillis()) +"  "+System.currentTimeMillis());
//					   // QLog.getLogger().dLog(TAG," location.getTime(): "+Utils.getFormatedTime(location.getTime()) +"  "+location.getTime());

					// // // //// QLog.getLogger().dLog(TAG," ");
					
					
				}
				
				
//				 // // // //// QLog.getLogger().dLog(TAG," system.current "+Utils.getFormatedTime(System.currentTimeMillis()) +"  "+System.currentTimeMillis());
//				 // // // //// QLog.getLogger().dLog(TAG," trackId "+ app.getRecordingTrack().getTrackBean().getTrackId() );
//				 // // // //// QLog.getLogger().dLog(TAG," app.sumPause "+app.sumPaused );
//				 // // // //// QLog.getLogger().dLog(TAG," track total pause time: "+	 app.getRecordingTrack().getTrackBean().getPauseTime() );
/*
				if (app.lastPaused == 0) {
					app.lastPaused = location.getTime();
				} 
				if (app.lastPaused > 0) {
					pausingTime = location.getTime() - app.lastPaused;
					if (location.getSpeed() == 0)
						app.lastPaused = location.getTime();
					else
						app.lastPaused = 0;
					// if(isForceUpdate)
					app.sumPaused += pausingTime;
					if(app.sumPaused<=0)app.sumPaused=0;
					// QLog.getLogger().d(TAG," app.sumPause "+app.sumPaused );
					// QLog.getLogger().d(TAG," track total pause time: "+
					// app.getRecordingTrack().getTrackBean().getPauseTime() );
				}*/
			}
		}
	 
		
		if (isForceUpdate) {
			// if(app.getLocationCached().size()==0)return;
			preUpdatedb(false);
			return;
		}
//		  QLog.getLogger().dLog(TAG," Location is here 3 ");
		sendToDb(location);
	}

	
	private void sendToDb(Location location) {
		
		
		
		
//		  QLog.getLogger().d(dTAG,TAG+  "  gg Location processed, and send to track service for db.");

//		long MAX_TIME_UPDATE_DB = Utils.get_updatedb_invterval(trackType);
		int MAX_WPS_UPDATE_DB = Utils.get_updatedb_cachsize(trackType);

		
		
		if( isFirstwp && app.sumDist>0   ){
			QLog.getLogger().dLog(TAG," isFirstwp && app.sumDist>0  ");
			QLog.getLogger().dLog(TAG,"  app.sumDist ?  " +app.sumDist );
// 			app.initialTrackParameters();
			 
		}

//		 QLog.getLogger().dLog(TAG," Location is here 5 ");
		boolean isGoodWp = location.getSpeed() > 0 || isFirstwp;

		if (isGoodWp) // ||QiYouConstant.DEVELOPER_MODE)
		{
//			QLog.getLogger().dLog(TAG," ---------------------------input new location to app.getLocationCached()..........-------------- ");
//			app.getLocationCached().put(app.getLocationCached().size() + 1,	location); //TODO: review +1
		
			
			
			Location lastLoc=app.getLocationCached().size()>0?app.getLocationCached().get(app.getLocationCached().size()-1):app.lastLocation;
			
			double dist =   (isFirstwp?0:Utils.getDistance2(location,lastLoc));
			if(!isFirstwp && lastLoc!=null){
				float maxSpeed=location.getSpeed()>lastLoc.getSpeed()?location.getSpeed():lastLoc.getSpeed();
				float cdist=maxSpeed*(location.getTime()-lastLoc.getTime());
				/*if(dist>cdist){
					QLog.getLogger().dLog(TAG,"-------------------------- dist>cdist, dist is "+dist +",cdist is"+ cdist);
					QLog.getLogger().dLog(TAG," location.getTime()： "+location.getTime() +",lastLoc.getTime()："+ lastLoc.getTime());
					QLog.getLogger().dLog(TAG,"maxSpeed ： "+maxSpeed );
				}*/
				dist=dist>cdist?cdist:dist; 
			}
			app.SpDist+=dist;
			app.sumNavDist+=dist;
			boolean isKmflag = app.SpDist > QiYouConstant.TRACK_SPLIT_DIST * 0.999;// || 
			
			// app.SpDist>QiYouConstant.TRACK_SPLIT_DIST;
			if (isKmflag) {
				// QLog.getLogger().d(dTAG,
				// TAG+"---- split dist meets target,sumdist is: ----"+
				// app.SpDist +","+ (app.sumDist + app.locDist));
				app.SpDist = 0;
//				app.setCntKm(app.getCntKm() + 1);
//				app.setCntKm((int)((app.getRecordingTrack().getTrackBean().getDistance()+500)/1000)); 
				if(QiYouConstant.BL_SPEAK_KM){
					speakNewKm();
				}
				app.timeKm=System.currentTimeMillis();		 
			}
			
		    Bundle bd = new Bundle(); 						
		 	bd.putDouble("dist", dist); 
			bd.putBoolean("iskm", isKmflag);
		 	location.setExtras(bd);
		 	if(app.canSendLocation2UI)
		 		app.getRecordingTrack().getTrackBean().setDistance((float) (app.getRecordingTrack().getTrackBean().getDistance()+dist) );
			
			
			
			
			app.getLocationCached().put(app.getLocationCached().size(),	location);
//			QLog.getLogger().dLog(TAG," app.getLocationCached().size()  - " +app.getLocationCached().size());
			app.getRecordingTrack().getTrackBean().setTopSpeed(location.getSpeed()*3.6f);// recording the top speed. 

			if(app.GPS_SPAN_FACTOR>1){
				app.GPS_SPAN_FACTOR=1;
				app.startAndroidGPSRequest();
			}
			
		} else if (app.getLocationCached().size() == 0) {
			return;
		}
//		 QLog.getLogger().dLog(TAG," Location is here 6 ");
		// if(
		// QiYouConstant.DEVELOPER_MODE)Log.e(dTAG,TAG+" "+"app.getLocationCached().size(): "
		// +app.getLocationCached().size());
		// to judge if its the time for update db.
		long last_update_db_request_time = app.getRecordingTrack()
				.getTrackBean().getLastdbTime(); // if(
													// QiYouConstant.DEVELOPER_MODE)Log.e(dTAG,TAG+" "+"last_update_db_request_time: "
													// +l)ast_update_db_request_time);
		boolean isUpdatedbTime = System.currentTimeMillis()
				- last_update_db_request_time > MAX_TIME_UPDATE_DB;

		boolean canUpdateDb = app.getLocationCached().size() >= MAX_WPS_UPDATE_DB; // wp
																					// number
		canUpdateDb = canUpdateDb || isFirstwp || isUpdatedbTime; // first wp,
																	// db time
																	// reach.
		
		
//		QLog.getLogger().dLog(TAG," canUpdateDb - " +canUpdateDb);
		// canUpdateDb = canUpdateDb && app.getLocationCached().size()>0; //wps
		// not null.

		if (canUpdateDb)// ||QiYouConstant.DEVELOPER_MODE) //prepare for db
						// updating
		{
			preUpdatedb(isFirstwp);
		}

		// send out new location and pausing status... to calculate this pausing
		// time

	}

	// final String KEY_Altitude ="ELE";
	// final String KEY_Adist ="ADIST";
	// final String KEY_Bearing ="Bear";
	// final String KEY_Dist ="Dist";
	float dist = 0f;
	float bear = 0f;
	boolean isBear;
	boolean isSumbear;
	boolean isKmflag;
	float sumBear = 0;
	float eleDist =  QiYouConstant.MAX_ELE ;
	float avBear = 0;
	float avBear2 = 0; // direction.
	float cTargetBear = 0;
    boolean isPlayback ;
     
	void preUpdatedb(boolean isFirstwp) {
		ArrayList<String> newLocLst = new ArrayList<String>();
		Location lastSavedLoc = null;
		Location lastLoc = null;
		Location currentLoc;
		boolean isWpForDb = true; // wp is too close to last one, bearing is not
									// changed much, then skip
		boolean isTime = false;
		boolean isDist = false;

		double sdist = 0;

		// float minDist=0;
		int interval = isPlayback ? QiYouConstant.PLAYBACK_TIME_INTERVAL
				: QiYouConstant.MAX_GPS_SPAN;
		// int MIN_WPS_DISTANCE = QiYouConstant.MIN_WPS_DISTANCE_FACTOR ;
		int MAX_WPS_EVERAGE_ELE_CNT = Utils
				.get_updatedb_wpsElesumcnt(trackType);
		// QLog.getLogger().d(dTAG,TAG+" "+" start prepare for  db request, app.getLocationCached().size() "
		// +app.getLocationCached().size());
//		float minDist = app.getRecordingTrack().getTrackBean().getAvs()
//				* interval * QiYouConstant.MIN_WPS_DISTANCE_FACTOR;

		float minDist = app.getRecordingTrack().getTrackBean().getAvs()/3.6f
				* interval/1000 * QiYouConstant.MIN_WPS_DISTANCE_FACTOR;
		
		if (app.minTime == 0) {
			app.minTime = QiYouConstant.WPS_SAVE_PERCENT_FACTOR * interval;

		}
//		  QLog.getLogger().dLog(TAG," Location is here 7 ");
		// QLog.getLogger().d(dTAG,
		// TAG+" ---- -------app.getLocationCached().size()--- -------- "+app.getLocationCached().size());

		
		/*QLog.getLogger().dLog(TAG," begin to check locations in app.getLocationCached() ----------------->");
		QLog.getLogger().dLog(TAG,"     is first WP?  " +isFirstwp);
	    QLog.getLogger().dLog(TAG,"     track start time:"+  Utils.getFormatedTime(app.getRecordingTrack().getTrackBean().getStartTime())+"," + app.getRecordingTrack().getTrackBean().getStartTime());
		QLog.getLogger().dLog(TAG,"  size of app.getLocationCached() :" +app.getLocationCached().size());
		for (int i = 0; i <= app.getLocationCached().size(); i++) {
			QLog.getLogger().dLog(TAG,"                      location          " +i+1 );
			
			Location  loc = app.getLocationCached().get(i); 
			if(loc==null){
				QLog.getLogger().dLog(TAG,"     loc is null  " );
			}else{
				QLog.getLogger().dLog(TAG,"     loc's time: " + Utils.getFormatedTime(loc.getTime()) +","+loc.getTime());
			}
			
		}
		QLog.getLogger().dLog(TAG," <---------------- end of check locations in app.getLocationCached()");*/
		
		int j = 0;
		if (app.getLocationCached().size() > 0) {
			currentLoc = app.getLocationCached().get(0);//currentLoc = app.getLocationCached().get(1);

			// if( lastLoc ==null ) lastLoc = currentLoc;

			if (lastSavedLoc == null) {
				if (app.lastSavedLocation == null) {
					app.lastSavedLocation = currentLoc;
				}
				lastSavedLoc = app.lastSavedLocation;

			}
			if (app.lastLocation == null)
				app.lastLocation = currentLoc;
			// if(app.lastBearLoc==null)app.lastBearLoc=currentLoc;
		}

		// check and mark the bearloc
																													//		for (int i = 1; i <= app.getLocationCached().size(); i++) {
		for (int i = 0; i <= app.getLocationCached().size()-1; i++) {
			currentLoc = app.getLocationCached().get(i);
			if (lastLoc == null)
				lastLoc = currentLoc;
			
			if (app.cntBeared == 0 && !isBear) {
				// app.sumBear+=currentLoc.getBearing();//>180?currentLoc.getBearing()-360:currentLoc.getBearing();
				app.sumBear += currentLoc.getBearing() > 180 ? currentLoc
						.getBearing() - 360 : currentLoc.getBearing();
			    app.sumBear2 += currentLoc.getBearing();
				app.cntBear++;
				// app.sumBear2+=currentLoc.getBearing();
				// bearing since last location
				avBear = app.sumBear / app.cntBear;
				
				cTargetBear =app.sumBear2 / app.cntBear;
				
				if (app.cntBear <= QiYouConstant.WPS_ROAD_BEAR_CNT && !QiYouConstant.BL_ONE_SHOT_BEAR)
				continue;
//				QLog.getLogger().d(dTAG, TAG+" avBear ,app.sumBear,app.cntBear is " +avBear +","+app.sumBear +","+app.cntBear);
//			} 
//
//			if (app.cntBeared == 0) { // first time for bearing calculation.

				float abear = (currentLoc.getBearing() > 180 ? currentLoc
						.getBearing() - 360 : currentLoc.getBearing())
						- (avBear > 180 ? avBear - 360 : avBear);

				if (Math.abs(abear) > QiYouConstant.WPS_ROAD_BEARING
						&& app.cntBear > QiYouConstant.WPS_ROAD_BEAR_CNT) {
					bear = abear;
					app.targetBear = avBear; 
	 
					
				} else if (QiYouConstant.BL_ONE_SHOT_BEAR) {
					float tbear = (currentLoc.getBearing() > 180 ? currentLoc
							.getBearing() - 360 : currentLoc.getBearing())
							- (lastLoc.getBearing() > 180 ? lastLoc
									.getBearing() - 360 : lastLoc.getBearing());
					if (Math.abs(tbear) > QiYouConstant.WPS_ROAD_BEARING) {
						bear = tbear;
						app.targetBear = currentLoc.getBearing() > 180 ? currentLoc
								.getBearing() - 360 : currentLoc.getBearing();
					}
				} else
//					continue;
					bear = 0;
 

			} else if(app.targetBear !=-360){
				bear = (currentLoc.getBearing() > 180 ? currentLoc.getBearing() - 360
						: currentLoc.getBearing())
						- (app.targetBear > 180 ? app.targetBear - 360
								: app.targetBear);
			}
//	  QLog.getLogger().d(dTAG, TAG+" bear,app.targetBear ,app.cntBeared" +bear +" , "+app.targetBear +"," +app.cntBeared);
			// bear =Math.abs(tbear)>Math.abs(abear)?tbear:abear;

			// bear =currentLoc.getBearing() - app.targetBear ;
			// sumBear+=Math.abs(bear);
			sumBear += currentLoc.getBearing() - avBear;
			// QLog.getLogger().d(dTAG, TAG+" bear,sumBear : "+bear +" , " +sumBear);

			// isBear = (app.cntBear > QiYouConstant.WPS_SAVE_PERCENT_FACTORE )
			// && h.abs(bear)>QiYouConstant.WPS_ROAD_BEARING ;
			// isBear = app.cntBear> QiYouConstant.WPS_ROAD_BEAR_CNT &&
			// Math.abs(bear)>QiYouConstant.WPS_ROAD_BEARING ;
			isBear = app.targetBear !=-360 
					&& Math.abs(bear) > QiYouConstant.WPS_ROAD_BEARING
					&& Math.abs(currentLoc.getBearing() - cTargetBear) > QiYouConstant.WPS_ROAD_BEARING 
					&& Math.abs(currentLoc.getBearing() - app.targetBear) > QiYouConstant.WPS_ROAD_BEARING;
								
					
			isSumbear = app.cntBear > QiYouConstant.WPS_ROAD_BEAR_CNT
					&& Math.abs(sumBear) > QiYouConstant.WPS_ROAD_BEARING
					&& (currentLoc.getTime() - app.lastSumbear > app.minTime);

			// isBear = isBear && (currentLoc.getTime() -
			// app.lastBearLoc.getTime() >
			// QiYouConstant.WPS_SAVE_PERCENT_FACTORE*1000);
			// isBear = isBear && (app.cntBear >
			// QiYouConstant.WPS_SAVE_PERCENT_FACTORE(Math.abs(bear)>QiYouConstant.WPS_ROAD_BEARING
			// || Math.abs(sumBear)>2*QiYouConstant.WPS_ROAD_BEARING);
			// isBear = app.cntBear > QiYouConstant.WPS_SAVE_PERCENT_FACTORE &&
			// Mat );
			if (isSumbear) {
				app.lastSumbear = currentLoc.getTime();
				app.sumBearLocs.put(currentLoc.getTime(), currentLoc);

			}

			// if(isBear && app.cntBeared<= QiYouConstant.WPS_ROAD_BEAR_CNT){
			if (isBear) {
				// QLog.getLogger().d(dTAG,
				// TAG+" bear, currentLoc.getBearing(), avBear , app.cntBear : "+
				// bear +" , " + currentLoc.getBearing() +" , " + targetBear+
				// " , "+ app.cntBear);

				if (app.cntBeared == 0) {
					app.lastBearLoc = currentLoc;
					// app.targetBear =(lastLoc.getBearing()>180?
					// lastLoc.getBearing()-360: lastLoc.getBearing()) > (
					// avBear>180? avBear-360: avBear)
					// ?avBear:lastLoc.getBearing();
					// app.targetBear =lastLoc.getBearing();
					// app.targetBear =avBear;
					// app.targetBear
					// =Math.abs(tbear)>Math.abs(abear)?lastLoc.getBearing():avBear;
				}
				app.cntBeared++;
				// app.sumBear2+=currentLoc.getBearing();
				// if(app.cntBeared>1)
				// app.sumBear2+=currentLoc.getBearing();//
				// >180?currentLoc.getBearing()-360:currentLoc.getBearing();
				isBear = isBear
						&& app.cntBeared > QiYouConstant.WPS_ROAD_BEAR_CNT;
				if (!isBear)
					continue;

				// QLog.getLogger().d(dTAG,
				// TAG+" app.lastBearLoc.getTime() : "+app.lastBearLoc.getTime()
				// );
				// QLog.getLogger().d(dTAG, TAG+"currentLoc.getBearing(),  app.targetBear"
				// +" , " +currentLoc.getBearing()+" , " + app.targetBear);

				// app.bearLocs.put( app.lastBearLoc.getTime(), new
				// Float[]{app.targetBear,app.sumBear2/(app.cntBeared-1)} );

//				app.bearLocs.put(app.lastBearLoc.getTime(), new Float[] {
//						app.targetBear, currentLoc.getBearing() });

				app.bearLocs.put( currentLoc.getTime(), new Float[] {
					app.targetBear, currentLoc.getBearing() });
				
				
				if (getRoadTurnFlag2(currentLoc.getBearing(), app.targetBear) != getRoadTurnFlag2(
						app.lastBearLoc.getBearing(), app.targetBear)) {// current
																	// loc'bear
																	// has a new
																	// turn
//					QLog.getLogger().d(dTAG, TAG+"getRoadTurnFlag2(currentLoc.getBearing(), targetBear), getRoadTurnFlag2(app.lastBearLoc.getBearing(), targetBear)" +getRoadTurnFlag2(currentLoc.getBearing(), app.targetBear) + ","+ getRoadTurnFlag2(app.lastBearLoc.getBearing(), app.targetBear) );
//					QLog.getLogger().d(dTAG, TAG+ "getRoadTurnFlag2" +currentLoc.getTime());
					app.bearLocs.put(currentLoc.getTime(), new Float[] {app.targetBear,app.lastBearLoc.getBearing() });
				}

				// app.bearLocs.put(
				// app.lastBearLoc.getTime(),app.sumBear2/app.cntBear );

				app.lastBearLoc = null;
				app.sumBear = 0;
				// app.sumBear =app.sumBear2;
			
				app.cntBear = 0;
				isBear = false;
				bear = 0;
//				 i=i>app.cntBeared?i-app.cntBeared:1;
				app.cntBeared = 0;
				app.targetBear =-360;	
				app.sumBear2=0;
				cTargetBear=0;
			 
			} else if (app.cntBeared > 0) {
				// }else {
				// QLog.getLogger().d(dTAG,
				// TAG+" app.getLocationCached().size(), i, app.cntBeared: "+app.getLocationCached().size()+" , "+
				// i +" , " + app.cntBeared );
				i = i > app.cntBeared ? i - app.cntBeared : 0;         												//				i = i > app.cntBeared ? i - app.cntBeared : 1;
				app.cntBeared = 0;
				app.lastBearLoc = null;
				app.sumBear =0;
				// app.sumBear =app.sumBear2;				
				app.cntBear = 0;
				bear = 0;	
				app.targetBear =-360;
				app.sumBear2 = 0;
				cTargetBear =0;
			
			}
			lastLoc = currentLoc;
		}
//		 QLog.getLogger().dLog(TAG," Location is here 8 ");
		HashMap<Integer, Location> tmpMap = new HashMap<Integer, Location>();
//		QLog.getLogger().dLog(dTAG, " begin to check cached locations.................................................");
		boolean isMaxProcessed =false;
		for (int i = 0; i <= app.getLocationCached().size()-1; i++) {
			
//			QLog.getLogger().dLog(dTAG, "current location: " + (i+1) +" of "   +(app.getLocationCached().size()));
			
			float lastAele = 0; // last average ele
			float elesum = 0;
			// float avSp =app.getRecordingTrack().getTrackBean().getAvs();
			// Log.e(dTAG,TAG+" "+ "current location: " + i +" of "
			// +app.getLocationCached().size());
			currentLoc = app.getLocationCached().get(i);

			if (app.lastBearLoc != null
					&& !app.bearLocs.containsKey(app.lastBearLoc.getTime())) {
				if (currentLoc.getTime() >= app.lastBearLoc.getTime()) {
//					QLog.getLogger().d(dTAG,	TAG	+ " Unfinished bearing judge, break the cache loop. i,size "	+  (i+1) + "," + (app.getLocationCached().size()));

//					tmpMap.put(tmpMap.size() + 1, currentLoc);
					tmpMap.put(tmpMap.size() , currentLoc);
					continue;
				}
			}

			if (app.sumOfftimeWp > 0 || isFirstwp

			// || app.lastPaused==0 &&(currentLoc.getTime()-lastLoc.getTime()
			// >QiYouConstant.MAX_GPS_SPAN*QiYouConstant.GPS_CODE_START_WPS_CNT_SKIP)//
			// offtime //TODO: RVIEW.

			) { // GPS just warmup, skip first 5 wps ele data.
				app.gpsStartTime = currentLoc.getTime();//TODO: remove.
				app.skipCnt = QiYouConstant.GPS_CODE_START_WPS_CNT_SKIP;
				// QLog.getLogger().d(dTAG, TAG+" GPS code start detected,next " +
				// app.skipCnt +" wp will be skipped for ele calculation.");
			}

			if (app.skipCnt == 0) {
				app.getEles().add((float) currentLoc.getAltitude());
			} else {
				// QLog.getLogger().d(dTAG, TAG+" wps left to skip ele cal is : "+
				// app.skipCnt);
				app.skipCnt--;

			}

			// 记录关键点,丢弃一些距离密集点

			// minDist =
			// avSp*((currentLoc.getTime()-lastLoc.getTime()))*QiYouConstant.MIN_WPS_DISTANCE_FACTOR;
			// distance since last saved location.

			isBear = app.bearLocs.containsKey(currentLoc.getTime());
			if (isBear) {
				Float[] bears = app.bearLocs.get(currentLoc.getTime());
				if (bears != null) {
					cTargetBear = bears[0];
					avBear2 = bears[1];
				}

//				QLog.getLogger().d(dTAG, TAG + " currentLoc.getTime(), targetBear is: "		+ currentLoc.getTime() + " , " + cTargetBear);

			} else
				isSumbear = app.sumBearLocs.containsKey(currentLoc.getTime());
			//
		/*	if (!(isBear || isSumbear)) {
				sdist = Utils.getDistance(currentLoc, lastSavedLoc);
				isDist = sdist > minDist;
				// QLog.getLogger().d(dTAG, TAG+" minDist,sdist : "+minDist +" , " +sdist);
				// time since last saved location
				isTime = app.minTime < currentLoc.getTime()
						- lastSavedLoc.getTime();
			}*/
//			  QLog.getLogger().dLog(TAG," Location is here 9 ");
			// QLog.getLogger().d(dTAG, TAG+" Sumbear,bear"+sumBear +"," + bear+","+isBear);

			// QLog.getLogger().d(dTAG, TAG+" isDist,isTime : "+isDist +" , " +isTime);
		
 

			
	       if(app.lastSavedLocation==null ||app.lastSavedLocation.getTime()==0){
				app.lastSavedLocation=currentLoc;
//				QLog.getLogger().dLog( TAG,  " app.lastSavedLocation is null. ");
			} 
//	       long diff = currentLoc.getTime() - app.lastSavedLocation.getTime() ;
	       long diff = currentLoc.getTime() - app.lastLocation.getTime();
		  
			if( isMaxProcessed || diff <= MAX_TIME_UPDATE_DB){
			
//				QLog.getLogger().dLog(dTAG," currentLoc time "+Utils.getFormatedTime(currentLoc.getTime()));
//				QLog.getLogger().dLog(dTAG," app.lastSavedLocation time "+Utils.getFormatedTime(app.lastSavedLocation.getTime()));
				
				/*sdist =   (isFirstwp?0:Utils.getDistance2(currentLoc, app.lastLocation)); 
				
				if(sdist -currentLoc.getExtras().getDouble("dist")!=0)
					QLog.getLogger().dLog(dTAG," old dist - new dist:  "+( sdist -currentLoc.getExtras().getDouble("dist")));
				 */
				
				sdist=currentLoc.getExtras().getDouble("dist");
				
				
				
//				app.sumDiff+=sdist -Utils.getDistance(currentLoc, app.lastLocation) ;

				
//				QLog.getLogger().dLog(dTAG," currentLoc time "+Utils.getFormatedTime(currentLoc.getTime()));
//				QLog.getLogger().dLog(dTAG," app.lastLocation time "+Utils.getFormatedTime(app.lastSavedLocation.getTime()));
				
//				sdist = (float) (isFirstwp?0:Utils.getDistance(currentLoc, app.lastLocation));
//				sdist = (float) (isFirstwp?0:Utils.getDistance2(currentLoc, app.lastSavedLocation));
//				app.sumDiff+=sdist -Utils.getDistance(currentLoc, app.lastSavedLocation) ;
//				QLog.getLogger().dLog(dTAG," app.sumDiff "+app.sumDiff );
			}else{
				sdist=0;  //系统暂停或失联gps后恢复，总距离不计入
				isMaxProcessed=true;
//				QLog.getLogger().dLog(TAG,"Caution! -------------------------------------- 系统暂停或失联gps后恢复，总距离不计入 , MAX_TIME_UPDATE_DB is" +MAX_TIME_UPDATE_DB +" ,diff is" +diff  );
				
			}
			
//			sdist = Utils.getDistance(currentLoc, lastSavedLoc);
			isDist = sdist > minDist;
			// QLog.getLogger().d(dTAG, TAG+" minDist,sdist : "+minDist +" , " +sdist);
			// time since last saved location
			isTime = app.minTime < currentLoc.getTime()
					- lastSavedLoc.getTime();
			
			
			 
			if (Math.round(app.sumDist) == 0 || Double.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN
					  ) {
				app.sumDist = app.getRecordingTrack().getTrackBean()
						.getDistance();
			}
			if (Math.round(app.sumDist) == 0 || Double.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN
					 ) {
//				Log.e(dTAG, " Distance is NaN? app.sumDist: " + app.sumDist);
//				QLog.getLogger().dLog(TAG," Distance is NaN? app.sumDist: " + app.sumDist);
				app.sumDist = 0;
			}
			 
				
			app.sumDist += sdist; 
			app.getRecordingTrack().getTrackBean().setDistance((float) app.sumDist); //累加总里程, Meter
		/*	if(currentLoc.getExtras().containsKey("sumdist")){
				double testSumdist =currentLoc.getExtras().getDouble("sumdist");
				QLog.getLogger().dLog(dTAG," ------------------- currentLoc speed " +currentLoc.getSpeed());
				QLog.getLogger().dLog(TAG,"  ------------------- app.sumDist   " +( app.sumDist  ));
				QLog.getLogger().dLog(TAG,"  ------------------- testSumdist: " +( testSumdist)); 
				QLog.getLogger().dLog(TAG,"  ------------------- delta sumdiff of app.sumDist - testSumdist: " +( app.sumDist - testSumdist));
			}*/
			
			
			// 几个点的平均海拔

			// QLog.getLogger().d(dTAG, TAG+" split dist is: "+ app.SpDist);
//			sdist = isFirstwp?0:Utils.getDistance(currentLoc, app.lastLocation);
			app.bearDist += sdist;
			// dist+=sdist;
			app.locDist += sdist;
//			app.SpDist += sdist;// (float)
								// Utils.getDistanceFromXtoY(currentLoc.getLatitude(),currentLoc.getLongitude(),app.lastLocation.getLatitude(),app.lastLocation.getLongitude());
			
			isKmflag=currentLoc.getExtras().getBoolean("iskm");
			/*isKmflag = app.SpDist > QiYouConstant.TRACK_SPLIT_DIST * 0.999;// || 
			
			// app.SpDist>QiYouConstant.TRACK_SPLIT_DIST;
			if (isKmflag) {
				// QLog.getLogger().d(dTAG,
				// TAG+"---- split dist meets target,sumdist is: ----"+
				// app.SpDist +","+ (app.sumDist + app.locDist));
				app.SpDist = 0;
//				app.setCntKm(app.getCntKm() + 1);
//				app.setCntKm((int)((app.getRecordingTrack().getTrackBean().getDistance()+500)/1000)); 
				if(QiYouConstant.BL_SPEAK_KM){
					speakNewKm();
				}
				app.timeKm=System.currentTimeMillis();				
				 
				 
				
			}*/
			isWpForDb = //isForceUpdate || 
					 isDist
					&& isTime
					|| isKmflag
					|| isBear
					|| isSumbear
					|| isFirstwp
					|| currentLoc.getTime() - lastSavedLoc.getTime() > QiYouConstant.MAX_GEO_TIME / 2
					|| currentLoc.getSpeed()*3.6f >= app.getRecordingTrack()
							.getTrackBean().getTopSpeed()
					|| QiYouConstant.WPS_SAVE_ALL		
				   ;
					
			 

	/*		if (Math.round(app.sumDist) == 0 || Float.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN
					  ) {
				app.sumDist = app.getRecordingTrack().getTrackBean()
						.getDistance();
			}
			if (Math.round(app.sumDist) == 0 || Float.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN
					 ) {
				Log.e(dTAG, " Distance is NaN? app.sumDist: " + app.sumDist);
				QLog.getLogger().dLog(TAG," Distance is NaN? app.sumDist: " + app.sumDist);
				app.sumDist = 0;
			}
			app.sumDist += sdist; 
			QLog.getLogger().dLog(dTAG, " app.sumDist "+app.sumDist );*/
			
			
//			  QLog.getLogger().dLog(TAG," Location is here 10 ");
			isWpForDb= isWpForDb &&!app.isRestoreLastTracking ;
			
			if(!isFirstwp && sdist==0)
				isWpForDb =isWpForDb && app.getLocationCached().size()>1;   //过滤偶尔出现的飘逸的卫星信号
				
				isWpForDb=isWpForDb ||isCleanning && (i == app.getLocationCached().size()-1);
			
			if (isWpForDb) {
				
//				QLog.getLogger().dLog(dTAG," -------------------------it isWpForDb to save the wp for db ");
				// dist = (float)
				// Utils.getDistanceFromXtoY(currentLoc.getLatitude(),currentLoc.getLongitude(),lastLoc.getLatitude(),lastLoc.getLongitude());
			

				/*if (Math.round(app.sumDist) == 0 || Float.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN
						  ) {
					app.sumDist = app.getRecordingTrack().getTrackBean()
							.getDistance();
				}
				if (Math.round(app.sumDist) == 0 || Float.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN
						 ) {
					Log.e(dTAG, " Distance is NaN? app.sumDist: " + app.sumDist);
					QLog.getLogger().dLog(TAG," Distance is NaN? app.sumDist: " + app.sumDist);
					app.sumDist = 0;
				}
				
				if(diff <= MAX_TIME_UPDATE_DB){ 
					QLog.getLogger().dLog(dTAG," currentLoc time "+Utils.getFormatedTime(currentLoc.getTime()));
					QLog.getLogger().dLog(dTAG," app.lastSavedLocation time "+Utils.getFormatedTime(app.lastSavedLocation.getTime()));
					
					sdist = (float) (isFirstwp?0:Utils.getDistance2(currentLoc, app.lastSavedLocation));//TODO : use double.....than float
 					app.sumDiff+=sdist -Utils.getDistance(currentLoc, app.lastSavedLocation) ;
				} else{
					sdist=0;
					QLog.getLogger().dLog(dTAG,"Caution 2! -------------------------------------- 系统暂停或失联gps后恢复，总距离不计入 , MAX_TIME_UPDATE_DB is" +MAX_TIME_UPDATE_DB +" ,diff is" +diff  );
					
				}
					
				app.sumDist += sdist; 
				
				
				QLog.getLogger().dLog(dTAG, " app.sumDist "+app.sumDist );
				*/
				
				
				int s = app.getEles().size();
				if (s >= MAX_WPS_EVERAGE_ELE_CNT) {
					StringBuffer sb = new StringBuffer();
					for (float e : app.getEles()) {
						elesum += Math.round(e);
						sb.append(e + ",");

					}

					lastAele = (float) (elesum / (s + 0.0));
					// QLog.getLogger().d(dTAG, TAG+" eles are: " + sb.toString());
					// QLog.getLogger().d(dTAG, TAG+" elesum,lastAele,s : "+ elesum+ " , "+
					// lastAele+" , "+s);
					if (app.lastEle < QiYouConstant.MAX_ELE ) {
						eleDist = lastAele - app.lastEle;
						
						float factor=(float) (sdist*QiYouConstant.ELED_FACTOR);
						 
						eleDist=  (float) (eleDist>0?
								eleDist> factor?eleDist-factor :0
								 : eleDist<-1*factor? eleDist - -1*factor:0);		
					}
					
					/*eleDist =  (float) (eleDist>0?
									  eleDist> sdist*0.07f?eleDist-sdist*0.07f :0
									 : eleDist<-1*sdist*0.07f? eleDist - -1*sdist*0.07:0);	 */
					
					 			
					
					app.lastEle = lastAele;
					app.eles.clear();
					elesum = 0;
					 
					if(app.getRecordingTrack().getTrackBean().getTrackId()>0 
							&& app.startTime > app.getRecordingTrack().getTrackBean().getLastdbTime()){
						app.maxEle= app.maxEle<app.getRecordingTrack().getTrackBean().getMaxEle()?
								app.getRecordingTrack().getTrackBean().getMaxEle():app.maxEle;
						app.minEle= app.minEle<app.getRecordingTrack().getTrackBean().getMinEle()?
								app.minEle:app.getRecordingTrack().getTrackBean().getMinEle(); 
						
						app.upDist =app.upDist > app.getRecordingTrack().getTrackBean().getUpDist()?
									app.upDist :app.getRecordingTrack().getTrackBean().getUpDist();
						app.downDist = app.downDist>app.getRecordingTrack().getTrackBean().getDownDist()?
								app.downDist:app.getRecordingTrack().getTrackBean().getDownDist();
					}
					
					app.maxEle=app.maxEle<lastAele?lastAele:app.maxEle;
					app.minEle=app.minEle>lastAele?lastAele:app.minEle;;
					app.upDist+=eleDist>0?sdist:0;
					app.downDist+=eleDist<0?sdist:0;
					 
				}

			/*	if (Math.round(app.sumDist) == 0 || Float.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN
						  ) {
					app.sumDist = app.getRecordingTrack().getTrackBean()
							.getDistance();
				}
				if (Math.round(app.sumDist) == 0 || Float.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN
						 ) {
					Log.e(dTAG, " Distance is NaN? app.sumDist: " + app.sumDist);
					app.sumDist = 0;
				}
				app.sumDist += app.locDist;*/
				String wpJson=getLocationChanges(currentLoc);
				if(!TextUtils.isEmpty(wpJson));
					newLocLst.add(wpJson); // put the
																// current loc
																// in the cache
																// for update

				if (eleDist !=  QiYouConstant.MAX_ELE ) {
					eleDist =  QiYouConstant.MAX_ELE ;
				}
				//
				// if(isBear){
				// app.sumBear =0;
				// app.cntBear=0;
				// app.cntBeared=0;
				// }
				//
				if (isBear)
				// if( Math.abs(bear)>QiYouConstant.WPS_ROAD_BEARING)
				{
					app.bearLocs.remove(currentLoc.getTime());
					app.bearDist = 0;
					// app.minTime = QiYouConstant.WPS_SAVE_PERCENT_FACTORE
					// *interval;
					app.minTime = interval;
					minDist = 0;
				} else {
					if (app.minTime < QiYouConstant.MAX_GEO_TIME / 2)
						app.minTime += 2 * interval; // 直线行驶状态下,递减wp个数
					minDist = app.getRecordingTrack().getTrackBean().getAvs()
							* interval * QiYouConstant.MIN_WPS_DISTANCE_FACTOR;
				}

				if (isSumbear) {
					app.sumBearLocs.remove(currentLoc.getTime());
				}

				// QLog.getLogger().d(dTAG, TAG+" minTime, location timeDiff,isBear "+
				// app.minTime +", "+
				// (currentLoc.getTime()-lastSavedLoc.getTime()) +" , "+isBear);
				app.locDist = 0;
				dist = 0;
				// bear=0;
				// sumBear =isBear?0:sumBear;
				sumBear = 0;
				isDist = false;
				isSumbear = false;
				isTime = false;
				app.sumPaused = 0;
				// app.offtime =0;
				app.sumOfftimeWp = 0;
				// if(!isPlayback)
				app.lastSavedLocation = currentLoc;
				lastSavedLoc = currentLoc;
				j++;

				// Log.e(dTAG,TAG+" "+ "to be updated...");
			}
//			  QLog.getLogger().dLog(TAG," Location is here 11 ");
			app.lastLocation = currentLoc;
		}

//		if(!isPlayback ||isPlayback && QiYouConstant.PLAYBACK_CAN_RECORD)			
		if (app.playBack && QiYouConstant.PLAYBACK_CAN_RECORD || app.isLastTrackExist() &&(isForceUpdate || newLocLst.size() > 0)) { // to update db
			
			/*if (app.getLocationCached().size() > 0){
				QLog.getLogger().dLog(dTAG,   " ..." + j + " of "+ app.getLocationCached().size() + ", wps keeped: " + j* 100 / (app.getLocationCached().size()) + "%");
			}*/
			
			Intent locIntent = new Intent(QiYouConstant.ACTION_NEW_WAYPOINTS_TO_SAVE);
			if (newLocLst.size() > 0)
				locIntent.putExtra(QiYouConstant.NEW_LOCATION, newLocLst);
			else if (isForceUpdate) {// only force update the db when there is
										// no new waypoint in
				locIntent.putExtra(QiYouConstant.EXTRA_KEY_FORCE_UPDATE,isForceUpdate);
//				QLog.getLogger().d(dTAG, TAG + " Force update to db broadcast.");

			} 
				sendBroadcast(locIntent);
			 
				
			newLocLst.clear();
		    app.setlastLocation( app.lastLocation );// persist the last location.
		    /*if(isFirstwp){				 
				if(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL<2)
					app.speech("卫星定位成功，记录开始",0);
		    }*/
		    	
 		    
		    
		    sendShareLocation();
		    
		    
		}
		

		// to remove the items in the location cache.
		app.getLocationCached().clear();
//		QLog.getLogger().dLog(TAG," ---------------------------app.getLocationCached().clear()..........-------------- ");
		if (app.lastBearLoc != null
				&& !app.bearLocs.containsKey(app.lastBearLoc.getTime())) {// location
																			// cache
																			// dosn't
																			// match
																			// isBear
																			// condition.
//			QLog.getLogger().dLog(dTAG, TAG
//							+ " The location cache dosn't contain enough points for bear judge,keep some locaitons in the cach for new comming ones.");
			// for(Iterator<Location> iterator =
			// app.getLocationCached().values().iterator();iterator.hasNext();){
			// Location loc =iterator.next();
			// if(loc.getTime()< app.lastBearLoc.getTime()){
			// iterator.remove();
			//
			// }
			// }

			app.getLocationCached().putAll(tmpMap);
//			QLog.getLogger().dLog(dTAG,  "locations put in next loop:   " + tmpMap.size());

		}
//		  QLog.getLogger().dLog(TAG," Location is here 13 ");
	}

	private String getLocationChanges(Location currentLoc) {
		// int MAX_WPS_EVERAGE_ELE_CNT =
		// Utils.get_updatedb_wpsElesumcnt(trackType) ;
//		Bundle bd = currentLoc.getExtras();// lastloc.getExtras();
//		long pause = bd.getLong(KEY_PAUSETIME) + app.sumPaused;
//		long pause =  app.sumPaused>QiYouConstant.MAX_GPS_SPAN*1? app.sumPaused:0;
		long pause = 0; //app.sumPaused;
		// long offtime = bd.getLong(KEY_OFFTIME)+app.sumOfftimeWp;

		long sportTime = app.getRecordingTrack().getTrackBean().getSportTime(); // current
																			// sport
																			// time
																			// of
																			// track;

		/*if (app.getRecordingTrack().getTrackBean().getEndTime() > 0) {
			long nt = currentLoc.getTime()
					- app.getRecordingTrack().getTrackBean().getEndTime() - pause
					- app.sumOfftimeWp;
			nt = nt > 0 ? nt : 0;
			if(nt==0)return null;
			sportTime += nt;
		}*/
 	 

//		app.lastLocationTime =app.lastLocation!=null?app.lastLocation.getTime():app.lastLocationTime;
		
	
		
		long diff = currentLoc.getTime() - app.lastSavedLocation.getTime() ;
	    long nt =0;
		if(diff <= MAX_TIME_UPDATE_DB){ 
		  if(app.locDist>0 && app.sumPaused>0){ 
			  
				long calPausetime =(long) (diff - 1000*app.locDist/( (app.lastSavedLocation.getSpeed() + currentLoc.getSpeed())/2.0000) - app.sumOfftimeWp) ;
				 pause = calPausetime>0?calPausetime:0;
//				 QLog.getLogger().dLog( TAG,  " app.locDist>0 && app.sumPaused>0, calPausetime:"+calPausetime +", app.sumPaused" + app.sumPaused);
				/* QLog.getLogger().dLog( TAG,  " pause is " +pause);
				 QLog.getLogger().dLog( TAG,  String.format(" last saved speed is%s ，current speed is%s",app.lastSavedLocation.getSpeed(),currentLoc.getSpeed()));*/
				 
		  }
		  
		    nt = diff  - pause	-  app.sumOfftimeWp;
//		    nt = diff  - app.sumPaused	-  app.sumOfftimeWp;//TODO: valid the change for sport time calculation.
			nt = nt > 0 ? nt : 0; 
		
		}else{// 和上次位置时间间隔 比较大，应为离线或静止状态，计入静止时间
			
		/*	pause=diff 	-  app.sumOfftimeWp;
			nt =0;*/
		    pause=diff 	 -MAX_TIME_UPDATE_DB -  app.sumOfftimeWp;
			nt =MAX_TIME_UPDATE_DB; 	
			 /*QLog.getLogger().dLog( TAG,  " diff > MAX_TIME_UPDATE_DB, diff:"+diff +","+ Utils.getTimeCnt(diff) +",MAX_TIME_UPDATE_DB is "+ MAX_TIME_UPDATE_DB +", app.sumPaused " + app.sumPaused);
			 QLog.getLogger().dLog( TAG,  " pause is " +pause);*/
			
			
			if(app.sumOfftimeWp==0){
				//TODO: dist should be 0, sumdist ,app.cntKm,kmdist should not grow;
			 
			}
			 
		}
		nt=nt>diff?diff:nt;
		sportTime += nt;
		
		if(isPlayback)
			sportTime = sportTime*QiYouConstant.MAX_GPS_SPAN/QiYouConstant.PLAYBACK_TIME_INTERVAL;
		
//		 QLog.getLogger().dLog( TAG,  " sportTime is " +sportTime);
		
/*		if ( app.lastSavedLocation!=null && app.lastSavedLocation.getTime() > 0 ) {
			
			long diff = currentLoc.getTime() - app.lastSavedLocation.getTime() ;
			
			if(diff > MAX_TIME_UPDATE_DB){
				pause =diff -app.sumOfftimeWp;
				
			}else if(app.locDist>0 && pause>0){ 
				
					long avsptime =(long) (diff - 1000*app.locDist/( (app.lastSavedLocation.getSpeed() + currentLoc.getSpeed())/2.000) - app.sumOfftimeWp) ;
					 pause = avsptime>0?
							 		 pause>(diff - avsptime)?(diff - avsptime):pause
							 		:0; 	
				
				long calPausetime =(long) (diff - 1000*app.locDist/( (app.lastSavedLocation.getSpeed() + currentLoc.getSpeed())/2.0000) - app.sumOfftimeWp) ;
				 pause = calPausetime>0?calPausetime:0;  
			}
			
			
			long nt = diff  - pause	-  app.sumOfftimeWp;
			nt = nt > 0 ? nt : 0;
			sportTime += nt;
//			if(pause>0){
//			   // // // //// QLog.getLogger().dLog( TAG,  " currentLoc.getTime()-  app.lastSavedLocation.getTime(): "
//						+ (currentLoc.getTime()-  app.lastSavedLocation.getTime())); 
//				// // // //// QLog.getLogger().dLog(TAG, "  delta sporttime is: " + nt);
//				// // // //// QLog.getLogger().dLog(TAG,  "  pause is: " + pause);
//			}
		}*/
		
		
//		app.sumSpeed+= currentLoc.getSpeed();
//		app.spdCnt++;
		
		app.getRecordingTrack().getTrackBean().setSportTime(sportTime);
		
//		QLog.getLogger().d(dTAG, TAG + "  app.lastLocationTime: " + app.lastLocationTime);
//		QLog.getLogger().d(dTAG, TAG + "  sportTime: " +sportTime);
 
//		QLog.getLogger().d(dTAG, TAG + "  app.recordingTrack.getTrackBean().getSportTime(): " +app.recordingTrack.getTrackBean().getSportTime());
		StringBuffer sb = new StringBuffer();
		sb.append("{");

		// sb.append("\"lastlat\":" +lastloc.getLatitude());
		// sb.append(",\"lastlon\":"+lastloc.getLongitude()+",");

		sb.append("\"latitude\":" + currentLoc.getLatitude());
		sb.append(",\"longitude\":" + currentLoc.getLongitude());
	    sb.append(",\"bearDist\":" + String.format("%.2f",  app.bearDist));
		if (isBear) {
			// if( Math.abs(bear)>QiYouConstant.WPS_ROAD_BEARING)
			// {
			// float bear =bd.getFloat(KEY_Bearing);
			// sb.append(",\"roadBear\":"+ avBear);
			// sb.append(",\"turnFlag\":"+
			// getRoadTurnFlag2(currentLoc.getBearing(), targetBear));
			sb.append(",\"turnFlag\":" + getRoadTurnFlag2(avBear2, cTargetBear));
		
			sb.append(",\"targetBear\":" +String.format("%.2f",  cTargetBear) );
			// }
			sb.append(",\"bearing\":" + String.format("%.2f",  avBear2));
			sb.append(",\"cbearing\":" + String.format("%.2f",  currentLoc.getBearing()));
		} else
			sb.append(",\"bearing\":" + String.format("%.2f",  currentLoc.getBearing()));

		if (isSumbear) {
			sb.append(",\"sumBear\":" + sumBear);
//			sb.append(",\"roadB\":" + bear);

		}

		sb.append(",\"accuracy\":" + String.format("%.2f",  currentLoc.getAccuracy()));
		// sb.append(",\"blat\":" +Utils.getbdLat(currentLoc.getLatitude(),
		// currentLoc.getLongitude()));
		// sb.append(",\"blon\":"+Utils.getbdLon(currentLoc.getLatitude(),
		// currentLoc.getLongitude()));
		// if(lastAele !=100000 || QiYouConstant.DEVELOPER_MODE)
		// sb.append(",\"ele\":"+currentLoc.getAltitude()*1.0);
//		sb.append(",\"cele\":" + currentLoc.getAltitude() * 1.0); // 取连续点的平均海拔值
		if (!Float.isNaN(app.lastEle) && app.lastEle < QiYouConstant.MAX_ELE  )
			sb.append(",\"elevation\":" + String.format("%.2f",  app.lastEle));
		// else
		// sb.append(",\"ele\":"+ currentLoc.getAltitude()*1.0);
		// if(null !=bd && bd.containsKey(KEY_Adist)){
		// float eleDist =bd.getFloat(KEY_Adist);
		// // float cele = bd.getFloat(KEY_Altitude);
		//
		// sb.append(",\"eled\":"+ eleDist*1.00 );
		// }

		if (eleDist <  QiYouConstant.MAX_ELE  && !Float.isNaN(app.lastEle)) {
			sb.append(",\"eled\":" +String.format("%.2f",  eleDist)  );
		}
			sb.append(",\"upDist\":" + String.format("%.2f",  app.upDist) );
			sb.append(",\"downDist\":" + String.format("%.2f",  app.downDist) );
			if(  app.maxEle >-1000)
				sb.append(",\"maxEle\":" + String.format("%.2f",  app.maxEle) );
			if(app.minEle < QiYouConstant.MAX_ELE) 
				sb.append(",\"minEle\":" + String.format("%.2f",  app.minEle) ); 
		

		if (isKmflag) {

			sb.append(",\"kmflag\":" + app.getCntKm());
		}
		// sb.append(",\"time\":"+Utils.getUTC(bloc.getTime()));
		sb.append(",\"time\":" + currentLoc.getTime());
		sb.append(",\"readabletime\": \""
				+ Utils.getFormatedTime(currentLoc.getTime()) + "\"");
		sb.append(",\"sportTime\":" + sportTime);
		sb.append(",\"distance\":" + String.format("%.2f",  app.locDist));
		// sb.append(",\"odist\":"+ odist );
		// sb.append(",\"cspdist\":"+ cspdist );
		sb.append(",\"sumDist\":" + String.format("%.2f",  app.sumDist));

		if (pause > 0)
			sb.append(",\"pauseTime\":" + pause);

		// offtime =app.sumOfftimeWp;
		
		
		if (app.sumOfftimeWp > 0) 
		{
			sb.append(",\"offTime\":" + app.sumOfftimeWp);
		}

		// if(bloc.getSpeed()>0)
		sb.append(",\"speed\":" + String.format("%.2f",  currentLoc.getSpeed() * 3.6f));
		sb.append("}");

		// Log.e(dTAG,TAG+" "+sb.toString());
		return sb.toString();

	}

	int getRoadTurnFlag(float cBear, float target) {
		int flag = 0;
		// boolean turnR=false;
		boolean turnR = false;
		if (target >= 180) {
			turnR = cBear < target - 180 || cBear > target;
		} else {
			// turnR =cBear>target +180 || cBear<target;
			turnR = cBear < target + 180 && cBear > target;
		}

		flag = turnR ? 1 : -1;

		// if(Math.abs((cBear>180?cBear-360:cBear) -target)>160) flag=2; //折返

		return flag;
	}

	wpFlag getRoadTurnFlag2(float cBear, float target) {
		int flag = 0;
		cBear = cBear > 180 ? cBear - 360 : cBear;
		target = target > 180 ? target - 360 : target;
		// boolean turnR=false;
		boolean turnR = false;
		if (target >= 0) {
			turnR = cBear < target - 180 || cBear > target;
		} else {
			// turnR =cBear>target +180 || cBear<target;
			turnR = cBear < target + 180 && cBear > target;
		}

		flag = turnR ? 1 : -1;

		// if(Math.abs((cBear>180?cBear-360:cBear) -target)>160) flag=2; //折返

		return wpFlag.valueOf(flag);
	}
	
  private void speakNewKm(){ 
		
	  if(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL==2)return;
	  long timeUsed=System.currentTimeMillis() -app.timeKm;
	  if(timeUsed/1000/60<1)return;
	  long totalTime=app.getRecordingTrack().getTrackBean().getTotalTime()>timeUsed?app.getRecordingTrack().getTrackBean().getTotalTime():timeUsed;
	  String total =QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL==1? //STANDARD
			  String.format("您已运动%s公里，共用时%s，平均速度%.2f公里每小时，最高速度%.2f公里每小时，消耗热量%.2f卡路里，过去的一公里用时%s，加油",
			 				app.getCntKm(),
			//				(int)((app.getRecordingTrack().getTrackBean().getDistance()+500)/1000),
							Utils.getTimeCnt4Read(totalTime,true),
							app.getRecordingTrack().getTrackBean().getAvs(),
							app.getRecordingTrack().getTrackBean().getTopSpeed(),
							app.getRecordingTrack().getCalBurn(),
							Utils.getTimeCnt4Read(timeUsed,true) 
							)
			   : //SIMPLE
			   String.format("过去的一公里用时%s，您已运动%s公里，共用时%s",
					   			Utils.getTimeCnt4Read(timeUsed,true),
				 				app.getCntKm(),
//					   			 
								Utils.getTimeCnt4Read(totalTime,true) 
								);	
		
		
				
//		String lastKm=String.format("过去的一公里用时%s",
//				Utils.getTimeCnt4Read(System.currentTimeMillis() -app.timeKm,true)  
//				);
//		
//		app.speech(lastKm);
//		QLog.getLogger().dLog(TAG, 
//				String.format("track distance is:%.3f，app。cntKm :%s",
//						app.getRecordingTrack().getTrackBean().getDistance(),app.cntKm));
		app.speech(total,0);
  }
  
  
  
  
  
  
  void  sendShareLocation(){
 	  QLog.getLogger().dLog(TAG," begin to send shared location... ");
	  if(!QiYouConstant.PV_BL_SHARE_LOCATION || !Utils.isNetworkConnected(app))return;
	  long shareInterVal = QiYouConstant.DEVELOPER_MODE ?  QiYouConstant.PV_INT_LIVE_SPAN /10 :  QiYouConstant.PV_INT_LIVE_SPAN;
	  if(System.currentTimeMillis() - app.lastSharedTime > shareInterVal){
		  app.sendSharedLocation();
	  }
	  
	  
  }
  
  
  
  
  
  
  
  
  
  

	@Override
	public void onDestroy() {

		// Log.i(TAG,"Services onDestory");

		// // isStop=true;//即使service销毁线程也不会停止，所以这里通过设置isStop来停止线程
		// QLog.getLogger().d(TAG," save app.sumPaused "+app.sumPaused );
		// QLog.getLogger().d(TAG," save app.sumOfftime: "+app.sumOfftime );
		// QLog.getLogger().d(TAG,"---------app.sumPause loop----------------------------" );
//		app.saveLocationParameters(false);
		super.onDestroy();

	}

	/*@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
*/
	

}
