How to get currently running applications in android ?

· 94 words · 1 minute read

Use this code in your app’s `src/MainActivity.kt’ file.

import android.app.ActivityManager
import android.app.ActivityManager.RunningTaskInfo
import android.content.Context
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.util.*
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val textView: TextView = findViewById(R.id.textView)
      val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
      val recentTasks: List<RunningTaskInfo> =
      Objects.requireNonNull(activityManager).getRunningTasks(Int.MAX_VALUE)
      for (i in recentTasks.indices) {
         textView.text = "Application executed: ${recentTasks[i].baseActivity!!.toShortString()}ID: ${recentTasks[i].id}"
      }
   }
}

Make sure you have a TextView with id textView in your XML layout.

All the currently running applications on your smartphone will be shown in the textview.

Share:
waffarx cash back