Android-এ AsyncTask-এর জন্য টাইমআউট সেট করার পদ্ধতি
দ্রষ্টব্য: AsyncTask Android 11 (API 30) থেকে ডিপ্রিকেট করা হয়েছে। নতুন প্রজেক্টের জন্য Kotlin Coroutines, RxJava, বা ExecutorService ব্যবহার করা উচিত। এই টিউটোরিয়াল শুধুমাত্র লিগ্যাসি কোড বুঝার জন্য রাখা হয়েছে।
প্রয়োজনীয় ধাপসমূহ
ধাপ ১: নতুন প্রজেক্ট তৈরি করুন
Android Studio-তে File → New Project এ যান এবং প্রজেক্ট তৈরি করুন।
ধাপ ২: লেআউট ফাইল (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/enterTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:background="@android:drawable/editbox_background"
android:inputType="number"
android:hint="সেকেন্ডে সময় লিখুন" />
<Button
android:id="@+id/btnRun"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/enterTime"
android:layout_centerHorizontal="true"
android:text="AsyncTask চালান" />
</RelativeLayout>
ধাপ ৩: MainActivity.java-এ AsyncTask এবং টাইমআউট লজিক বাস্তবায়ন করুন
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
Button button;
EditText editTextTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btnRun);
editTextTime = findViewById(R.id.enterTime);
button.setOnClickListener(v -> {
String sleepTimeStr = editTextTime.getText().toString().trim();
if (!sleepTimeStr.isEmpty()) {
AsyncTaskRunner runner = new AsyncTaskRunner();
// টাইমআউটসহ এক্সিকিউট করুন
runner.execute(sleepTimeStr);
} else {
Toast.makeText(this, "দয়া করে সময় লিখুন", Toast.LENGTH_SHORT).show();
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private ProgressDialog progressDialog;
private static final long TIMEOUT_MILLIS = 10000; // ১০ সেকেন্ড টাইমআউট
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(
MainActivity.this,
"প্রগ্রেস",
"অপেক্ষা করুন: " + editTextTime.getText().toString() + " সেকেন্ড",
true, // indeterminate
false // cancelable
);
}
@Override
protected String doInBackground(String... params) {
publishProgress("AsyncTask শুরু হয়েছে...");
String resp;
try {
int time = Integer.parseInt(params[0]) * 1000; // মিলিসেকেন্ডে রূপান্তর
// টাইমআউট চেক: যদি অনুরোধ করা সময় টাইমআউটের চেয়ে বেশি হয়
if (time > TIMEOUT_MILLIS) {
return "ত্রুটি: অনুরোধ করা সময় (" + params[0] + "s) টাইমআউট সীমা (" + (TIMEOUT_MILLIS/1000) + "s) অতিক্রম করেছে";
}
Thread.sleep(time);
resp = "" + params[0] + " সেকেন্ডliğে স্লিপ সম্পন্ন";
} catch (Exception e) {
e.printStackTrace();
resp = "ত্রুটি: " + e.getMessage();
}
return resp;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Toast.makeText(MainActivity.this, values[0], Toast.LENGTH_SHORT).show();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
}
@Override
protected void onCancelled(String result) {
super.onCancelled(result);
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
Toast.makeText(MainActivity.this, "AsyncTask বাতিল করা হয়েছে: " + result, Toast.LENGTH_LONG).show();
}
}
}
AsyncTask-এ টাইমআউট বাস্তবায়নের ভিন্ন পদ্ধতিগুলি
পদ্ধতি ১:ExecutorService এবং Future ব্যবহার (প্রস্তাবিত লিগ্যাসি পদ্ধতি)
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
// ব্যাকগ্রাউন্ড টাস্ক
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// দীর্ঘমেয়াদী কাজ এখানে করুন
Thread.sleep(5000);
return "কাজ সম্পন্ন";
}
});
try {
// ৩ সেকেন্ড টাইমআউটসহ ফলাফল পান
String result = future.get(3, TimeUnit.SECONDS);
// সফল
} catch (TimeoutException e) {
future.cancel(true); // থ্রেড ইন্টারাপ্ট করুন
// টাইমআউট হ্যান্ডেল করুন
} catch (Exception e) {
// অন্যান্য এক্সেপশন
} finally {
executor.shutdown();
}
পদ্ধতি ২: Kotlin Coroutines + withTimeout (আধুনিক পদ্ধতি)
// build.gradle-এ
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
// কোডে
lifecycleScope.launch {
try {
val result = withTimeout(5000L) { // ৫ সেকেন্ড টাইমআউট
// সাসপেন্ড ফাংশন কল করুন
longRunningOperation()
}
// সফল
} catch (e: TimeoutCancellationException) {
// টাইমআউট - অটোমেটিক্যালি ক্যাঞ্চেল হয়
}
}
suspend fun longRunningOperation(): String = withContext(Dispatchers.IO) {
Thread.sleep(10000)
"সম্পন্ন"
}
পদ্ধতি ৩: RxJava Timeout Operator
// build.gradle-এ
implementation 'io.reactivex.rxjava3:rxandroid:3.1.0'
implementation 'io.reactivex.rxjava3:rxjava:3.1.0'
// কোডে
Single.fromCallable(() -> {
Thread.sleep(10000);
return "সম্পন্ন";
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.timeout(5, TimeUnit.SECONDS)
.subscribe(
result -> { /* সফল */ },
error -> { if (error instanceof TimeoutException) { /* টাইমআউট */ } }
);
ধাপ ৪: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
অ্যাপ্লিকেশন চালানোর পদ্ধতি
আপনার Android ডিভাইস কম্পিউটারের সাথে সংযুক্ত করুন। Android Studio-তে Run আইকনে ক্লিক করুন। EditText-এ সেকেন্ড সংখ্যা লিখুন (যেমন ৫) এবং "AsyncTask চালান" বাটনে ক্লিক করুন। প্রগ্রেস ডায়ালগ দেখাবে এবং কাজ শেষে ফলাফল দেখাবে।

