runOnUiThread() কি?
runOnUiThread(Runnable action) একটি Activity মেথড যা ব্যাকগ্রাউন্ড থ্রেড থেকে UI থ্রেডে (মেইন থ্রেড) কোড এক্সিকিউট করার অনুমতি দেয়। অ্যান্ড্রয়েডে UI আপডেট শুধু মেইন থ্রেড থেকে করা যেতে পারে।
উদাহরণ: ব্যাকগ্রাউন্ড থ্রেড থেকে UI আপডেট
ধাপ ১: নতুন প্রজেক্ট তৈরি করুন
ধাপ ২: লেআউট XML (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/parent"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/runOn"
android:text="Run"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/text"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
ধাপ ৩: জাভা কোড (src/MainActivity.java)
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int i = 0;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = findViewById(R.id.text);
final Button runOn = findViewById(R.id.runOn);
runOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// নতুন ব্যাকগ্রাউন্ড থ্রেড শুরু করুন
new Thread(new Runnable() {
@Override
public void run() {
while (i++ < 1000) {
try {
// UI থ্রেডে কোড চালান
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText("#" + i);
}
});
Thread.sleep(300); // ৩০০ms विलম্ব
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
}
}
runOnUiThread() বনাম অন্যান্য পদ্ধতি
| পদ্ধতি | ব্যবহার | সুবিধা |
|---|---|---|
runOnUiThread() | Activity-এ সরাসরি | সरल, কনটেক্সট দরকার নেই |
Handler(Looper.getMainLooper()) | কहीं থেকেও | বিলম্বে এক্সিকিউট (postDelayed) |
View.post(Runnable) | View-এ আটকানো | View আটাচড থাকলে কাজ করে |
LiveData/Flow + observe | আধুনিক MVVM | লাইফসাইকেল-অware, নো লিক |
আধুনিক বিকল্প: Coroutines (Kotlin)
// Kotlin Coroutines
lifecycleScope.launch(Dispatchers.IO) {
for (i in 1..1000) {
delay(300)
withContext(Dispatchers.Main) {
textView.text = "#$i"
}
}
}
সতর্কতা
- অत्यधিক
runOnUiThreadকল UI ল্যাগ করতে পারে - ব্যাচ আপডেট করুন (৫০-১০০ms ইন্টারভ্যালে)
- অ্যাক্টিভিটি ডেস্ট্রয় হওয়ার পর কল না করুন (লিক হবে)
- isFinishing() বা isDestroyed() চেক করুন
সুরক্ষিত প্যাটার্ন
private void safeRunOnUiThread(Runnable action) {
if (!isFinishing() && !isDestroyed()) {
runOnUiThread(action);
}
}