[英]Monitor time elapsed for a process or method
在我的Android應用程序中,我使用TTS和語音識別。 盡管使用所有可用的回調來了解它們所處的狀態,但仍然遇到無法處理的情況。 例子:
1)TTS報告初始化成功,但是無法講話(某些自定義TTS引擎的已知問題(未提及名稱))。
2)初始成功連接后,網絡訪問將會丟失,這可能會導致大量延遲,直到返回網絡錯誤。
在其他情況下,我不會讓您感到厭煩。
我已閱讀並消化時間監視線程比如這個和這個 ,所以我知道如何准確地確定X和Y之間的時間,但它是一個監測方法是我后,我可以達到設定限制時作出反應。
請原諒我的偽代碼,但是我舉起手來,不知道從哪里開始。
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()實際開始之前不得不“等待”返回的布爾響應,那將毫無意義! 或者麻煩的方法在我開始監視它之前就開始了...
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);
請記住,將Handler設置為與創建該線程的線程相同。如果要監視的方法在同一線程中運行,則可能會遇到問題。 在另一個線程中調用您的方法,並在需要時保留對該線程的引用以將其中斷。
Thread mThread = new Thread(new Runnable() {
@Override public void run() {
// Call your method here and keep a reference to this thread.
}
});
mThread.run();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.