gpt4 book ai didi

java - 如何在Android中使用定时器

转载 作者:行者123 更新时间:2023-12-02 01:44:58 24 4
gpt4 key购买 nike

在我的应用程序中,我为某些作品设置了计时器
当我的应用程序运行一段时间后,我的应用程序卡住并且无法运行任何 View !
在此计时器中,每500ms发出 socket.io

我的代码:

   AsyncTask.execute(new Runnable() {
@Override
public void run() {
socketPingTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (isSendSocketPing) {
checkSocketPingTimer += startSocketPingTimer;
if (checkSocketPingTimer == sendSocketPingTimer) {
currentTimerForSocket = System.currentTimeMillis();
try {
detailSocketUtils.getSendRTTforPing(currentTimerForSocket + "");
} catch (Exception e) {
}
}
//Show ping (from search)
Constants.currentActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (isShownPing) {
detailToolbar_ping.setVisibility(View.VISIBLE);
if (checkSocketPingTimer > 500) {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.RED);

} else {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.GREEN);
}
} else {
detailToolbar_ping.setVisibility(View.GONE);
}
}
});
socketPing = checkSocketPingTimer;
}
}
}, 500, startSocketPingTimer);
}
});

如何在另一个线程中运行此计时器并且不卡住我的应用程序?

最佳答案

它应该类似于此代码:

class MyActivity extends Activity
{
private void executeLoop()
{
Handler myHandler = new Handler()
{
public void handleMessage(Message msg)
{
if (isShownPing)
{
detailToolbar_ping.setVisibility(View.VISIBLE);

if (checkSocketPingTimer > 500) {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.RED);

} else {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.GREEN);
}
} else
{
detailToolbar_ping.setVisibility(View.GONE);
}

}
}

socketPingTimer.scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
if (isSendSocketPing)
{
checkSocketPingTimer += startSocketPingTimer;
if (checkSocketPingTimer == sendSocketPingTimer) {
currentTimerForSocket = System.currentTimeMillis();
try {
detailSocketUtils.getSendRTTforPing(currentTimerForSocket + "");
} catch (Exception e) {
}
}

myHandler.sendEmptyMessage();

socketPing = checkSocketPingTimer;
}
}
}, 500, startSocketPingTimer);
}

}

关于java - 如何在Android中使用定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53827494/

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