我正在编写一个Android应用程序,它允许有人添加两个数字并输入答案。但我希望这些数字只显示5秒,然后显示一个新数字,如果他们输入正确或错误的答案,计时器重置并显示新数字.. 我已经编写了执行随机数的代码,而其他只是计时器无法执行 有人请帮忙
答案 0 :(得分:1)
使用Handler和Runnable应该适合您,但不要使用Anonymous runnable,因为它们可能导致内存泄漏。而是将runnable扩展为静态类,并在removeCallbacks
中使用onDestroy
。
此外,您可以使用WeakReference,因为onDestroy
不能保证被调用,因此如果您的活动被杀,WeakReference将允许GC释放内存
public class BarActivity extends AppCompatActivity {
private Handler mHandler;
private FooRunnable mRunnable;
private void finishActivityAfterDelay(int milliSeconds) {
mHandler = new Handler();
mRunnable = new FooRunnable(this);
mHandler.postDelayed(mRunnable, 5000); // 5 seconds
}
@Override
protected void onDestroy() {
mHandler.removeCallbacks(mRunnable);
super.onDestroy();
}
private static class FooRunnable implements Runnable {
private WeakReference<AppCompatActivity> mWeakActivity;
public FooRunnable(AppCompatActivity activity) {
mWeakActivity = new WeakReference<>(activity);
}
@Override
public void run() {
AppCompatActivity activity = mWeakActivity.get();
if (activity != null) activity.finish();
}
}
}
答案 1 :(得分:0)
您可以使用android.os.Handler
类来执行此操作,
像
private Handler handler = new Handler(); // Create Handler
Runnable runnable = new Runnable() {
@Override
public void run() {
// Perform action here...
}
};
handler.postDelayed(runnable, 3 * 1000); // action will be performed after 3 seconds.
答案 2 :(得分:0)
CountDownTimer timer = new CountDownTimer(30000/*modify value as per need*/, 1000) {
public void onTick(long millisUntilFinished) {
//millisUntilFinised is the remaining time
}
public void onFinish() {
//timer finished .Do what you need to do next here
}
};
使用timer.start();
,你必须启动计时器。