Mo Benito
Mo Benito

Reputation: 5

Java Android - Do a background loop function every 5sec

Im trying to show a toast (also in background) every 5 seconds but there is no way. There is my code:

    private void time() {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                Toast toast=Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT);
                toast.setMargin(50,50);
                toast.show();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

        }, 5000); // 5 sec

    }

}

Thanks

Upvotes: 0

Views: 47

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93561

Don't thread.sleep(5000). Have it do handler.post(this, 5000). That will repost the message 5s from now.

It still may not work (I'm not sure if you can toast every 5 seconds), but it will at least try.

Upvotes: 1

Related Questions