在我的 Android 应用程序中,我使用 TTS 和语音识别。尽管使用了所有可用的回调来了解它们所处的状态,但我仍然遇到无法处理的情况。示例:
1) TTS 报告初始化成功,但无法说话(某些自定义 TTS 引擎的已知问题(未提及名称))。
2) 初始成功连接后网络访问丢失,这可能会导致返回网络错误之前出现大量延迟。
还有其他情况我不会让您感到厌烦。
我已经阅读并消化了时间监控线程,例如 this和 this所以我知道如何准确确定 X 和 Y 之间的时间,但这是我追求的一种监控方法,当达到设定的限制时我可以使用react。
请原谅我的伪代码,但我举起双手,我不知道从哪里开始......
public boolean methodSuccess = false;
public void troublesomeMethod() {
if(// everything completed and I got a usual result) {
methodSuccess = true;
}
public boolean timeMonitor(int maxDuration) {
// use System.currentTimeMillis() here as start value
// monitor time elapsed here in loop
// monitor methodSuccess in loop
// return false if methodSuccess is set to true whilst in loop
// break if maxDuration reached and return true
}
再次,请原谅上面的代码,我根本不知道如何实现这个......
此外,如果我以以下方式开始上述内容:
boolean monitorThis = timeMonitor(5000); // let me know when 5 seconds have passed
startTroublesomeMethod(); // the one I want to monitor
如果我必须在 startTroublesomeMethod() 实际开始之前“等待”返回的 boolean 响应,那就毫无意义了!或者在我开始监控之前麻烦的方法就开始了......
if(monitorThis) {
// react to lagging method by destroying TTS or Listener Object
} else {
// the troublesomeMethod behaved normally - do nothing
}
我希望在我的困惑中我能够表达出我想要实现的目标。
预先感谢您的帮助。
最佳答案
您可以使用Handler
来发布延迟检查。例如:
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
@Override public void run() {
// You can set a flag or if you run your method
// on another thread, you can interrupt that thread.
}
}, 5000);
请记住,处理程序被设置为创建它的同一线程。如果您尝试监视的方法正在同一线程中运行,则可能会遇到问题。在另一个线程中调用您的方法,并保留对该线程的引用,以便在必要时中断它。
Thread mThread = new Thread(new Runnable() {
@Override public void run() {
// Call your method here and keep a reference to this thread.
}
});
mThread.run();
关于java - 监控流程或方法所花费的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11524202/