Android: "Auto refresh" after a certain time

João Silva picture João Silva · Jun 14, 2013 · Viewed 25.3k times · Source

i have search how i can do an "Auto refresh" or a runnable method for my program, i saw some posts about handlers and threads... I think that what im search from is a thread but i cant get the program to work... Let me show you some code:

refresh.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            getUrlText();
            if (time.getText().toString().equals("")
                    || time.getText().toString().equals("0")) {
                mins = 0;
            } else {

                mins = Integer.parseInt(time.getText().toString());
                setTimer(mins);
                t.start();


            }

        }

        private void setTimer(int mins) {
            miliSecTime = mins * 60 * 1000;

        }
    });

    t= new Thread() {
        @Override
        public void run() {
            long start = System.currentTimeMillis();

            while (true) {
                long time = System.currentTimeMillis() - start;
                int seconds = (int) (time / 1000);
                if (seconds > miliSecTime) {
                    getUrlText();
                    start = System.currentTimeMillis();

                }
            }
        }
    };
}

So, this part of code should get a number from the user and then execute getUrlText(); every x minutes, where x is the number that user input... My problem should be in the run but i can't figure out what is... Thank you in advance for the help :)

Answer

Ken Wolf picture Ken Wolf · Jun 14, 2013

Here's one way to do it.

Declare these in your Activity:

Handler handler = new Handler();
Runnable timedTask = new Runnable(){

    @Override
    public void run() {
        getUrlText();
        handler.postDelayed(timedTask, 1000);
    }};

Then set your onClick:

button.setOnClickListener(new OnClickListener() {

    @Override
        public void onClick(View v) {
            getUrlText();
            handler.post(timedTask);
        }
    });

This will execute timedTask every 1000 milliseconds. Increase this number as necessary.

I'm not sure what you're doing with mins and so on but put all your logic that needs to be executed periodically into the timedTask Runnable. Hope that makes sense.