David T.
David T.

Reputation: 23389

Android Is it safe to assume the "main/UI thread" ID is always 1?

I'm working on a jar file that gets included in other applications, and it has to be very robust.

in the jar, i have an object, say SomeView, which takes in an Android Context, tries to create a Handler object, and will touch views, so it needs to be initialized from the main thread. How can i guarantee 100% that they won't initialize my SomeView in the wrong thread?

such as:

public class SomeView {
    Handler mHandler;
    public SomeView(Context context) {
        mHandler = new Handler();
    }
}

i.e. will if (Thread.currentThread().getId() != 1) failSafely(); in the constructor work?

Upvotes: 1

Views: 792

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006964

How can i guarantee 100% that they won't initialize my SomeView in the wrong thread?

Wrap your code in a Runnable and use runOnUiThread() (on an Activity) or post() (on SomeView) to ensure that it is run on the main application thread.

i.e. will if (Thread.currentThread().getId() != 1) failSafely(); in the constructor work?

I certainly would not count on that.

Use Looper.getMainLooper().getThread() to get the Thread object that represents the main application thread. But, I'd just wrap the thread-sensitive blocks in Runnables and have those blocks run on the main application thread.

Upvotes: 3

Related Questions