13

In my method, I want to call another method that will run 1 second later. This is what I have.

final Timer timer = new Timer();

timer.schedule(new TimerTask() {
    public void run() {
          MyMethod();
          Log.w("General", "This has been called one second later");
        timer.cancel();
    }
}, 1000);

Is this how it's supposed to be done? Are there other ways to do it since I'm on Android? Can it be repeated without any problems?

djcouchycouch
  • 12,724
  • 13
  • 69
  • 108

4 Answers4

29

There are several alternatives. But here is Android specific one.

If you thread is using Looper (and Normally all Activity's, BroadcastRecevier's and Service's methods onCreate, onReceive, onDestroy, etc. are called from such a thread), then you can use Handler. Here is an example:

Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
     @Override
     public void run()
     {
         myMethod();
     }
}, 1000);

Note that you do not have to cancel anything here. This will be run only once on the same thread your Handler was created.

Community
  • 1
  • 1
inazaruk
  • 74,247
  • 24
  • 188
  • 156
  • +1, this is a neat approach. I've never done anything with the Android platform, so this is probably the better approach. my answer is more generic. – mre Jun 01 '11 at 17:40
17

Instead of a Timer, I'd recommend using a ScheduledExecutorService

final ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);

exec.schedule(new Runnable(){
    @Override
    public void run(){
        MyMethod();
    }
}, 1, TimeUnit.SECONDS);
mre
  • 43,520
  • 33
  • 120
  • 170
2

If you are not in UI thread, consider adding a very simple:

try
{
  Thread.sleep( 1000 );
}//try
catch( Exception ex)
{ ex.printStackTrace(); }//catch

//call your method
Snicolas
  • 37,840
  • 15
  • 114
  • 173
1

ScheduledExecutorService or AsyncTask for UI related.

Note that if you are to update UI, that code should be posted to UI thread. as in Processes and Threads Guide

        final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");
        mImageView.post(new Runnable() {
            public void run() {
                mImageView.setImageBitmap(bitmap);
            }
        });

There is also nice postDelayed method in View

    mImageView.postDelayed(new Runnable(){
        @Override
        public void run() {
            mImageView.setImageResource(R.drawable.ic_inactive);
        }
    }, 1000);

that will update UI after 1 sec.

Paul Verest
  • 60,022
  • 51
  • 208
  • 332