我开发了一个 Android 应用程序,它从服务器中提取单行文本消息。单击按钮后,它会发出一个函数调用,从服务器获取下一条消息。其中一些消息是基于时间的,
即这些消息必须在 TextView
中显示特定的时间,并且在该时间过去后,它应该自动调用函数以从服务器获取下一条消息(即无需单击按钮)。
有人可以帮助我实现这一目标吗?
我尝试使用 while 循环,如下所示:
while(!presentTime.equals(expiryTime)){
calculatePresentTym(); //This method calculates the presentTime value
display.settext(the received instruction);
}
if(presentTime.equals(expiryTime))
(make the function call)
如果我这样做,在 presentTime
和 expiryTime
相等之前不会显示任何内容。一旦它们相等,函数调用就会自动获取下一条指令并显示在 TextView 中。
最佳答案
使用处理程序
Handler m_handler;
Runnable m_handlerTask ;
m_handler = new Handler();
@Override
public void run() {
// do something
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
T0 取消运行
m_handler.removeCallbacks(m_handlerTask); // to cancel the run
您还可以使用计时器,但必须使用 runOnUiThread
来更新 ui,因为计时器在不同的线程上运行。
Timer _t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
@Override
public void run() {
//do something
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
//update ui
}
});
}
}, 1000, 1000 );
注意:
gets the next message from the server
从服务器获取消息应该在后台线程上完成。
编辑:
虽然复制粘贴初始化部分丢失。您有一个计数器 i 显示在 TextView 中。计数器每秒增加 1。当它达到 100 时,您取消运行。根据您的要求修改以下内容。
public class MainActivity extends Activity {
TextView tv;
Handler m_handler;
Runnable m_handlerTask ;
int i=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
m_handler = new Handler();
m_handlerTask = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if(i<=100)
{
tv.setText(""+i);
i++;
}
else
{
m_handler.removeCallbacks(m_handlerTask);
}
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
}
}
关于java - 如何在 TextView 中显示一些文本指定的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17584782/