Search code examples
androidtoast

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


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); 

}

Solution

  • 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);