java - 如何在另一个活动的 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 的新手,提前致谢!
解决方案
如果我必须从应用程序中的其他地方调用方法/函数,我会使用接口。
例如:
这是一个活动:
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");
}
}
推荐阅读
- python - 如何检查 Django Rest Framework 中每个请求中是否存在某些标头?
- javascript - 如何在 React js 中转换一个简单的 js 代码?
- awk - 如何通过使用awk忽略带有字符的行来找到该字段的最大值?
- angular - 我有这部分代码的解释吗?
- node.js - 网络错误:无法获取离子反应
- jsf - 由于 javax.faces.ViewState,无法从 Postman 加载网页?
- java - 使用 openapi-generator-gradle-plugin 只为 spring boot 生成 REST 接口
- python - 如何动态过滤 Pandas 数据框中的数据?
- javascript - 唯一数组Javascript中具有不同键的数组列表
- python - 处理 pandas Dataframe 中的 no-List