0

my TimerTask in Android runs most of the time just once, sometimes it starts a bit more often and stops then.

Basically I want an App to track the sensor-data of the device.

I have a MainActivity and 2 Services for Sensoring and Logging.

Here's the logging part:

@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);
}

and here's the 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);
        }
    }

Can anyone tell me what's wrong with the Timer?

Thanks

Philipp
  • 468
  • 3
  • 24

1 Answers1

0

Most likely it is because you are returning the default values on onStartCommand:

return super.onStartCommand(intent, flags, startId);

Should be replaced by:

return START_STICKY;

This makes the service to continue running until it is explicitly stopped, so you'll have to stop it manually somewhere else, do not let it runing forever.

Aerinx
  • 152
  • 4
  • that sounds correct, I just tried it but I still got just one entry in the logfile :-( – Philipp Nov 09 '12 at 00:45
  • solved it with a handler: public void run() { /* do what you need to do */ try { sendData(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } /* and here comes the "trick" */ handler.postDelayed(this, 500); } ............. handler.postDelayed(logTimerTask, 500); – Philipp Nov 12 '12 at 02:22