系统服务详解之时间服务1

2、Handler是处理定时操作的核心类。通过Handler可以提交和处理一个Runnable对象。该类通过3个方法来处理Runnable对象:

                 立即执行:post ;指定时间执行:postAtTime;指定的时间间隔:postDelayed

因为该类处理对象为Runnable,所以在调用这3个方法之前,需要实现Runnable接口的run方法。

public class Main extends Activity implements OnClickListener, Runnable
{
	private Handler handler;
	private TextView tvCount;
	private int count = 0;

	class RunToast implements Runnable
	{
		private Context context;

		public RunToast(Context context)
		{
			this.context = context;
		}

		@Override
		public void run()
		{
			Toast.makeText(context, "15秒后显示Toast提示信息", Toast.LENGTH_LONG)
					.show();

		}
	}

	@Override
	public void onClick(View view)
	{
		switch (view.getId())
		{
			case R.id.btnStart:
				handler.postDelayed(this, 5000);
				break;
			case R.id.btnStop:
				handler.removeCallbacks(this);
				break;
			case R.id.btnShowToast:
				
				handler.postAtTime(new RunToast(this)
				{
				}, android.os.SystemClock.uptimeMillis() + 15 * 1000);
				break;

		}
	}

	@Override
	public void run()
	{
		tvCount.setText("Count:" + String.valueOf(++count));
		handler.postDelayed(this, 5000);

	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Button btnStart = (Button) findViewById(R.id.btnStart);
		Button btnStop = (Button) findViewById(R.id.btnStop);
		Button btnShowToast = (Button) findViewById(R.id.btnShowToast);
		tvCount = (TextView) findViewById(R.id.tvCount);
		btnStart.setOnClickListener(this);
		btnStop.setOnClickListener(this);
		btnShowToast.setOnClickListener(this);
		handler = new Handler();
		

	}
}


上一篇:RDS for SQL Serve使用OSS备份文件增量上云过程


下一篇:专访阿里云王伟民:一站式全链路,阿里云向云原生数据库2.0跃迁