Run Handler messages in a background thread

前端 未结 5 1956
失恋的感觉
失恋的感觉 2020-12-04 19:09

I want to run some Runnable in a background thread. I want to use Handler because it\'s convenient for delays. What I mean is

handler.post(runnable, delay);
         


        
5条回答
  •  抹茶落季
    2020-12-04 19:57

    You can try something like this

        private void createHandler() {
            Thread thread = new Thread() {
                public void run() {
                    Looper.prepare();
    
                    final Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                           // Do Work
                            handler.removeCallbacks(this);
                            Looper.myLooper().quit();
                       }
                    }, 2000);
    
                    Looper.loop();
                }
            };
            thread.start();
        }
    

提交回复
热议问题