user1748526
user1748526

Reputation: 464

Handler constructor stops a thread in Android

There's something weird happening. I can't show all the code, but situation is like this;

Runnable program = new Runnable() {
    @Override 
    public void run() {
        //This code is running
        new Handler();
        //This code not running
}};
new Thread(program).start();

Log shows nothing. Main thread is working good.

Upvotes: 0

Views: 241

Answers (2)

s.d
s.d

Reputation: 29436

Creating a Handler needs a Looper polling on that thread first. By the way, there's usually no need to create a Handler inside non UI threads. Create a Handler outside the runnable. An easier alternative is to use runOnUiThread() method.

Upvotes: 1

user1744056
user1744056

Reputation:

You should always declare Handler in UI thread.You need to provide the Handler with a Looper from some thread.E.g. from main UI thread:

 Handler mHandler = new Handler(Looper.getMainLooper());

Handler always runs in the Looper thread context. When you create another thread its context is different from the Looper. Right solution is to declare Handlers always in onCreate(), onStart() and onResume().

Upvotes: 2

Related Questions