在下面的代码中send()函数在一秒钟内执行多次,我想在一秒钟内执行一次send(),我如何更改代码
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
try {
send();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
},
1000,
1000);
Run Code Online (Sandbox Code Playgroud)
发送功能如下
void send() throws Exception, IOException
{
s=new Socket("10.0.2.2",4200);
r=new PrintWriter(s.getOutputStream());
while(true)
{
Log.e("msg","hi send\n");
r.print("hai");
}
}
Run Code Online (Sandbox Code Playgroud)
Logcat输出如下

我最近用Runnables/Handlers替换了计时器,它更容易
//declare at top of your activity
private Handler h = new Handler();
private Runnable myRunnable = new Runnable() {
public void run() {
//do stuff
//run again in one second
h.postDelayed(myRunnable, 1000);
}
};
//trigger the runnable somewhere in your code e.g. onClickHander or onCreate etc
h.postDelayed(myRunnable, 1000);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3983 次 |
| 最近记录: |