Question

I am confuse about the following two ways to initialize the Handler. What's the difference ?

1. First way:

class MyFirstActivity extends Activity {
    class Handler mHandler = new Handler();
    ...
}

2. Second way:

class MySecondActivity extends Activity {

    private MyHandler mHandler;

    @Oerride
    protected void onCreate(Bundle bundle) {
        mHandler = new MyHandler(getMainLooper());
    }

    private final class MyHandler extends Handler {
        public MyHandler(Looper looper) {
            super(looper, null, true);
        }
        ...
    }
}

Note: I know there is the documentation:

Handler() - Default constructor associates this handler with the Looper for the current thread.
If this thread does not have a looper, this handler won't be able to receive messages so an exception is thrown.
and
Handler(Looper looper) - Use the provided Looper instead of the default one.

It means I want to know more, like

  1. when quit, are there some special operations to do?

  2. Which way is better (or More efficient)?

Thanks~

Était-ce utile?

La solution

The Handler (Looper looper) constructor (second way) is used when creating Handler from threads, which do not have default looper, or when you want the handler to run actions on a different thread than your own.

In your "second way" example there is no need to use this type of constructor, the default one will do the same. And as the Activity constructor is invoked on the same thread as onCreate(..) method, two possible initializations ("first" and "second way") of Handler are totally equal.

UPD: make sure not to create inner Handler class.

Autres conseils

As per documentation here

Handler() - Default constructor associates this handler with the Looper for the current thread.

If this thread does not have a looper, this handler won't be able to receive messages so an exception is thrown.

and

Handler(Looper looper) - Use the provided Looper instead of the default one.

Here Looper is Class used to run a message loop for a thread. Check this

It's documented here. Basically second example explicitly tries to get app's main looper, while first one leaves this to the Handler's constructor:

Default constructor associates this handler with the Looper for the current thread.

Since your both classes are Activities, there's no difference in this particular case.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top