How to run a Runnable thread in Android at defined intervals?

后端 未结 11 1991
青春惊慌失措
青春惊慌失措 2020-11-22 02:50

I developed an application to display some text at defined intervals in the Android emulator screen. I am using the Handler class. Here is a snippet from my cod

11条回答
  •  失恋的感觉
    2020-11-22 03:26

    Kotlin

    private lateinit var runnable: Runnable
    override fun onCreate(savedInstanceState: Bundle?) {
        val handler = Handler()
        runnable = Runnable {
            // do your work
            handler.postDelayed(runnable, 2000)
        }
        handler.postDelayed(runnable, 2000)
    }
    

    Java

    Runnable runnable;
    Handler handler;
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                // do your work
                handler.postDelayed(this, 1000);
            }
        };
        handler.postDelayed(runnable, 1000);
    }
    

提交回复
热议问题