由于某种原因,计时器开始正常,但从未停止。
我创建了一个新类:
package com.test.webservertest;
import android.os.Handler;
import android.os.SystemClock;
import android.widget.TextView;
/**
* Created by me on 11/18/2015.
*/
public class Timers
{
private long startTime = 0L;
private Handler customHandler = new Handler();
private long timeInMilliseconds = 0L;
private long timeSwapBuff = 0L;
private long updatedTime = 0L;
private String recordtimer;
private Runnable updateTimerThread;
public void StartTimer(TextView timerValue) {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread = new UpdateTimerThread(timerValue), 0);
}
public void StopTimer(TextView timerValue) {
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread = new UpdateTimerThread(timerValue));
}
public class UpdateTimerThread implements Runnable {
protected TextView timerValue;
public UpdateTimerThread(TextView timerValue) {
this.timerValue= timerValue;
}
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (timeInMilliseconds / 1000);
int mins = secs / 60;
secs = secs % 60;
int hours = mins / 60;
mins = mins % 60;
recordtimer = "Recording Time: " + String.format("%02d", hours) + ":" + String.format("%02d", mins) + ":" + String.format("%02d", secs);
timerValue.post(new Runnable()
{
public void run()
{
timerValue.setText(recordtimer);
}
});
//set yout textview to the String timer here
customHandler.postDelayed(this, 1000);
}
}
}
然后在MainActivity中我做了:
if (is_start == true)
{
timers.StartTimer(timerValueRecord);
response = Get(iptouse + "start");
is_start = false;
} else
{
timers.StopTimer(timerValueRecord);
textforthespeacch = "Recording stopped and preparing the file to be shared on youtube";
MainActivity.this.initTTS();
response = Get(iptouse + "stop");
is_start = true;
startuploadstatusthread = true;
servercheckCounter = 0;
}
计时器然后启动,但它在执行
时没有停止timers.StopTimer(timerValueRecord);
我检查了一个断点它到了那里,但计时器永远不会停止并继续。
答案 0 :(得分:1)
customHandler.removeCallbacks(updateTimerThread);
而不是
customHandler.removeCallbacks(updateTimerThread = new UpdateTimerThread(timerValue));
你不能指望处理程序找到一个对象,如果你销毁它来代替它。