clayton33
clayton33

Reputation: 4216

struggling with timer in android

All I am looking to do is run some function 5 seconds after the app starts. However i keep getting a "force close" after 5 sec. Is timerTask even the correct function to be using in a situation like this? How about if i want to press a button later in the program, and have an event occur 5 seconds after user presses the button?

package com.timertest;

import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;


public class timerTest extends Activity {

Timer timer = new Timer();
TextView test;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    test = (TextView)findViewById(R.id.test);
    timer.schedule(task, 5000);
}
TimerTask task = new TimerTask() {
    @Override
    public void run() {
        test.setText("task function run");
    }
};
}

Upvotes: 1

Views: 1935

Answers (2)

adamp
adamp

Reputation: 28932

A TimerTask will run on a background thread but you're trying to change UI. You want to run your operation on the UI thread instead. Android traditionally uses messages posted to a Handler to do this. A Handler will not create a new thread, when used as shown below it will simply attach to the same message queue that your app uses to process other incoming UI events.

public class Test extends Activity {
    private final Handler mHandler = new Handler();
    private TextView mTest;

    private Runnable mTask = new Runnable() {
        public void run() {
            mTest.setText("task function run");
        }
    };

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mTest = (TextView) findViewById(R.id.test);
        mHandler.postDelayed(mTask, 5000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(mTask);
    }
}

Upvotes: 4

AjOnFire
AjOnFire

Reputation: 2878

If you want to execute some code after 5 secs try the following...

 new CountDownTimer(5000,5000) 
        {
            @Override
            public void onTick(long millisUntilFinished) {
                            }

@Override public void onFinish() { // DO YOUR OPERATION } }.start();

Upvotes: 3

Related Questions