2012-11-08 2 views
0

안드로이드에서의 TimerTask는 대부분 한 번만 실행되며 때로는 더 자주 시작되어 중지됩니다.Android TimerTask는 한 번만 실행되지만 때로는 더 자주 실행됩니다.

기본적으로 앱의 센서 데이터를 추적하고 싶습니다.

Sensoring 및 Logging을위한 MainActivity와 2 개의 서비스가 있습니다.

다음은 로깅 부분 :

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    if (!started) { 
     started = true; 
    } 
    logfile = new File(Environment.getExternalStorageDirectory() + File.separator + "log.csv"); 
    if (!logfile.exists()) { 
     try { 
      logfile.createNewFile(); 
      //FileWriter fw = new FileWriter(logfile, true); 
      //fw.write("Modell;GPS-Zeit[Millis];Lat;Lon;Alt;Speed;AccX;AccY;AccZ;LinAccX;LinAccY;LinAccZ\n"); 
      //fw.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    myTimer = new Timer(); 
    myTimer.schedule(pingTimerTask, 1000, 1000); 
    myTimer.schedule(logTimerTask, 500,500); 
    Toast.makeText(this, "LogService started", Toast.LENGTH_SHORT).show(); 
    Log.i(T, "LogService started"); 
    return super.onStartCommand(intent, flags, startId); 
} 

과 여기의 TimerTask는 다음과 같습니다

TimerTask logTimerTask = new TimerTask() { 
    @Override 
    public void run() { 
     try { 
      logData(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
}; 

logdata()

private void logData() { 
     currentMsg = createMsg(); 
     try { 
      FileWriter fw = new FileWriter(logfile, true); 
      fw.write(currentMsg + "\n"); 
      fw.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     logSize+=currentMsg.length(); 
     for (Listener l : listener) { 
      l.logged(logfile.toString(), logSize); 
     } 
    } 

사람이 타이머 뭐가 잘못 말해 줄래?

감사

답변

0
당신이 onStartCommand의 기본 값을 반환하기 때문에 그것이 가장 가능성

:

return super.onStartCommand(intent, flags, startId); 
에 의해 대체되어야합니다

return START_STICKY; 

이 될 때까지 계속 실행 할 수있는 서비스를 만드는 명시 적으로 중지되므로 다른 곳에서 수동으로 중지해야합니다. 영원히 돌진하지 마십시오.

+0

소리가 맞지만 방금 시도했지만 로그 파일에 여전히 하나의 항목이 있습니다 .-( – Philipp

+0

처리기로 해결 : public void run() { /* 수행 할 작업 */ try { 같이 sendData(); } 캐치 (예외 전자) { // TODO 자동 생성 된 catch 블록 e.printStackTrace(); } /* 여기가 "속임수"*/ 핸들러를 온다. postDelayed (this, 500); } ............. handler.postDelayed (logTimerTask, 500); – Philipp