我已经使用计时器在特定时间段后调用某些功能。
我用以下代码完成了这项工作:
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
public void run() {
Toast.makeText(getApplicationContext(),"Insidedsfdsf Click " , Toast.LENGTH_LONG).show();
UpdateTask();
}
}, 1, 1000);
public void UpdateTask() {
// TODO Auto-generated method stub
try
{
Toast.makeText(getApplicationContext(),"update " , Toast.LENGTH_LONG).show();
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
String id = intent.getStringExtra(MainActivity.EXTRA_ID);
String[] lst = null;
String[] lstNew = null;
ListView lm=(ListView)findViewById(R.id.listView1);
TextView tv = (TextView)findViewById(R.id.textView1);
TextView tvNewMessages = (TextView)findViewById(R.id.tvNewMessages);
tv.setText("Welcome " + message);
CallSoap cs=new CallSoap();
lst=cs.GetMessage(id);
lstNew=cs.GetNewMessage(id);
final int numOfMessages=lstNew.length;
//Toast.makeText(getApplicationContext(),"Call "+lstNew.length , Toast.LENGTH_LONG).show();
tvNewMessages.setText("You have "+ numOfMessages +" new messages");
ArrayAdapter<String> adpt = new ArrayAdapter<String>(Messages.this, android.R.layout.simple_list_item_1,lst){
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
if(position<numOfMessages){
v.setBackgroundColor(Color.RED);
}
else
{
v.setBackgroundColor(Color.WHITE);
}
return v;
}
};
lm.setAdapter(adpt);
}
catch(Exception ex)
{
ex.printStackTrace();
//Toast.makeText(getApplicationContext(),"Call "+ex.getMessage() , Toast.LENGTH_LONG).show();
}
}
但我发现我的UpdateTask函数没有被调用,而在logcat中它显示错误:
can't create handler inside thread
请帮帮我。
答案 0 :(得分:2)
计时器任务在不同的线程上运行。 Ui应该在ui线程上更新。
所以你可以使用Handler
。或使用runOnUiThread
Handler m_handler;
Runnable m_handlerTask ;
m_handler = new Handler();
m_handlerTask = new Runnable()
{
@Override
public void run() {
// do something
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
另请将此作为附注
编辑:
您每次都在初始化您的观看次数。将其移至onCreate
并将其声明为类成员
ListView lm=(ListView)findViewById(R.id.listView1);
TextView tv = (TextView)findViewById(R.id.textView1);
TextView tvNewMessages = (TextView)findViewById(R.id.tvNewMessages);
答案 1 :(得分:1)
你必须使用它:
Handler h = new Handler();
Runnable r = new Runnable(){
@Override
public void run() {
//perform action here.
h.postDelayed(m_handlerTask, 1000);
}
};
h.run();
答案 2 :(得分:1)
或者您可以尝试CountDownTime
new CountDownTimer(x, x) {
public void onTick(long millisUntilFinished) {
Toast.makeText(getApplicationContext(),"Insidedsfdsf Click " , Toast.LENGTH_LONG).show();
}
public void onFinish() {
UpdateTask();
}
}.start();