package com.qiyou.mb.android.service;

import java.lang.reflect.Method;

import com.qiyou.mb.android.QiYouApplication;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.R;
import com.qiyou.mb.android.receivers.TimeTickReceiver;
import com.qiyou.mb.android.ui.MainActivity;
import com.qiyou.mb.android.ui.Welcome;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.TrackStatus;
import com.qiyou.mb.android.utils.log.QLog;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.PowerManager;
import android.util.Log;


import java.lang.reflect.InvocationTargetException;
 


public class TimtickService extends Service /*implements Runnable*/ {
	public final static String TAG = "com.qiyou.TimtickService";
	public static final String dTAG = "com.qiyou";
    Notification mNotification ;
    NotificationManager mNotificationManager;
    int NOTIFICATION_ID=1;
	
    int updateStaticsCnt=0;
    final int GPS_REQUEST_MINUTES=5;
	
	TimeTickReceiver timeTickReceiver;
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
//// QLog.getLogger()().d(dTAG,TAG+"... service TimtickService onStart.....," );
		if(intent!=null)
			handleIntent(intent);
		startAndroidGPSRequest();    
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId){
		// QLog.getLogger().d(dTAG,TAG+"... service TimtickService onStartCommand.....," );
		handleIntent(intent);
	    // We want this service to continue running until it is explicitly
	    // stopped, so return sticky.
		return START_STICKY;		
	}
	
	Handler mHandler;
	long registTime=0;
	protected QiYouApplication app; 
    @Override
	public void onCreate(){
    	/*mHandler = new Handler(Looper.getMainLooper());
        mHandler.post(this);*/
        super.onCreate();
    	 QLog.getLogger().d(dTAG,TAG+"... service TimtickService onCreate.....," );
    	app = (QiYouApplication) this.getApplication();		
    	if(!app.isLastTrackExist()){
    		// QLog.getLogger().d(dTAG,TAG+" no exist recording track exist,TimtickService return .............." );
    		return;
    	
    	}
    	if(app.isRouting)return;//路书不需要启动下面
    	
    	getForegroundMethod();
    	 try{
    		 setUpAsForeground("触摸可显示小驴子",Welcome.class);
    	 }catch(Exception e){
    		 Utils.logStackTrace(e, TAG);
    		 
    	 }
//    	 setUpAsForeground("触摸可显示小驴子",MainActivity.class); 
    	 timeTickReceiver =new TimeTickReceiver();
    	 regTimeTick();
    	 acquireWakeLock();
	}
    
    
   
 
     void regTimeTick(){
		IntentFilter javaFilter = new IntentFilter();  
	    javaFilter.addAction("android.intent.action.TIME_TICK");  
	    registerReceiver(timeTickReceiver, javaFilter);  
	    registTime =System.currentTimeMillis();
	    String debugstring=" TimtickService Time Tick regist at: "
				+ Utils.getFormatedTime( registTime)
				+ ",  Application instance start time is:" 
				+ Utils.getFormatedTime( app.startTime )
				+ ",Time past:"+Utils.getTimeCnt( app.startTime -registTime,true);
//QLog.getLogger().d(dTAG,TAG+ debugstring);
//Utils.logStackTrace(new Exception(debugstring),dTAG);
	    	QLog.getLogger().dLog( TAG,   debugstring);

	}

    void unregTimeTick(){ 
    	
	    unregisterReceiver(timeTickReceiver);
 }

    private void setUpAsForeground(String text,Class cls) {

    	Intent intent=new Intent(getApplicationContext(),	cls);
    	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    	intent.putExtra("noani", "1");
    	PendingIntent pendingIntent = PendingIntent.getActivity(
    	getApplicationContext(), 0,/* new Intent(getApplicationContext(),	cls)*/intent, PendingIntent.FLAG_UPDATE_CURRENT);
    	mNotification = new Notification();
    	mNotification.tickerText = text;
    	mNotification.icon = R.drawable.ic_launcher;// TODO 更换服务前置的图标
    	mNotification.flags = Notification.FLAG_ONGOING_EVENT;
    	 
//    	mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    	mNotification.setLatestEventInfo(getApplicationContext(), "运动中", text,
    	pendingIntent);
    
    /*	Notification noti = new Notification.Builder(this)        
    	 .setContentTitle("运动中")    
    	 .setContentText("运动中")        
    	 .setSmallIcon(R.drawable.ic_launcher)        
//    	 .setLargeIcon(R.drawable.ic_launcher)    
    	 .build();*/
    	 
    	
//    	startForeground(NOTIFICATION_ID, mNotification);
    	 startForegroundCompat(NOTIFICATION_ID, mNotification);
    	}
    
    
    void handleIntent(Intent intent){
    	
    	//to check if the application restart with new instances or not
    	// The check result is, the new application instance created, the original referenced application still exits.
    	
    	//TODO: to find what cause creating new application instances?
    	if(intent==null)return;
    	
    	/*if(QiYouApplication.lockStatic==null){
    		QLog.getLogger().dLog(  TAG ," lockStatic is null");
    	}else{
    		QLog.getLogger().dLog(  TAG ," lockStatic.isHeld():"+QiYouApplication.lockStatic.isHeld());
    	}*/
    	
    	if(app.isLastTrackExist() 
    			&&(QiYouApplication.lockStatic==null || !QiYouApplication.lockStatic.isHeld())){ 
    	 
	        getForegroundMethod();	        
	       	try{
	       		 setUpAsForeground("触摸可显示小驴子",Welcome.class);
	       	 }catch(Exception e){
	       		 Utils.logStackTrace(e, TAG);
	       		 
	       	 }
	//       	 setUpAsForeground("触摸可显示小驴子",MainActivity.class);
	       	if(timeTickReceiver==null)
	       		timeTickReceiver =new TimeTickReceiver();
	       	else{
	       		unregTimeTick();
	       	}
	       	 
	       	 regTimeTick();
	       	 
	       	 acquireWakeLock();
    	}
    	
    	String key = QiYouConstant.EXTRA_KEY_START_GPS;
    	if (intent.hasExtra(key)){
    		startAndroidGPSRequest();    		
    		return;
    	}
        key = QiYouConstant.EXTRA_KEY_STOP_GPS;
    	if (intent.hasExtra(key)){
    		stopAndroidGPSRequest();    		
    		return;
    	}
    	
        key = QiYouConstant.EXTRA_KEY_TICK_UPDATE; 
    	
		if (intent.hasExtra(key)) {
 			 QLog.getLogger().dLog(dTAG, TAG + " get notice to check gps.................., allower to update? QiYouConstant.PV_BL_SAVE_POWER: "+QiYouConstant.PV_BL_SAVE_POWER);
			
			if(QiYouConstant.PV_BL_SAVE_POWER){
				updateGPSstatus();
			}
			
			
			
			updateStaticsCnt++;
			if( updateStaticsCnt%3==0){ //do it on each 3 minutes
				// QLog.getLogger().dLog( TAG, " begin to update statistics, updateStaticsCnt: "+updateStaticsCnt +"updateStaticsCnt%3="+updateStaticsCnt%3);
				updateStaticsCnt=0;
				app.updateStatistics();  //update recording data into statistics.
				
			}
			return;
		}
		
		
    }
    
    
    
    private static final Class<?>[] mSetForegroundSignature = new Class[] {
        boolean.class};
    private static final Class<?>[] mStartForegroundSignature = new Class[] {
        int.class, Notification.class};
    private static final Class<?>[] mStopForegroundSignature = new Class[] {
        boolean.class};

    private NotificationManager mNM;
    private Method mSetForeground;
    private Method mStartForeground;
    private Method mStopForeground;
    private Object[] mSetForegroundArgs = new Object[1];
    private Object[] mStartForegroundArgs = new Object[2];
    private Object[] mStopForegroundArgs = new Object[1];

    void invokeMethod(Method method, Object[] args) {
        try {
            method.invoke(this, args);
        } catch (InvocationTargetException e) {
            // Should not happen.
            Log.w(dTAG, "Unable to invoke method", e);
        } catch (IllegalAccessException e) {
            // Should not happen.
            Log.w(dTAG, "Unable to invoke method", e);
        }
    }
boolean isForeground=false;
    /**
     * This is a wrapper around the new startForeground method, using the older
     * APIs if it is not available.
     */
    void startForegroundCompat(int id, Notification notification) {
        // If we have the new startForeground API, then use it.
    	isForeground=true;
    	if (mStartForeground != null) {
            mStartForegroundArgs[0] = Integer.valueOf(id);
            mStartForegroundArgs[1] = notification;
            invokeMethod(mStartForeground, mStartForegroundArgs);
            return;
        }

        // Fall back on the old API.
        mSetForegroundArgs[0] = Boolean.TRUE;
        invokeMethod(mSetForeground, mSetForegroundArgs);
        mNM.notify(id, notification);
        
    }

    /**
     * This is a wrapper around the new stopForeground method, using the older
     * APIs if it is not available.
     */
    void stopForegroundCompat(int id) {
    	isForeground=false;
        // If we have the new stopForeground API, then use it.
        if (mStopForeground != null) {
            mStopForegroundArgs[0] = Boolean.TRUE;
            invokeMethod(mStopForeground, mStopForegroundArgs);
            return;
        }

        // Fall back on the old API.  Note to cancel BEFORE changing the
        // foreground state, since we could be killed at that point.
        if(mNM==null)return;
        mNM.cancel(id);
        mSetForegroundArgs[0] = Boolean.FALSE;
        invokeMethod(mSetForeground, mSetForegroundArgs);
    }

   
    public void getForegroundMethod() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        try {
            mStartForeground = getClass().getMethod("startForeground",
                    mStartForegroundSignature);
            mStopForeground = getClass().getMethod("stopForeground",
                    mStopForegroundSignature);
            return;
        } catch (NoSuchMethodException e) {
            // Running on an older platform.
            mStartForeground = mStopForeground = null;
        }
        try {
            mSetForeground = getClass().getMethod("setForeground",
                    mSetForegroundSignature);
        } catch (NoSuchMethodException e) {
            throw new IllegalStateException(
                    "OS doesn't have Service.startForeground OR Service.setForeground!");
        }
    }
 
    void updateGPSstatus() {
    	 QLog.getLogger().dLog(dTAG, 	TAG 	+ " app.isLastTrackExist():" +app.isLastTrackExist());
		if(!app.isLastTrackExist() ||app.getRecordingTrack().getTrackBean().getStatus()==TrackStatus.PAUSED)return;
		
		if (app.canSendLocation2UI &&System.currentTimeMillis() -app.lastLocationTime> app.getGPS_REQUEST_SPAN()*2) {
//		 	if (!app.playBack) {
//				broadcastIntent = new Intent(this,	LocationMornitorService.class); // monitor the location
														// change //change it to fragment
				startService( new Intent(this,	LocationMornitorService.class));
//				QLog.getLogger().d(dTAG, 	TAG 	+ "  start MORNITOR_LOCATION_SERVICE by ACTION_TIME_TICK.");
				 // QLog.getLogger().dLog( TAG,   "start MORNITOR_LOCATION_SERVICE by ACTION_TIME_TICK.");
//		 	  }
		}
		
//		QLog.getLogger().dLog( TAG , " app.isLostGps()? "+app.isLostGps());
		  
//		QLog.getLogger().d(dTAG, TAG 
//				+ String.format(" app.isLostGps()?%s, app.isGPSstopped?%s,app.lastGpsStopTime?%s,app.lastGpsStartTime?%s"
//				,app.isLostGps(), app.isGPSstopped ,app.lastGpsStopTime ,app.lastGpsStartTime ));
//		
//		 QLog.getLogger().dLog( TAG,   String.format(" app.isLostGps()?%s, app.isGPSstopped?%s,app.lastGpsStopTime?%s,app.lastGpsStartTime?%s"
//					,app.isLostGps(), app.isGPSstopped ,Utils.getFormatedTime(app.lastGpsStopTime) ,Utils.getFormatedTime(app.lastGpsStartTime )));
		
//		if (app.playBack && !app.isLostGps()) {
//			 app.stopAndroidGPSRequest(); 
//			 return;
//		}
		
		 if (app.isLastTrackExist()) {
			  if(app.getExistTrackingID()>app.getRecordingTrack().getTrackBean().getTrackId())
				app.restoreLastTracking();
			}
		
//		boolean lostGPS = app.lastOfftime > 0;
		 // QLog.getLogger().dLog(dTAG, 	TAG 	+ " app.isLostGps():" +app.isLostGps()); 
		if (app.isLostGps()) {
//			if (app.lastGpsChkTime == 0)
//				app.lastGpsChkTime = System.currentTimeMillis();		
			app.GPS_SPAN_FACTOR =1;
			
//			QLog.getLogger().dLog(  dTAG ,TAG+" System.currentTimeMillis()  - app.startTime:  "		+ Utils.getTimeCnt((System.currentTimeMillis()  - app.startTime)));
//			
//			QLog.getLogger().dLog(  dTAG ,TAG+" QiYouConstant.MAX_GPS_OFF_TIME :  "	+ QiYouConstant.MAX_GPS_OFF_TIME );
//			
//			QLog.getLogger().dLog(dTAG, TAG+"System.currentTimeMillis()  - app.startTime< QiYouConstant.MAX_GPS_OFF_TIME  " +(System.currentTimeMillis()  - app.startTime< QiYouConstant.MAX_GPS_OFF_TIME ));
//			QLog.getLogger().dLog(dTAG, TAG+"app.lastGpsStopTime>0 &&(app.startTime - app.lastGpsStopTime > QiYouConstant.MAX_GPS_OFF_TIME)  " +(app.lastGpsStopTime>0 &&(app.startTime - app.lastGpsStopTime > QiYouConstant.MAX_GPS_OFF_TIME)));

			
			
			if( System.currentTimeMillis()  - app.startTime< QiYouConstant.MAX_GPS_OFF_TIME 
					||app.lastGpsStopTime>0 &&(app.startTime - app.lastGpsStopTime > QiYouConstant.MAX_GPS_OFF_TIME)){
				
//				QLog.getLogger().dLog(  TAG ," System.currentTimeMillis()  - app.startTime:  "
//						+ Utils.getTimeCnt((System.currentTimeMillis()  - app.startTime)));
//				
//				QLog.getLogger().dLog(  TAG ," app.startTime - app.lastGpsStopTime:  "
//						+ Utils.getTimeCnt((app.startTime  - app.lastGpsStopTime)));
				if(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL<2)
					app.speech("正在进行卫星定位",0);
//				app.startAndroidGPSRequest();
				startAndroidGPSRequest();
				// QLog.getLogger().dLog(  dTAG ,TAG+" Start the GPS request on the restart after app start if it is not started.) ");
				return;
			}
			
			
			// QLog.getLogger().dLog(dTAG, 	TAG 	+ " app.isGPSstopped:" + app.isGPSstopped); 
			if (app.isGPSstopped) {

//				QLog.getLogger().dLog(  TAG ," System.currentTimeMillis() - app.lastGpsStopTime:  "
//						+ Utils.getTimeCnt((System.currentTimeMillis() - app.lastGpsStopTime)));
				startAndroidGPSRequest(); //after stopped for 1 minute,start it again
//				QLog.getLogger().dLog(  TAG ," app.isGPSstopped ? "+app.isGPSstopped 
//						+ "  startAndroidGPSRequest by timeStickService service.");
				/*if (System.currentTimeMillis() - app.lastGpsStopTime > QiYouConstant.MAX_GPS_OFF_TIME*0.8) {
 					startAndroidGPSRequest();
 					QLog.getLogger().dLog(  TAG ," app.isGPSstopped ? "+app.isGPSstopped 
									+ "  startAndroidGPSRequest by timeStickService service.");
				}*/

			} else {
				
				
				// QLog.getLogger().dLog(  dTAG ,TAG+" System.currentTimeMillis() -  app.lastGpsStartTime  > QiYouConstant.MAX_GPS_OFF_TIME * 5 " +(System.currentTimeMillis() -  app.lastGpsStartTime  > QiYouConstant.MAX_GPS_OFF_TIME * 5));
				// QLog.getLogger().dLog(  dTAG ,TAG+" System.currentTimeMillis() -  app.lastGpsStartTime    " + Utils.getTimeCnt((System.currentTimeMillis()  - app.lastGpsStartTime)));

				if(  app.getRecordingTrack().getTrackBean().getTrackId() == 0  //app.gpsStartTime==0 //no gps ever got
						&&(System.currentTimeMillis() -  app.lastGpsStartTime  > QiYouConstant.MAX_GPS_OFF_TIME * 5)//if the interval since last start is long enough,then to start again.
				       ||  //or got gps ever, but stopped for saving power 
//				       app.lastGpsStartTime ==0
				       app.lastGpsStopTime>0
				       &&(System.currentTimeMillis() - app.lastGpsStopTime > QiYouConstant.MAX_GPS_OFF_TIME) // interval since last stopped	,stop 1 minute for saving power.					
					   
				       || app.lastGpsStopTime==0 &&  app.lastGpsStartTime ==0 //first time lostgps/stopped since last connected to gps.
						
						){
//					app.startAndroidGPSRequest();
					startAndroidGPSRequest();
//					app.lastGpsStopTime =0;
//					app.lastGpsStartTime = System.currentTimeMillis();
//				    QLog.getLogger().dLog(TAG	," startAndroidGPSRequest again by timeStickService  ");
					return;	
				}
					
				
//				if(app.canRecord() && app.lastGpsChkTime==0){ 
//					app.startAndroidGPSRequest();
//							
//				}
				
				
				/*
				if(app.lastGpsStartTime ==0 
						&&(System.currentTimeMillis() - app.lastGpsStopTime > QiYouConstant.MAX_GPS_OFF_TIME) ){
					
					app.startAndroidGPSRequest();
					app.lastGpsStopTime =0;
					app.lastGpsStartTime = System.currentTimeMillis();
				}
					*/
					
					
					
				long time2stop =QiYouConstant.MAX_GPS_OFF_TIME * GPS_REQUEST_MINUTES;//3; //每请求3分钟，停顿1分钟
//				long time2stop =app.getRecordingTrack().getTrackBean().getTrackId()>0?QiYouConstant.MAX_GPS_OFF_TIME * 2:QiYouConstant.MAX_GPS_OFF_TIME * 10;

				 //to stop gps request for saving power.
				if( app.getRecordingTrack().getTrackBean().getTrackId()>0 &&
						!app.canSendLocation2UI 
						&& app.lastGpsStartTime>0
						&&(System.currentTimeMillis() - app.lastGpsStartTime > time2stop)) { //interval since last started,it need big enough to connect to gps.
//					app.stopAndroidGPSRequest();
					stopAndroidGPSRequest();
//					app.lastGpsStartTime =0;
//					app.lastGpsStopTime =System.currentTimeMillis();
//					QLog.getLogger().dLog(TAG	, "  stopAndroidGPSRequest by timeStickService.");
				}
				
				

			} 
			

		}else {
			if(app.isNotMoving()){
//				app.stopAndroidGPSRequest();
			    // QLog.getLogger().dLog(TAG	," Not moving for long time,stop gps request by timeStickService  ");
//				QLog.getLogger().dLog(TAG	," Not moving for long time, update the gps_span interverl. ");

//				app.startAndroidGPSRequest();
				startAndroidGPSRequest();
			}
			
			app.lastGpsStartTime =0;
			app.lastGpsStopTime =0;
		}

	}
    

    //TODO: if the lock is still not working, then put it to applicaiton class,
    //lock/release the lock while regist /unregist timeticktservice.
    
  /*  private static volatile PowerManager.WakeLock lockStatic=null;

    synchronized private static PowerManager.WakeLock getLock(Context context) {
      if (lockStatic == null) {
        PowerManager mgr=
            (PowerManager)context.getSystemService(Context.POWER_SERVICE);

        lockStatic=mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        lockStatic.setReferenceCounted(true);
      }

      return(lockStatic);
    }
    */
    
//    PowerManager.WakeLock wakeLock;
private void acquireWakeLock() {
        /* if (wakeLock ==null) {
        	 QLog.getLogger().dLog(TAG,	" Acquiring wake lock");
                PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
                wakeLock.acquire();
         
            }*/
	  PowerManager.WakeLock lock=QiYouApplication.getLock(this.getApplicationContext());

	    if (!lock.isHeld()){
	    	lock.acquire();
//	    	QLog.getLogger().dLog(TAG,	" Acquired wake lock");
	    }
        
    }


private void releaseWakeLock() {
        /*if (wakeLock !=null&& wakeLock.isHeld()) {
            wakeLock.release();
            wakeLock =null;
            // // QLog.getLogger().dLog(TAG,	" Released wake lock");
        }*/
	  PowerManager.WakeLock lock=QiYouApplication.getLock(this.getApplicationContext());

	    if (lock.isHeld()){
	    	lock.release();
	    	// QLog.getLogger().dLog(TAG,	" Released wake lock");
	    }
    }
    






 	  LocationManager lm;
	  void startAndroidGPSRequest(){
		 
		if(app.getRecordingTrack().getTrackBean().getStatus() == TrackStatus.PAUSED) return;
		
		app.startNetworkLocationRequest(false);//先开启网络定位,收到gps信号后姜自动关闭网络定位
		
	/*	  while(!Utils.isGpsEnabled(this)){ 
			  try {
				Thread.sleep(QiYouConstant.MAX_GPS_SPAN*5);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
			  app.speech("请开启手机卫星定位");
		  }
		  */
		
//		if(!Utils.isGpsPermited(this)){
//			if(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL<2)
//				  app.speech(R.string.GPSNotPermited,1);
//		}else		
		  if(!Utils.isGpsEnabled(this)){
			  if(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL<2){
				  app.speech("请开启手机卫星定位",1);
			  }
			  
			  return;
		  }
//		if(!getGpsState(this));
//		{
//			//TODO: let user to toggle the GPS on.
//		}
		if(lm==null)lm =app.lm;// (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		
		if(!QiYouConstant.PV_BL_SAVE_POWER){
			app.GPS_SPAN_FACTOR=1;
		}
		
		
		
//		canRecord =true;
//		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, QiYouConstant.MAX_GPS_SPAN*app.GPS_SPAN_FACTOR,0,   locationListenerPendingIntent);
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, QiYouConstant.MAX_GPS_SPAN*app.GPS_SPAN_FACTOR,0,   listener, Looper.getMainLooper());
		// QLog.getLogger().dLog(dTAG, TAG+" QiYouConstant.MAX_GPS_SPAN*app.GPS_SPAN_FACTOR: " + QiYouConstant.MAX_GPS_SPAN*app.GPS_SPAN_FACTOR); 
		app.isGPSstopped =false;
		app.lastGpsStopTime=0;
		app.lastGpsStartTime = System.currentTimeMillis();
 		// QLog.getLogger().dLog(dTAG, TAG+" TimtickService startAndroidGPSRequest"); 
	}
	

	  void stopAndroidGPSRequest(){
//		 Log.d(dTAG,TAG + " stopping gps request ");	
		if(lm!=null){
//				lm.removeUpdates(locationListenerPendingIntent);
				lm.removeUpdates(listener);
//				 Log.i(dTAG,TAG + " stopped gps request ");	
			}
		app.isGPSstopped =true;
		app.lastGpsStartTime =0;
		app.lastGpsStopTime =System.currentTimeMillis();
//		this.canRecord =!this.playBack;
		if(!app.canRecord()){
			app.cancelForceDbAlarm();
		}
//		  QLog.getLogger().dLog(TAG," TimtickService stopAndroidGPSRequest");
		  
//		  Intent serviceIntent = new Intent(this, LocationService.class);
//		  stopService(serviceIntent);
//	      serviceIntent.putExtra(QiYouConstant.STOP_LOCATION_SERVICE, true);
//	      startService(serviceIntent); 
	}

	  @Override
	    public void onDestroy() {
		/*  mHandler.removeCallbacks(this);    */
		  
		  if(registTime==0 && app.isRouting){
			  stopAndroidGPSRequest();
			  return; 
		  }
		  if(registTime!=0){			
			 unregTimeTick();
		  }
	        // Make sure our notification is gone. 
	    	if(isForeground)
	    		stopForegroundCompat(NOTIFICATION_ID);
//	        QLog.getLogger().dLog(dTAG,TAG+"... service TimtickService onDestroy.....," );
	        stopAndroidGPSRequest();
	        releaseWakeLock();
	    }
//	  boolean isMaxProcessed;
	  Location lastLocation;
	private LocationListener listener = new LocationListener() {

	    @Override
	    public void onLocationChanged(Location location) {
	        // TODO Auto-generated method stub

//	        Log.e("Google", "Location Changed");

	        if (location == null)
	            return;
	        
	        app.lastLocationTime =System.currentTimeMillis();
	        
	        if(location.getAccuracy()>30 || location.getSpeed()<0.25){
	        	if(location.getSpeed()>0){
//		        	QLog.getLogger().dLog(TAG," loacation accuracy:" +location.getAccuracy());
//		    		QLog.getLogger().dLog(TAG," loacation speed:" +location.getSpeed());	    		
		    		location.setSpeed(0f);
	        	}
//	        	return;
	        }
	        
	        lastLocation= lastLocation ==null?(location):lastLocation;   
			if(location.getSpeed() >0 ||QiYouConstant.DEVELOPER_MODE){
				//to filter out the suddenly high speed.
				
				String pearTag="PEARTAG";
/*				QLog.getLogger().d(dTAG, "  PEARTAG get location change notice.................---------------------------------------------------");
				QLog.getLogger().d(dTAG, "  PEARTAG location.getSpeed() " +location.getSpeed());
				QLog.getLogger().d(dTAG, "  PEARTAG lastLocation.getSpeed() " +lastLocation.getSpeed());
				QLog.getLogger().d(dTAG, "  PEARTAG app.getRecordingTrack().getTrackBean().getTopSpeed() " +app.getRecordingTrack().getTrackBean().getTopSpeed()/3.6);
				QLog.getLogger().d(dTAG, "  PEARTAG location.getTime() -lastLocation.getTime()<4* QiYouConstant.MAX_GPS_SPAN  " +(location.getTime() -lastLocation.getTime()<4* QiYouConstant.MAX_GPS_SPAN ));
				QLog.getLogger().d(dTAG, "  PEARTAG location.getTime() -lastLocation.getTime() " +(location.getTime() -lastLocation.getTime()));
				QLog.getLogger().d(dTAG, "  PEARTAG 2*app.getRecordingTrack().getTrackBean().getAvs()/3.6 " +2*app.getRecordingTrack().getTrackBean().getAvs()/3.6);
*/				if(lastLocation!=null
	 					&& (  lastLocation.getSpeed()>0  && location.getSpeed()>2*lastLocation.getSpeed()
	 						  || lastLocation.getSpeed()==0 
	 								&& (    app.getRecordingTrack().getTrackBean().getTopSpeed()>0
	 											&& location.getSpeed()>app.getRecordingTrack().getTrackBean().getTopSpeed()/3.6 
	 										|| app.getRecordingTrack().getTrackBean().getTopSpeed()==0
	 											&& location.getSpeed()*3.6>30
	 									) 
	 						 )  
						&& location.getTime() -lastLocation.getTime()<4* QiYouConstant.MAX_GPS_SPAN 
						&& 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() "+lastLocation.getSpeed()*3.6);
					QLog.getLogger().dLog(TAG,pearTag, "  2*app.getRecordingTrack().getTrackBean().getAvs()  "+ 2*app.getRecordingTrack().getTrackBean().getAvs() );
					*/
					return;
				
				} 
			}
			
			
			
	        
	    	
			if(app.lastSavedLocation==null)app.lastSavedLocation=location;
			
//	        QLog.getLogger().d(dTAG, TAG+" gps locaiton change Receiver got noticed, and sending to locationService.");
//            // QLog.getLogger().dLog(TAG," gps locaiton change Receiver got noticed ");
//              QLog.getLogger().dLog(TAG," Location Receiver got the new location");
//	    	
//	    	Log.e(TAG, "GPS time:" +Utils.getFormatedTime(location.getTime()));
              
           if(app.getRecordingTrack().getTrackBean().getStatus()== TrackStatus.RECORDING ){
        	    String key = LocationManager.KEY_LOCATION_CHANGED;		   
		       Intent serviceIntent = new Intent(app, LocationService.class);		
		      
		     /*  Bundle bd = new Bundle(); 
		       if(app.lastSavedLocation==null ||app.lastSavedLocation.getTime()==0){
					app.lastSavedLocation=location;
					QLog.getLogger().dLog( TAG,  " app.lastSavedLocation is null. ");
				} 
		       
		       long diff = location.getTime() - lastLocation.getTime() ;
				 double sdist; 
				if(   diff <=  QiYouConstant.MAX_TIME_UPDATE_DB*10){
				 			    
//					sdist =   (isFirstwp?0:Utils.getDistance2(currentLoc, app.lastLocation));
					
					sdist =   Utils.getDistance3(location, lastLocation);
//					app.sumDiff+=sdist -Utils.getDistance(location, app.lastSavedLocation) ; 
					
//					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" +QiYouConstant.MAX_TIME_UPDATE_DB +" ,diff is" +diff  );
					
				}
				
		       
			       
			   	if (Math.round(app.sumDist) == 0 || Double.isNaN(app.sumDist ) //||Double.isNaN(app.sumDist)//app.sumDist == Float.NaN
						  ) {
					app.sumDist2 = 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.sumDist2 = 0;
				}
				
				app.sumDiff2+=sdist -Utils.getDistance(location, lastLocation) ;
				QLog.getLogger().dLog(TAG," app.sumDiff2 " + app.sumDiff2);
				app.sumDist2+=sdist;
		        bd.putDouble("sumdist", app.sumDist2);
		        location.setExtras(bd);*/
//		       location.getExtras().put
		       
		       
		       serviceIntent.putExtra(key,  location); 
		       startService(serviceIntent); 
		       
		       
		       
		       lastLocation=location;
           }
          
//	         QLog.getLogger().dLog(TAG," Location is here 01 ");
	       if(Utils.canUpdateUI(app)){
	    		Intent broadcastIntent = new Intent();
				broadcastIntent
						.setAction(QiYouConstant.ACTION_NEW_LOCATION_GETBACK);
				broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); 
			    broadcastIntent.putExtra(QiYouConstant.NEW_LOCATION, location);
			    sendBroadcast(broadcastIntent); 
	    }
	       app.lastNaviLocation= location;

	}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			
		}
	    
	 
	};
	/*@Override
	public void run() {
		// TODO Auto-generated method stub
		
	}*/
	
}




	 


 