Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

java - Run Handler messages in a background thread

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);

Where runnable should be run in background Thread. Is it possible to create such Handler? Is there a "background" Looper somewhere or how can I create it?

P.S. I know how to do it with a custom class extends Thread but it requires a little more coding effort than doing it the handler way. So please don't post other solutions or something like

handler.post(new Runnable() {
    @Override
    public void run() {
        new Thread() {
            @Override
            public void run() {
                //action
            }
        }.start();
    }
});

I just wander if Handler can do it the "clean" way.

question from:https://stackoverflow.com/questions/18694732/run-handler-messages-in-a-background-thread

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can simply do this:

private Handler mHandler;

private HandlerThread mHandlerThread;

public void startHandlerThread(){
    mHandlerThread = new HandlerThread("HandlerThread");
    mHandlerThread.start();
    mHandler = new Handler(mHandlerThread.getLooper());
}

Then invoke with:

mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
          // Your task goes here
        }
    },1000);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...