can any Handler post to mainThread using Lopper.getMainLooper()

958 views Asked by At

Lets say i am in another thread that i created and in android i do the following:

//this is called from another thread (not mainTread)

new Handler(Lopper.getMainLooper()).post(new Runnable() {  
                    @Override
                    public void run() {
                        mAdapter.notifyDataSetChanged();
                    }
                });

am i to understand that the handler here is associated with the thread but since i'm using the mainThreads looper that it will send the runnable to the mainThreads message queue for processing ? and if thats true that any handler on any thread can accept another threads looper to post to it ? is that correct ?

Or is it that "new Handler(Lopper.getMainLopper())" makes this a mainThread handler ?

2

There are 2 answers

0
Taras  Mykhalchuk On BEST ANSWER

Yes, you've got it right.

  1. One thread can have only one unique Looper and can have many unique Handlers associated with it.
  2. A Handler gets implicitly associated with the thread that instantiates it via thread’s Looper. Also you are allowed to tie your Handler with any thread simply by passing its Looper in constructor.

I would recommend to take a glance at this article to grasp the better understanding of this issue.

2
Sujit Yadav On

try this ...replace Looper.getMainLooper() with context.getMainLooper().This should work .

new Handler(context.getMainLooper()).post(new Runnable() {  
                    @Override
                    public void run() {
                        mAdapter.notifyDataSetChanged();
                    }
                });