我創建了一個可以使用我們的SIP服務器進行調用的應用程序。現在我想要做的是向用戶顯示他的通話持續了多久。我的腳本實際上正在工作,但我注意到通話時間越長,我的應用程序就會變慢。下面是我的代碼Handler.postDelayed導致延遲
Handler h = new Handler(Looper.getMainLooper());
_isOnCall = true;
long time = 0;
int x = 0;
while(_isOnCall) {
if (_isOnCall){
final int counter = 1 + x;
time += 1000;
h.postDelayed(new Runnable() {
@Override
public void run() {
(TargetDetailsActivity.this).runOnUiThread(new Runnable() {
@Override
public void run() {
final int seconds = counter % 60;
final int minutes = (counter % 3600)/60;
final int hours = counter/3600;
callcounter.post(new Runnable() {
@Override
public void run() {
callcounter.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
}
});
}
});
}
}, time);
x++;
}else{
break;
}
}
的片段基本上什麼代碼所做的僅僅是計數秒/分鐘/小時他一直在打電話。當他掛斷電話時,我撥打以下代碼:
_isOnCall = false;
h.removeCallbacksAndMessages(null);
我不確定是什麼原因導致了延遲。幫幫我!謝謝。
UPDATE
我能夠通過使用定時器利用高爾文的建議,使這一工作。這是我以供將來參考代碼:
private Timer myTimer;
private int counter_time=0;
public void onCallEstablished() {
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
private void TimerMethod()
{
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
counter_time++;
int seconds = counter_time % 60;
int minutes = (counter_time % 3600)/60;
int hours = counter_time/3600;
callcounter.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
}
};
public void releaseCall(){
if(myTimer != null){
myTimer.cancel();
myTimer.purge();
counter_time = 0;
}
}
是while循環在UI線程上運行? – Blackbelt
@Blackbelt uhm抱歉,我不完全知道你對UI線程的意思。我對android非常陌生。 :( – user3360031
@ user3360031:發佈完整的代碼,這段代碼是否寫在UI線程中? –