简体   繁体   English

一定时间后如何关闭窗口/活动

[英]How to close a window/activity after a certain amount of time

am writing an android application, it allow someone add two numbers and input the answer. 我正在编写一个android应用程序,它允许某人加两个数字并输入答案。 but I want this numbers to display for only 5 seconds and then a new number show up, if they input the correct or wrong answer, the timer reset and display new numbers.. i have written the code that does the random numbers and other just the timer am unable to do someone help please 但我希望此数字仅显示5秒钟,然后显示一个新数字,如果他们输入正确或错误的答案,则计时器会重置并显示新数字。.我已经编写了执行随机数和其他代码的代码计时器无法帮助别人,请

Using a Handler and Runnable should work for you but don't use an Anonymous runnable as they can cause memory leaks. 使用Handler和Runnable应该适合您,但不要使用Anonymous runnable,因为它们会导致内存泄漏。 Instead extend runnable into a static class and use removeCallbacks in onDestroy . 而是将runnable扩展为静态类,并在onDestroy使用removeCallbacks

Also you can use WeakReference as onDestroy is not guaranteed to be called so a WeakReference will allow GC to free up the memory if your activity gets killed 您也可以使用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();
        }

    }

}

You can use android.os.Handler class to do so, Like 您可以使用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.
 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
     }
  };

use timer.start(); 使用timer.start(); where you had to start the timer. 您必须在其中启动计时器的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM