public class myActivity extends Activity {
private Timer myTimer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
//Do something to the UI thread here
}
};
}
final ScheduledExecutorService SCHEDULER = Executors.newScheduledThreadPool(1);
安排你运行:
final Future<?> future = SCHEDULER.schedule(Runnable task, long delay,TimeUnit unit);
您现在可以使用 future 取消任务或检查是否已完成,例如:
future.isDone();
希望您会发现这对于在Android中创建任务非常有用 .
完整的例子:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Future<?> sampleFutureTimer = scheduler.schedule(new Runnable(), 120, TimeUnit.SECONDS);
if (sampleFutureTimer.isDone()){
// Do something which will save world.
}
17
void method(boolean u,int max)
{
uu=u;
maxi=max;
if (uu==true)
{
CountDownTimer uy = new CountDownTimer(maxi, 1000)
{
public void onFinish()
{
text.setText("Finish");
}
@Override
public void onTick(long l) {
String currentTimeString=DateFormat.getTimeInstance().format(new Date());
text.setText(currentTimeString);
}
}.start();
}
else{text.setText("Stop ");
}
421
我认为你可以用Rx方式做到:
timerSubscribe = Observable.interval(1, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
//TODO do your stuff
}
});
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class TestActivity extends Activity {
TextView timerTextView;
long startTime = 0;
//runs without a timer by reposting this handler at the end of the runnable
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerTextView.setText(String.format("%d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);
timerTextView = (TextView) findViewById(R.id.timerTextView);
Button b = (Button) findViewById(R.id.button);
b.setText("start");
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Button b = (Button) v;
if (b.getText().equals("stop")) {
timerHandler.removeCallbacks(timerRunnable);
b.setText("start");
} else {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
b.setText("stop");
}
}
});
}
@Override
public void onPause() {
super.onPause();
timerHandler.removeCallbacks(timerRunnable);
Button b = (Button)findViewById(R.id.button);
b.setText("start");
}
}
0
这是一个计时器的简单代码:
Timer timer = new Timer();
TimerTask t = new TimerTask() {
@Override
public void run() {
System.out.println("1");
}
};
timer.scheduleAtFixedRate(t,1000,1000);
0
很简单!你创建了新的计时器 .
Timer timer = new Timer();
然后扩展计时器任务
class UpdateBallTask extends TimerTask {
Ball myBall;
public void run() {
//calculate the new position of myBall
}
}
然后以一些更新间隔将新任务添加到Timer
final int FPS = 40;
TimerTask updateBall = new UpdateBallTask();
timer.scheduleAtFixedRate(updateBall, 0, 1000/FPS);
18 回答
他是一个更简单的解决方案,在我的应用程序中运行良好 .
如果您还需要在UI线程上运行代码(而不是在计时器线程上),请查看博客:http://steve.odyfamily.com/?p=12
如果有人感兴趣,我开始玩创建一个在活动UI线程上运行的标准对象 . 似乎工作正常 . 欢迎评论 . 我希望布局设计器可以将其作为拖动到Activity的组件 . 不敢相信这样的东西还不存在 .
在活动中,我有这个onStart:
您需要创建一个线程来处理更新循环并使用它来更新textarea . 但棘手的部分是只有主线程才能实际修改ui,因此更新循环线程需要通知主线程进行更新 . 这是使用Handler完成的 .
看看这个链接:http://developer.android.com/guide/topics/ui/dialogs.html#点击 Headers 为"Example ProgressDialog with a second thread"的部分 . 这是您需要做的一个示例,除了使用进度对话框而不是文本字段 .
您希望UI更新发生在已存在的UI线程中 .
最好的方法是使用一个Handler,它使用postDelayed在延迟后运行Runnable(每次运行安排下一个);使用removeCallbacks清除回调 .
你_____1859_ t你想要什么 . (另见Updating the UI from a Timer的相同文章) .
如果你已经有增量时间了 .
对于那些不能依赖Chronometer的人,我提出了一个实用类,其中一个建议是:
}
使用..只是做:
.....
因为这个问题仍然吸引了很多谷歌搜索用户(关于Android计时器),我想插入我的两个硬币 .
首先,Timer类将在Java 9 (read the accepted answer)中弃用 .
official建议的方法是使用ScheduledThreadPoolExecutor,它更有效,功能更丰富,可以额外安排命令在给定的延迟后运行,或定期执行 . 此外,它还提供了ThreadPoolExecutor的额外灵活性和功能 .
以下是使用简单功能的示例 .
future
取消任务或检查是否已完成,例如:希望您会发现这对于在Android中创建任务非常有用 .
完整的例子:
我认为你可以用Rx方式做到:
取消这个就像:
Rx定时器http://reactivex.io/documentation/operators/timer.html
你也可以使用动画师:
这是一个简单可靠的方法......
将以下代码放在Activity中,当您的活动处于“恢复”状态时,将在UI线程中每秒调用tick()方法 . 当然,您可以更改tick()方法以执行您想要的操作,或者更频繁或更不频繁地调用 .
对于那些感兴趣的人,如果您的活动暂停并在滴答期内恢复,则必须使用“_h0 = _handler”代码以避免两个定时器同时运行 .
我很惊讶没有答案可以提及RxJava2的解决方案 . 它非常简单,并提供了一种在Android中设置计时器的简便方法 .
首先,您需要设置Gradle依赖项,如果您还没有这样做:
(用current version number替换
x
和y
)由于我们只有一个简单的 NON-REPEATING TASK ,我们可以使用
Completable
对象:对于 REPEATING TASK ,您可以以类似的方式使用
Observable
:Schedulers.computation()
确保我们的计时器在后台线程上运行,.observeOn(AndroidSchedulers.mainThread())
表示我们在计时器完成后运行的代码将在主线程上完成 .为避免不必要的内存泄漏,您应确保在销毁Activity / Fragment时取消订阅 .
.XML
好吧,因为这还没有解决,有3种简单的方法来处理这个问题 . 下面是一个显示所有3的示例,底部是一个示例,显示了我认为更可取的方法 . 还记得在onPause中清理你的任务,必要时保存状态 .
要记住的主要事情是UI只能从主ui线程修改,所以使用处理程序或activity.runOnUIThread(Runnable r);
这是我认为首选的方法 .
这是一个计时器的简单代码:
很简单!你创建了新的计时器 .
然后扩展计时器任务
然后以一些更新间隔将新任务添加到Timer
免责声明:这不是理想的解决方案 . 这是使用Timer类的解决方案(由OP提出) . 在Android SDK中,建议使用Handlerclass(在接受的答案中有例子) .
如果一个人只想安排倒计时,直到将来有定期通知的时间段,您可以使用自API级别1以来可用的CountDownTimer类 .