首页 > 解决方案 > 如何在另一个活动的 Countdown OnFinish 时调用方法?

问题描述

我有一个具有 CountDownTimer 的类,它将在我的整个项目中使用,我想在不同活动的 Countdown onFinish() 上调用不同的方法。

这是我的 CountDownTimer 课程;

public class CountDownTimer {

    private static final long START_TIME_IN_MILLIS = 10000;
    private long timeLeftInMillis = START_TIME_IN_MILLIS;
    private final TextView textViewCountDown;
    private CountDownTimer countDownTimer;
    private boolean timerRunning;

    public CountDownTimer(TextView textView) {
        this.textViewCountDown = textView;
        startTimer();
    }

    public void startTimer() {
        countDownTimer = new android.os.CountDownTimer(timeLeftInMillis, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeLeftInMillis = millisUntilFinished;
                updateCountDownText();
            }

            @Override
            public void onFinish() {
                timerRunning = false;
            }
        }.start();
        timerRunning = true;
    }

    public void resetTimer() {
        timeLeftInMillis = START_TIME_IN_MILLIS;
        updateCountDownText();
    }

    public void pauseTimer() {
        countDownTimer.cancel();
        timerRunning = false;
    }
}

示例场景 - 一旦提示特定活动,倒计时将开始,用户有 10 秒的时间做他想做的任何事情,否则它将自动收集数据并验证。因此,一旦 10 秒结束,验证和数据收集方法应该从活动中调用。

我是 Android Dev 的新手,提前致谢!

标签: javaandroidcountdowntimer

解决方案


如果我必须从应用程序中的其他地方调用方法/函数,我会使用接口。

例如:

这是一个活动:


public class SomeActivity extends AppCompatActivity implements RemoteRunner.RemoteRunnerCallback{
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_about_us);

        RemoteRunner remoteRunnerObject = new RemoteRunner(this); 
        remoteRunnerObject.runExternalMethod(); // <--- This part calls the showMessage() function

    }

    private void showMessage(String message){
        Toast.makeText(this, message,Toast.LENGTH_LONG).show();
    }

    @Override
    public void onRemoteCalled(String message)

}

我想SomeActivity从这个类中运行一个方法:

public class RemoteRunner{
    
    public interface RemoteRunnerCallback{
        void onRemoteCalled(String message);
    }

    private RemoteRunnerCallback remoteRunnerListener;
    
    public RemoteRunner(RemoteRunnerCallback remoteRunnerListener){
        this.remoteRunnerListener = remoteRunnerListener;
    }

    public void runExternalMethod(){
        remoteRunnerListener.onRemoteCalled("This message is from RemoteRunner");
    }

}



推荐阅读