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

来源:互联网 发布:网络群众路线怎么做 编辑:程序博客网 时间:2024/05/17 23:31

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;}@Overridepublic void run(){Toast.makeText(context, "15秒后显示Toast提示信息", Toast.LENGTH_LONG).show();}}@Overridepublic 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;}}@Overridepublic void run(){tvCount.setText("Count:" + String.valueOf(++count));handler.postDelayed(this, 5000);}@Overridepublic 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();}}


原创粉丝点击