Kaloyan Roussev
Kaloyan Roussev

Reputation: 14711

How to throw NetworkOnMainThreadException?

I am creating some classes that do not implement threading logic but need to be used off the main thread, so I want to throw NetworkOnMainThreadException (or a similar one for DB operations) in their constructors. How do I do that? How do Android do that, can I find it somewhere in the source code?

Upvotes: 0

Views: 109

Answers (1)

Blackbelt
Blackbelt

Reputation: 157437

you could check the current's thread looper. E.g.

if (Looper.myLooper() == Looper.getMainLooper()) {
   throw new NetworkOnMainThreadException();
}

I would avoid it anyway. If I were in you I would document the method/class to clarify it has to be executed on an asynchronously

Upvotes: 2

Related Questions