public class MainActivity extends Activity { Timer timer = new Timer(); public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.button1).setOnClickListener(l); } OnClickListener l = new OnClickListener() { @Override public void onClick(View v) { // timer.schedule(task, 10000); 延迟十秒启动,执行一次 // timer.schedule(task, 10000, 10000); 延迟十秒启动,十秒启动一次 } }; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Log.i("test", "time up..."); timer.cancel(); } }; TimerTask task = new TimerTask() { public void run() { handler.sendEmptyMessage(1); } }; }
时间: 2024-10-12 16:20:46