यह उदाहरण दर्शाता है कि Kotlin में Handler और Runnable का उपयोग करके एक विधि को हर 10 सेकंड में कैसे चलाया जाए।
चरण 1 - नया प्रोजेक्ट बनाएं
Android Studio: File → New Project।
चरण 2 - 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"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="हर 10 सेकंड में एक विधि चल रही है"
android:textColor="@android:color/holo_orange_dark"
android:textSize="16sp"
android:textStyle="bold" />
</RelativeLayout>
चरण 3 - MainActivity.kt में आवधिक टास्क
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private val handler = Handler(Looper.getMainLooper())
private var runnable: Runnable? = null
private val delayMillis = 10000L // 10 सेकंड
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
}
override fun onResume() {
super.onResume()
startPeriodicTask()
}
override fun onPause() {
super.onPause()
stopPeriodicTask()
}
private fun startPeriodicTask() {
runnable = Runnable {
// यहां अपना आवधिक कार्य करें
Toast.makeText(this@MainActivity, "यह विधि हर 10 सेकंड में चलती है", Toast.LENGTH_SHORT).show()
// अगली बार के लिए पुनर्निर्धारित करें
handler.postDelayed(runnable!!, delayMillis)
}
handler.postDelayed(runnable!!, delayMillis)
}
private fun stopPeriodicTask() {
runnable?.let { handler.removeCallbacks(it) }
runnable = null
}
}
चरण 4 - AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.periodictask">
<application ...>
<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>
ऐप चलाएं
ऐप चलाएं। हर 10 सेकंड में एक टोस्ट संदेश "यह विधि हर 10 सेकंड में चलती है" दिखाई देगा। ऐप को पृष्ठभूमि में भेजने पर टास्क रुक जाएगा।
आधुनिक विकल्प (अनुशंसित): Kotlin Coroutines का उपयोग करें:
lifecycleScope.launch {
while (isActive) {
delay(10000)
// कार्य करें
}
}
यह जीवनचक्र-जागरूक है और लीक नहीं करता।