Search code examples
androidhandlerlooper

How can i handle my Looper in an OnClick method to run a function with delay?


I would like to be able to run my specific method in background through a looper in an on click event, is this the right way to do this?

myThread = new LooperThread();
    myThread.start();
    upload.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
        }
    });
    stop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myThread.handler.post(new Runnable() {
                @Override
                public void run() {
                    //my methods
                }
            });
        }
    });

And my Looper Class:

class LooperThread extends Thread {
    Handler handler;
    public void run() {
        Looper.prepare();
        handler = new Handler();
        Looper.loop();
    }
}

If it is, the problem is that in this way, i don't understand why the system don't recognize "handler" while i typing: "myThread.handler.post.." and run the methods.

Otherwise, can you help me on making this?

I am sorry if i made mistakes while making the question, but it's my first time here :)``


Solution

  • Welcome to Stack Overflow.

    I would like to be able to run my specific method in background through a looper in an on click event, is this the right way to do this?

    Your code works, but I couldn't say it's the right way to do it. Like @tynn mentioned, a HandlerThread might be a better option.

    If it is, the problem is that in this way, i don't understand why the system don't recognize "handler" while i typing: "myThread.handler.post.." and run the methods.

    Otherwise, can you help me on making this?

    If I understood your problem, it's an access issue. Your handler seems unaccessible since it's declared as package-private. You could make your handler visible this way:

    // Should this class be public or package-private?
    public class LooperThread extends Thread {
    
        private Handler handler;
    
        public Handler getHandler() {
            return handler;
        }
    
        // ...
    }
    

    And you will be able to reference the handler like this:

    myThread.getHandler().post(...);
    

    UPDATE

    You can delay a Runnable execution this way:

    // Delay execution of a Runnable task by 5000 milliseconds.
    myThread.getHandler().postDelayed(myDelayedRunnable, 5000);