我有这个按钮,我想为它设置一个计时器,这样用户不必每次都点击它,这样它每20秒自动点击一次这个按钮。我该怎么设置它?
基本上我使用的是tabhost活动,因此总共有3个标签。在第一个选项卡中,有这个按钮,我需要单击按钮,因此我能够从webservice检索信息,这个webservice每次都会更新。当我点击其他选项卡并返回第一个选项卡时,我希望它自动刷新..而不是单击按钮刷新。
holder.btnClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
答案 0 :(得分:2)
IMO使用ScheduledExecutorService的更有效方式:
private void doTheActualJobWhenButtonClicked() {
// put whatever you need to do when button clicked here
... ...
}
... ...
holder.btnClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// job triggered by user click button:
doTheActualJobWhenButtonClicked();
}
});
... ...
ScheduledExecutorService scheduleTaskExecutor= Executors.newScheduledThreadPool(1);
// This schedule a task to run every 20 seconds:
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
// job triggered automatically every 20 seconds:
doTheActualJobWhenButtonClicked();
}
}, 0, 20, TimeUnit.SECONDS);
更新: 如果您的按钮单击执行某些UI更新,例如TextView中的刷新文本,则只需进行换行 runOnUiThread()中的方法调用:
private void doTheActualJobWhenButtonClicked() {
myTextView.setText("refreshed");
}
ScheduledExecutorService scheduleTaskExecutor= Executors.newScheduledThreadPool(1);
// This schedule a task to run every 20 seconds:
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
// involved your call in UI thread:
runOnUiThread(new Runnable() {
public void run() {
doTheActualJobWhenButtonClicked();
}
});
}
}, 0, 20, TimeUnit.SECONDS);
此外,您需要在打开下一个活动或关闭当前活动之前正确关闭ScheduledExecutorService:
// Shut down scheduled task before starting next activity
if (scheduleTaskExecutor != null)
scheduleTaskExecutor.shutdownNow();
Intent intent = new Intent(getBaseContext(), NextActivity.class);
startActivity(intent);
... ...
public void onDestroy() {
super.onDestroy();
// Shut down scheduled task when closing current activity
if (scheduleTaskExecutor != null)
scheduleTaskExecutor.shutdownNow();
}
希望得到这个帮助。
答案 1 :(得分:1)
由于你有一个按钮,我假设你在某个地方有一个ActionPerformed
类型的方法。
鉴于此,您可以这样做:
public class AutoClick extends Thread {
// Time to wait in milliseconds
private long wait;
//Latency excepted
private long lat;
AutoClick(long time, long latency) {
wait = time;
lat = latency;
}
public void run() {
long start = System.getCurrentTimeMillis();
long current;
while(true)
current = System.getCurrentTimeMillis();
long step = (current-start) % 20000;
if(step <= latency || step >= wait-latency)
//call the action-performed method
}
}
然后创建一个线程实例并运行它:
public AutoClick clicker = new AutoClick(20000);
clicker.run();