StalkerRus
StalkerRus

Reputation: 411

Problems with runnable

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?

Upvotes: 1

Views: 4578

Answers (2)

fredcrs
fredcrs

Reputation: 3621

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); // wait 1 second before "Do your thing" again
   }
}


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

EDIT by peer: Moved the Thread.Sleep(1000) so that the Runnable will run once a second until stopped (instead of running continuously and then waiting 1 second after being stopped).

Upvotes: 1

Reuben Scratton
Reuben Scratton

Reputation: 38707

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.

Upvotes: 2

Related Questions