Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - how to execute toast every 10 seconds using ScheduledExecutorService?

Tags:

android

toast

the log "hello" appear only one time , and the toast didn't appear at all ..

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ScheduledExecutorService scheduler =
            Executors.newSingleThreadScheduledExecutor();
    scheduler.scheduleAtFixedRate(new Runnable() {

        public void run() {
            Log.i("hello", "world");
            Toast.makeText(getApplicationContext(), "It works", Toast.LENGTH_SHORT).show();
            // TODO Auto-generated method stub

        }
    }, 10, 10, TimeUnit.SECONDS); 

}
like image 478
SaberTrika Avatar asked Jan 18 '23 09:01

SaberTrika


1 Answers

Try

        scheduler.scheduleAtFixedRate(new Runnable() {

        public void run() {
            Log.i("hello", "world");
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getApplicationContext(), "It works", Toast.LENGTH_SHORT).show();
                }
            });

        }
    }, 10, 10, TimeUnit.SECONDS);
like image 159
Vyacheslav Shylkin Avatar answered Jan 20 '23 15:01

Vyacheslav Shylkin