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?

David T.
  • 22,301
  • 23
  • 71
  • 123
  • 1
    Seems like a duplicate of http://stackoverflow.com/questions/2848575/how-to-detect-ui-thread-on-android – MTilsted Dec 15 '13 at 23:53
  • @MTilsted thanks for the find. i also wanted to know that in my particular case, if i only wanted to check the thread ID, as opposed to the object, it would work better. – David T. Dec 16 '13 at 00:09

1 Answers1

3

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • as for your first suggestion: The constructor for `SomeView` is `SomeView(Context context)`, which allows for a global application context, which doesn't have any notion of `runOnUiThread()` (only `Activity` does). and if i use `post()`, i'm assuming i have to use a `Handler` object? If the developer accidentally instantiated that `mHandler` from my constructor of `SomeView` on the wrong thread, it'll crash with "Can't create handler inside thread that has not called Looper.prepare()" – David T. Dec 15 '13 at 23:36
  • 1
    @DavidT.: "which allows for a global application context" -- do not create instances of a `View` using the `Application` context. "if i use post(), i'm assuming i have to use a Handler object?" -- `post()` is also a method on `View`. – CommonsWare Dec 15 '13 at 23:38
  • as for your second suggestion, may i assume that 100% of the time, even running on millions of regular Android stock devices, that`Thread.currentThread().getId() != Looper.getMainLooper().getThread().getId()` is the correct check? – David T. Dec 15 '13 at 23:38