Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle deprecated Handler in android [duplicate]

Previously this code worked perfect.

Now its is showing android.os.handler is deprecated.

private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
        break;
        }
    }

How can we resolve this issue.

like image 477
GNK Avatar asked Aug 21 '20 05:08

GNK


People also ask

How do I get rid of handler on android?

removecallback and handler = null; to cancel out the handle just to keep the code clean and make sure everything will be removed.

What is the replacement of handler in Kotlin?

The constructor new Handler(Looper. myLooper(), callback) is the exact alternative to the aforementioned deprecated methods. All these use the local thread to execute the background task.

How do I remove runnable from Handler?

Just use the removeCallbacks(Runnable r) method.

What is Handler postDelayed in android?

postDelayed(Runnable r, Object token, long delayMillis) Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. final void. removeCallbacks(Runnable r) Remove any pending posts of Runnable r that are in the message queue.


Video Answer


1 Answers

As mentioned by Mike in the comments, Handler is not deprecated. The way of creating an object of Handler using new Handler() is deprecated.

As per the documentation, using new Handler() can lead to bugs. So you should specify a looper for the handler explicitly. Looper must not be null.

Refer the code:

private final Handler mHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
        break;
        }
    }
like image 64
Alpha 1 Avatar answered Oct 17 '22 21:10

Alpha 1