java - 如何在 Android 中使用计时器
问题描述
在我的应用程序中,我有一些工作的计时器。
当我的应用程序在一段时间后运行时,我的应用程序冻结并且无法运行任何视图!
在这个计时器中,每500 毫秒我emit
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);
}
});
我怎样才能在另一个中运行这个计时器thread
而不冻结我的应用程序?
解决方案
它应该类似于以下代码:
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);
}
}
推荐阅读
- sas - 具有自定义日期格式的 sas 格式变量 - 如何保留格式?
- php - file_exists() 从 phpunit 执行时有效,但不是从网页执行
- c++ - 如何修复 sfml c++ 代码编译错误?
- apache-flink - Flink 在 Kubernetes 中使用的内存比 taskmanager.memory.process.size 多
- ruby-on-rails - 如何在从 ERB 动态创建的 html 中调用 image_tag 和 number_to_currency
- wordpress - WordPress 根据自定义帖子类型过滤自定义分类法
- reactjs - 反应钩子状态不更新
- html - 将子 div 设为内联?
- c++ - 为什么 std::async 使用同一个线程运行函数
- parsing - 在 Rust 中返回多种类型的惯用方式