Looking Forward
Looking Forward

Reputation: 3585

Run asynctask periodically in android

Here, I've to run an asynctask periodically say at the interval of every 5 seconds. Below is my code,

//call asynctask at interval of 5 seconds

    final Handler handler = new Handler();
    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask()
    {       
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {       
                    try
                    {
                        new PerformBackgroundTask().execute();

                    } 
                    catch (Exception e) 
                    {

                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 5000); //execute in every 5s*



}

// call asynctask at interval of 5 seconds

public class PerformBackgroundTask extends AsyncTask<Void, Void, Void>
{


    @Override
    protected void onPreExecute() {
        super.onPreExecute();           
    }

    @Override
    protected Void doInBackground(Void... params) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, "Call at interval of 5 seconds" + "" + count , 500).show();

            }
        });
        count++;
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

    }
}

It is running completely for the first time when I run my app, means toast message is there at the interval of every 5 seconds. Now when I close the app and restart again, there are two toast messages (means I can say that, second instance of class is created), and new toast messages are created every time I restart the app. I want only one toast message (first one) every time I restart my app. How can I do this?

Upvotes: 2

Views: 5142

Answers (3)

P. Haller
P. Haller

Reputation: 75

Try to explicitly cancel the Timer anywhere inside onDestroy() or onPause() using timer.cancel(true).

Upvotes: 0

Praveen Sharma
Praveen Sharma

Reputation: 4348

You should use a service with alarm manager instead of Timer task.

check this one

and this one

Upvotes: 4

GOLDEE
GOLDEE

Reputation: 2318

Simply You can Cancel the AsyncTask When in Activities onPause() Method

Upvotes: 2

Related Questions