Android - 如何使用ScheduledExecutorService每10秒执行一次吐司?

时间:2012-02-25 09:45:49

标签: android toast

日志“你好”只出现一次,吐司根本没有出现..

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

}

1 个答案:

答案 0 :(得分:9)

尝试

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