我有这个秒表需要在 30、45 和 60 秒后播放声音。
这是我的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.random1);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/tele.ttf");
TextView tv = (TextView) findViewById(R.id.bowman);
tv.setTypeface(tf);
mChronometer = (Chronometer) findViewById(R.id.chronometer1);
player1 = MediaPlayer.create(Random1.this, R.raw.stopwatch1);
player2 = MediaPlayer.create(Random1.this, R.raw.stopwatch2);
player3 = MediaPlayer.create(Random1.this, R.raw.stopwatch3);
player4 = MediaPlayer.create(Random1.this, R.raw.stopwatch4);
start = (Button) findViewById(R.id.bstartsw1);
stop = (Button) findViewById(R.id.bstopsw1);
reset = (Button) findViewById(R.id.bresetsw1);
vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
start.setTypeface(tf);
stop.setTypeface(tf);
reset.setTypeface(tf);
start.setOnClickListener(this);
stop.setOnClickListener(this);
reset.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bstartsw1:
mChronometer.start();
vib.vibrate(50);
break;
case R.id.bstopsw1:
mChronometer.stop();
vib.vibrate(50);
break;
case R.id.bresetsw1:
mChronometer.setBase(SystemClock.elapsedRealtime());
vib.vibrate(50);
finish();
startActivity(getIntent());
break;
}
mChronometer
.setOnChronometerTickListener(new OnChronometerTickListener() {
@Override
public void onChronometerTick(Chronometer chronometer) {
long elapsedTime = SystemClock.elapsedRealtime()
- chronometer.getBase();
if (elapsedTime > currentNeededTime1) {
player1.start();
currentNeededTime1 += currentNeededTime1 == 14500 ? 3600000
: 3600000;
} else if (elapsedTime > currentNeededTime2) {
player2.start();
currentNeededTime2 += currentNeededTime2 == 30000 ? 3600000
: 3600000;
} else if (elapsedTime > currentNeededTime3) {
player3.start();
currentNeededTime3 += currentNeededTime3 == 45000 ? 3600000
: 3600000;
} else if (elapsedTime > currentNeededTime4) {
player4.start();
currentNeededTime4 += currentNeededTime4 == 60000 ? 3600000
: 3600000;
}
}
});
}
}
不是最著名的解决方案,但它是一个解决方案。在重置按钮中,我设置了完成();开始活动(getIntent());所以它会根据我的需要重新加载活动和声音在 15、30、45 和 60 秒时正常播放。