计时器应该工作不停止一旦我开始我的程序与一秒的间隔。在MainActivity的顶部,我添加了:
import java.util.Timer;
然后在MainActivity类中:
public class MainActivity extends ActionBarActivity
我补充说:
private Timer timer = new Timer();
现在我有了onCreate方法:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
currentActivity = this;
initTTS();
}
我怎样才能使定时器将开始工作,一旦我开始我的程序与一秒的间隔?
首先需要导入:
import java.util.Timer;
import java.util.TimerTask;
之后,你需要像这样设置你的计时器:
//Declare the timer
Timer myTimer = new Timer();
//Set the schedule function and rate
myTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//Called at every 1000 milliseconds (1 second)
Log.i("MainActivity", "Repeated task");
}
},
//set the amount of time in milliseconds before first execution
0,
//Set the amount of time between each execution (in milliseconds)
1000);
您可以使用如下方法之一启动计时器:
timer.schedule(new TimerTask() {
@Override
public void run() {
//do your stuff here...
}
}, 0, 1000);
这将以0毫秒的延迟启动计时器,并在1000毫秒后重复。
您应该至少阅读一下javadoc的标题:java.util.Timer.
我不太了解Android平台,但你必须谨慎使用线程。阅读这里:https://developer.android.com/guide/components/processes-and-threads.html#Threads
将时间间隔设置为1000,因为计时器中的时间间隔是以毫秒为单位的,所以1000毫秒= 1秒
尝试在属性选项卡中搜索属性"间隔",因为我使用netbeans并且有间隔,并且命令要放在Timer_Tick事件上,以确保每次间隔发生时命令都完成,这是每秒钟