android - 从 CountDownTimer 返回布尔值
问题描述
我有一个 5 秒倒计时计时器,我需要检测持续时间内的加速度幅度。如果幅度满足陈述,则返回一个真值。但是,由于 void 方法 OnTick 并且它也是一个内部类,我无法将任何值返回或传递给外部类。
public boolean low_high_Detection(final double ampA) {
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
final double low_TH = 9.0, high_TH = 10.5;
boolean lying_on_floor = false;
if(ampA > low_TH && ampA <high_TH)
{
lying_on_floor = true;
}
}
public void onFinish() {
Toast.makeText(detect.getBaseContext(), "5 seconds dectection over",Toast.LENGTH_SHORT).show();
}
}.start();
if (lying_on_floor == true)
{
return true;
}
return false;
}
任何人都可以建议我如何解决此方法?或者还有另一种处理方式。
解决方案
这可以通过匿名类作为侦听器来实现。
声明一个充当侦听器的接口。
public interface LowHightDetectionListener {
void onDetected(boolean result);
}
然后,调用此方法并将此侦听器的实例传递给该方法low_high_Detection()
low_high_Detection(ampA, new LowHightDetectionListener {
@Override
public void onDetected(boolean result) {
// Process the result
}
});
在这里,您将获得“返回”值。
要在方法中返回所需的值,low_high_Detection()
您需要调用侦听器。
public void low_high_Detection(final double ampA, final LowHightDetectionListener callback) {
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
final double low_TH = 9.0, high_TH = 10.5;
boolean lying_on_floor = false;
if(ampA > low_TH && ampA <high_TH) {
lying_on_floor = true;
callback.onDetected(true); // EXAMPLE OF RETURNING VALUE INSIDE AN ANONYMOUS CLASS
}
}
public void onFinish() {
Toast.makeText(detect.getBaseContext(), "5 seconds dectection over",Toast.LENGTH_SHORT).show();
}
}.start();
if (lying_on_floor == true) {
callback.onDetected(true);
return;
}
callback.onDetected(false);
}
}
推荐阅读
- c# - 使用动态属性反序列化 JSON,该属性包含一个数组到具有泛型类的字典
- python - 在 x 和 y 轴上具有对数刻度的 python 直方图
- c++ - 有什么方法可以返回主菜单吗?
- database - 对尝试感到困惑......除了在vb中
- javascript - 使用对象值动态合并数组
- python - 为什么 set() 构造函数比 list() 慢
- r - ggplot2 分组箱线图不会将不同时间点的组分开
- amazon-web-services - Redmine数据库yml中的AWS RDS SSL连接错误mysql2
- python - 这个模块'utils'的具体包是什么?
- haskell - 具有来自 IO 的第一个值的列表