简体   繁体   中英

android timer exception onResume

I am properly executing a timed task on activity as follows. However, when activity onResume, an exeption is thrown, "Timer Task is scheduled already". I cancel timer once task is executed. How to solve it? thank you

final Runnable setButton = new Runnable() {
        public void run() {
            myClass.aBridge.button_back.setVisibility(View.INVISIBLE);
                timer.cancel();
        }
    };

    TimerTask task = new TimerTask(){
        public void run() {
            webPush.this.runOnUiThread(setButton);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();

            timer = new Timer();
            timer.schedule(task, 5000);

    }

task is called once before onResume as:

        timer = new Timer();
        timer.schedule(task, 5000);

You can only call timer.schedule() one time for each TimerTask instance. Create a new instance before you schedule it.

edit: for your code, don't initialize the TimerTask member variable at the point where you define it. Instead, create a new instance in your onResume(), right before you schedule it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM