系统服务详解之时间服务0
作者:互联网
Android SDK中内置了多种时间服务,用于处理时间相关的操作。
1、计时器:Chronometer组件
这个组件可以以1秒为时间间隔进行计时。
示例如下:
public class Main extends Activity implements OnClickListener,
OnChronometerTickListener
{
private Chronometer chronometer;
private TextView tvTime;
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
@Override
public Object onRetainNonConfigurationInstance()
{
// TODO Auto-generated method stub
return super.onRetainNonConfigurationInstance();
}
@Override
public void onClick(View view)
{
switch (view.getId())
{
case R.id.btnStart:
chronometer.start();
break;
case R.id.btnStop:
chronometer.stop();
break;
case R.id.btnReset:
chronometer.setBase(SystemClock.elapsedRealtime());
break;
}
}
@Override
public void onChronometerTick(Chronometer chronometer)
{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
tvTime.setText("当前时间:" + sdf.format(new Date()));
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvTime = (TextView)findViewById(R.id.tvTime);
Button btnStart = (Button) findViewById(R.id.btnStart);
Button btnStop = (Button) findViewById(R.id.btnStop);
Button btnReset = (Button) findViewById(R.id.btnReset);
chronometer = (Chronometer) findViewById(R.id.chronometer);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
btnReset.setOnClickListener(this);
chronometer.setOnChronometerTickListener(this);
chronometer.setFormat("计时器:%s");
}
}
Chronometer组件默认之显示(H):MM:SS格式,通过setFormat方法设置显示信息。
标签:服务,void,系统,chronometer,Button,public,详解,Override,id 来源: https://blog.51cto.com/u_9894631/2789302