gpt4 book ai didi

java - 为什么在新类中启动计时器时它可以工作,但当尝试停止计时器时却不能?

转载 作者:行者123 更新时间:2023-12-01 10:52:16 26 4
gpt4 key购买 nike

由于某种原因,计时器启动正常,但永远不会停止。

我创建了一个新类:

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);

我用断点检查了它是否到达那里,但计时器永远不会停止并继续。

最佳答案

customHandler.removeCallbacks(updateTimerThread);

而不是

customHandler.removeCallbacks(updateTimerThread = new UpdateTimerThread(timerValue));

如果您销毁某个对象并在其位置创建一个新对象,则不能指望处理程序找到该对象。

关于java - 为什么在新类中启动计时器时它可以工作,但当尝试停止计时器时却不能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33793904/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com