views:

69

answers:

2

Hello! I was advised to use this code to make my method execute after a definite period of time, i modified it a bit and now I have:

private Handler mHandler = new Handler();
private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        final long start = mStartTime;

        // Get the difference in ms
        long millis = SystemClock.uptimeMillis() - start;

        // Format to hours/minutes/seconds
        int mTimeInSec = (int) (millis / 1000);

        // Do your thing

        Location location = tracker.getLastKnownLocation(best);
        RetrieveAvgPower(location);

        // Update at the next second
        mHandler.postAtTime(this, 1000);//start + ((mTimeInSec + 10) * 1000));
    }
};

And I try to start and stop it with:

public void onClick(View v) {
         switch (v.getId()) {
            case R.id.start:
                    mStartTime = System.currentTimeMillis();
                    mHandler.removeCallbacks(mUpdateTimeTask);
                    mHandler.postDelayed(mUpdateTimeTask, 1000);
                    break;
                case R.id.stop:
                    mHandler.removeCallbacks(mUpdateTimeTask);
                    break;}}

However, there is an issue. First of all, my method sets text and writes a line to log file, but if I use the code above text is not being set, however all info is being written to log file automatically. Another thing is i can't stop runnable - after it starts executing program seems to be not responding and crashes if I try to press stop button. What am I doing wrong and how it can be solved?

+2  A: 

Shouldn't the last line of run() call Handler.postDelayed() rather than Handler.postAtTime()?

Depending on how event queues are implemented in Android you might be killing the thread by using the wrong one... you're basically repeatedly setting a Runnable to run at 1 second after the thread originally started, so no other events get to run.

Reuben Scratton
A: 

To stop your runnable you can just add something like this:

class A implements Runnable
{
private volatile boolean runTask = false;

public void run()
{
runTask = true;
   while(runTask)
   {
      //Do your thing
   }
Thread.sleep(1000); //updates in the next second (Surround with try catch)
}


public void stop()
{
   runTask = false;
}


}

As for the text not updating I didnt understand very well, is it in a swing gui that is not setting?

EDIT Added a Thread.sleep(1000) at the end of the run method

fredcrs