UI Thread (Main Thread) Android में मुख्य thread होता है, जो UI components को handle करता है।
Run on UI Thread का मतलब है कि कोई भी code या task सीधे UI thread पर execute होगा।
UI updates जैसे TextView update, Button click events, Toast message, Dialog box open करना आदि केवल UI thread से ही किए जा सकते हैं।
यदि कोई heavy operation (network call, database query, file processing) UI thread पर execute किया जाए, तो app slow हो सकती है या ANR (Application Not Responding) error आ सकता है।
Android में runOnUiThread() method का उपयोग करके किसी भी background thread से UI thread पर task execute किया जा सकता है।
runOnUiThread(new Runnable() { @Override public void run() { textView.setText("Updated on UI Thread"); } });
Handler & Looper का उपयोग भी background thread से UI thread पर task भेजने के लिए किया जाता है।
java
new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { textView.setText("Updated using Handler"); } });
AsyncTask (Deprecated) का उपयोग background में task करने और उसके result को UI thread पर update करने के लिए किया जाता था।
Coroutines (Kotlin) और LiveData (MVVM Architecture) modern तरीके हैं, जिनसे UI thread को सुरक्षित तरीके से update किया जाता है।
अगर कोई long-running task UI thread पर execute होता है, तो पूरी application freeze हो सकती है, इसलिए background thread का उपयोग करना जरूरी है।
Proper thread management से app की performance और user experience बेहतर होता है।
नीचे एक simple example दिया गया है, जिसमें background thread से UI thread पर update किया जाता है।
Example: runOnUiThread() का उपयोग
java
public class MainActivity extends AppCompatActivity { private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); // Background thread शुरू करें new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(3000); // 3 सेकंड का delay } catch (InterruptedException e) { e.printStackTrace(); } // UI thread पर update करें runOnUiThread(new Runnable() { @Override public void run() { textView.setText("Updated on UI Thread!"); } }); } }).start(); } }
Code कैसे काम करता है?
हैलो दोस्तों! उम्मीद करता हूं आपको हमारा यह content/post पसंद आया होगा। अगर आपको हमारा ये content/post पसंद आई हो तो अपने दोस्तों के पास भी share करे। और अगर आपको कोई problem या कोई specific content हिन्दी में चाहिए है तो आप हमें नीचे दिए गए Email या whatsapp number के जरिए बता सकते है।
अगर आप CCC/diploma/polytechnic/MCA/BCA etc कर रहे है तो ये website स्पेशली आपके लिए ही है, जो student हिंदी में पढ़ाई करते है।
Email: deepanshuranjan8057@gmail.com
Whatsapp: +91 8057754706