{"id":1885,"date":"2014-11-13T11:57:46","date_gmt":"2014-11-13T06:27:46","guid":{"rendered":"http:\/\/codetheory.in\/?p=1885"},"modified":"2014-11-13T11:59:50","modified_gmt":"2014-11-13T06:29:50","slug":"checkdetect-whether-current-thread-uimain-thread-android","status":"publish","type":"post","link":"https:\/\/codetheory.in\/checkdetect-whether-current-thread-uimain-thread-android\/","title":{"rendered":"How to Check\/Detect Whether Current Thread is UI\/Main Thread or Not in Android"},"content":{"rendered":"

Checking whether the current thread is the UI\/Main thread or some other background thread is very easy. Here’s the code for it:<\/p>\n

<\/p>\n

\r\nif (Looper.myLooper() == Looper.getMainLooper()) {\r\n    \/\/ Current thread is the UI\/Main thread\r\n}        \r\n\r\n\/\/ Another approach\r\n\r\nif (Looper.getMainLooper().getThread() == Thread.currentThread()) {\r\n    \/\/ Current thread is the UI\/Main thread\r\n}\r\n<\/pre>\n

Bonus: <\/strong> If you’re in a thread other than the UI Thread and you want to execute a piece of code in the UI thread then you can make use of the runOnUiThread()<\/code><\/a> method.<\/p>\n

\r\n\/\/ Sample code from one of my Android applications\r\n\r\nrunOnUiThread(new Runnable(){\r\n    public void run() {\r\n        mChatMessages.clear();\r\n        mChatMessages.addAll(chatMessages);\r\n        mChatLogAdapter.notifyDataSetChanged();\r\n    }\r\n});\r\n<\/pre>\n

Hope that helps!<\/p>\n","protected":false},"excerpt":{"rendered":"

Checking whether the current thread is the UI\/Main thread or some other background thread is very easy. Here’s the code for it:<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[121,40],"tags":[105,89,137],"_links":{"self":[{"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/posts\/1885"}],"collection":[{"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/comments?post=1885"}],"version-history":[{"count":4,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/posts\/1885\/revisions"}],"predecessor-version":[{"id":1889,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/posts\/1885\/revisions\/1889"}],"wp:attachment":[{"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/media?parent=1885"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/categories?post=1885"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/tags?post=1885"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}