CamronK22
CamronK22

Reputation: 17

Android Timer/Clock

i want a clock/timer that's not insanely fast and force closes like a while loop. This force closes:

while(loopEnabled == true)
{
    //Do stuff
   Toast toast Toast.makeText(this, "Hi!", 10000);
    toast.show();
}

And so does this:

public void loop()
{
    //Do stuff
    Toast toast Toast.makeText(this, "Hi!", 10000);
    toast.show();

    resetLoop();
}

public void resetLoop()
{
    Thread.sleep(100);
    loop();
}

Any alternatives to stop this? I'm meaning for code to happen rapidly over and over.

Upvotes: 0

Views: 682

Answers (2)

Android Newbie
Android Newbie

Reputation: 711

Look at Handler especially the postAtTime or postDelayed methods.

For example:

private int mInterval = 1000; // in ms, so 1s here
private Handler mHandler;

@Override
protected void onCreate(Bundle bundle)
{

  mHandler = new Handler();
}

Runnable mRepeatingTask = new Runnable() 
{
     @Override 
     public void run() {

          // do something here

          // schedule run again for mTnterval ms from now
          mHandler.postDelayed(mRepeatingTask , mInterval);
     }
};

void startRepeatingTask()
{
    mRepeatingTask.run(); 
}

void stopTask()
{
    mHandler.removeCallbacks(mRepeatingTask);
}

Upvotes: 2

prijupaul
prijupaul

Reputation: 2086

Are you doing this in the UI thread? If so, avoid it as there is a high chance that you will get a Application Not Responding dialog.

In android timers can be implemented using TimerTask and also by Handlers.

Check this link for all sample codes. Async task, handler and timer

Upvotes: 1

Related Questions