我目前正在开发一款具有多个CountDownTimer的Android应用。在一天的特定时间段内,只会激活其中一个CountDownTimer(例如,在上午9点到上午10点,对象myCountDownTimer [0]将被激活并从上午9点到上午10点倒计时,但在上午10点到11点,myCountDownTimer [0 ]将被停用,myCountDownTimer [1]将工作并倒计时直到上午11点)。但现在我遇到了一个问题。为了在myCountDownTimer [0]完成倒计时之后激活myCountDownTimer [1],我必须在MyCountDownTimer类之外调用myCountDownTimer [1]的构造函数。我试图在MyCountDownTimer类的onFinish()方法中初始化对象myCountDownTimer [1],但我的应用程序一直在崩溃。在做了一些研究之后,我想我必须使用回调来在不同的类之间进行通信。我尝试通过在线阅读和观看教程来理解回调方法,但我失败了。我还是很困惑。你能看一下我的代码并告诉我如何在我的代码中实现回调吗?非常感谢你,祝你有个美好的一天。
public class MainActivity extends Activity{
//...
private final int TIMER_SUM = 10;
MyCountDownTimer [] myCountDownTimer;
private int timerIndex;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myCountDownTimer = new MyCountDownTimer[TIMER_SUM];
timerIndex = 0;
myCountDownTimer[timerIndex] = new MyCountDownTimer(getRemainingTime(), 100);
myCountDownTimer[timerIndex].start();
}
private long getRemainingTime()
{
//The method that returns the remaining milliseconds until next specified time.
}
private class MyCountDownTimer extends CountDownTimer
{
public MyCountDownTimer(long millisInFuture,
long countDownInterval) {
super(millisInFuture, countDownInterval);
timerIndex++;
}
@Override
public void onTick(long millisUntilFinished) {
//This method display the remaining time.
}
@Override
public void onFinish() {
this.cancel();
//I want to add a callback here to tell the MainActivity to create a new MyCountDownTimer object.
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}