java – Error creating thread inside a Handler

Question:

I need to delay one of the parts of my application for 5 seconds:

final Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // Encadeia trabalho serializado
        jobChain.append(new Job() {
            public void doJob(final OnChainItemListener itemListener) {
                // Obtém metadados do Artigo
                onlineArticle.get(idArticle, new HttpJsonObjectListener() {
                    public void onRequestCompleted(JSONObject object, Integer httpStatus, CharSequence msg) {
                        offlineArticle.save(object, new HttpJsonObjectListener() {
                            public void onRequestCompleted(JSONObject object, Integer httpStatus, CharSequence msg) {
                                Log.v(this.getClass().getName(), "Artigo salvo!");
                            }
                        }, null);

                        itemListener.onRequestCompleted(object, httpStatus, msg);
                    }
                }, defFail);
            }
        });

    }
};
new Handler().postDelayed(runnable, 5000);

I tried to implement it, but it turns out that all this is inside a handler and it gives me the following error:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

I read about it, that it would have to run in the main thread, but I'm not able to do it.

Answer:

I decided by doing the following:

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() {
                   // Ação a ser atrasada
                    handler.removeCallbacks(this);
                    Looper.myLooper().quit();
               }
            }, 2000);

            Looper.loop();
        }
    };
    thread.start();
}
Scroll to Top